file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./partial_match/1/0x71E368Ed06814Bf35d4E663eFf946400a5BC8115/sources/Degrain.sol
|
approve token transfer to cover all possible scenarios add the liquidity
|
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
owner(),
block.timestamp
);
}
| 3,693,754 |
pragma solidity ^0.5.0;
import "./ERCStaking.sol";
import "./Checkpointing.sol";
import "./res/Autopetrified.sol";
import "./res/IsContract.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
contract Staking is Autopetrified, ERCStaking, ERCStakingHistory, IsContract {
using SafeMath for uint256;
using Checkpointing for Checkpointing.History;
using SafeERC20 for ERC20;
// todo: switch back to safetransfer?
// This changes all 'transfer' calls to safeTransfer
string private constant ERROR_TOKEN_NOT_CONTRACT = "STAKING_TOKEN_NOT_CONTRACT";
string private constant ERROR_AMOUNT_ZERO = "STAKING_AMOUNT_ZERO";
string private constant ERROR_TOKEN_TRANSFER = "STAKING_TOKEN_TRANSFER";
string private constant ERROR_NOT_ENOUGH_BALANCE = "STAKING_NOT_ENOUGH_BALANCE";
// standard - imitates relationship between Ether and Wei
uint8 private constant DECIMALS = 18;
// Default minimum stake
uint256 internal minStakeAmount = 0;
// Default maximum stake
uint256 internal maxStakeAmount = 0;
// Reward tracking info
uint256 internal currentClaimBlock;
uint256 internal currentClaimableAmount;
struct Account {
Checkpointing.History stakedHistory;
Checkpointing.History claimHistory;
}
ERC20 internal stakingToken;
mapping (address => Account) internal accounts;
Checkpointing.History internal totalStakedHistory;
address treasuryAddress;
address stakingOwnerAddress;
event StakeTransferred(
address indexed from,
uint256 amount,
address to
);
event Test(
uint256 test,
string msg);
event Claimed(
address claimaint,
uint256 amountClaimed
);
function initialize(address _stakingToken, address _treasuryAddress) external onlyInit {
require(isContract(_stakingToken), ERROR_TOKEN_NOT_CONTRACT);
initialized();
stakingToken = ERC20(_stakingToken);
treasuryAddress = _treasuryAddress;
// Initialize claim values to zero, disabling claim prior to initial funding
currentClaimBlock = 0;
currentClaimableAmount = 0;
// Default min stake amount is 100 AUD tokens
minStakeAmount = 100 * 10**uint256(DECIMALS);
// Default max stake amount is 100 million AUD tokens
maxStakeAmount = 100000000 * 10**uint256(DECIMALS);
}
/* External functions */
/**
* @notice Funds `_amount` of tokens from msg.sender into treasury stake
*/
function fundNewClaim(uint256 _amount) external isInitialized {
// TODO: Add additional require statements here...
// Stake tokens for msg.sender from treasuryAddress
// Transfer tokens from msg.sender to current contract
// Increase treasuryAddress stake value
_stakeFor(
treasuryAddress,
msg.sender,
_amount,
bytes(""));
// Update current claim information
currentClaimBlock = getBlockNumber();
currentClaimableAmount = totalStakedFor(treasuryAddress);
}
/**
* @notice Allows reward claiming for service providers
*/
function makeClaim() external isInitialized {
require(msg.sender != treasuryAddress, "Treasury cannot claim staking reward");
require(accounts[msg.sender].stakedHistory.history.length > 0, "Stake required to claim");
require(currentClaimBlock > 0, "Claim block must be initialized");
require(currentClaimableAmount > 0, "Claimable amount must be initialized");
if (accounts[msg.sender].claimHistory.history.length > 0) {
uint256 lastClaimedBlock = accounts[msg.sender].claimHistory.lastUpdated();
// Require a minimum block difference alloted to be ~1 week of blocks
// Note that a new claim funding after the latest claim for this staker overrides the minimum block difference
require(
lastClaimedBlock < currentClaimBlock,
"Minimum block difference not met");
}
uint256 claimBlockTotalStake = totalStakedHistory.get(currentClaimBlock);
uint256 treasuryStakeAtClaimBlock = accounts[treasuryAddress].stakedHistory.get(currentClaimBlock);
uint256 claimantStakeAtClaimBlock = accounts[msg.sender].stakedHistory.get(currentClaimBlock);
uint256 totalServiceProviderStakeAtClaimBlock = claimBlockTotalStake.sub(treasuryStakeAtClaimBlock);
uint256 claimedValue = (claimantStakeAtClaimBlock.mul(currentClaimableAmount)).div(totalServiceProviderStakeAtClaimBlock);
// Transfer value from treasury to claimant if >0 is claimed
if (claimedValue > 0) {
_transfer(treasuryAddress, msg.sender, claimedValue);
}
// Update claim history even if no value claimed
accounts[msg.sender].claimHistory.add64(getBlockNumber64(), claimedValue);
emit Claimed(msg.sender, claimedValue);
}
/**
* @notice Slashes `_amount` tokens from _slashAddress
* Controlled by treasury address
* @param _amount Number of tokens slashed
* @param _slashAddress address being slashed
*/
function slash(uint256 _amount, address _slashAddress) external isInitialized {
// restrict functionality
require(msg.sender == treasuryAddress, "Slashing functionality locked to treasury owner");
// unstaking 0 tokens is not allowed
require(_amount > 0, ERROR_AMOUNT_ZERO);
// transfer slashed funds to treasury address
// reduce stake balance for address being slashed
_transfer(_slashAddress, treasuryAddress, _amount);
}
/**
* @notice Sets caller for stake and unstake functions
* Controlled by treasury address
*/
function setStakingOwnerAddress(address _stakeCaller) external isInitialized {
require(msg.sender == treasuryAddress, "Slashing functionality locked to treasury owner");
stakingOwnerAddress = _stakeCaller;
}
/**
* @notice Sets the minimum stake possible
* Controlled by treasury
*/
// NOTE that _amounts are in wei throughout
function setMinStakeAmount(uint256 _amount) external isInitialized {
require(msg.sender == treasuryAddress, "Stake amount manipulation limited to treasury owner");
minStakeAmount = _amount;
}
/**
* @notice Sets the max stake possible
* Controlled by treasury
*/
function setMaxStakeAmount(uint256 _amount) external isInitialized {
require(msg.sender == treasuryAddress, "Stake amount manipulation limited to treasury owner");
maxStakeAmount = _amount;
}
/**
* @notice Stakes `_amount` tokens, transferring them from `msg.sender`
* @param _amount Number of tokens staked
* @param _data Used in Staked event, to add signalling information in more complex staking applications
*/
function stake(uint256 _amount, bytes calldata _data) external isInitialized {
require(msg.sender == stakingOwnerAddress, "Unauthorized staking operation");
_stakeFor(
msg.sender,
msg.sender,
_amount,
_data);
}
/**
* @notice Stakes `_amount` tokens, transferring them from caller, and assigns them to `_accountAddress`
* @param _accountAddress The final staker of the tokens
* @param _amount Number of tokens staked
* @param _data Used in Staked event, to add signalling information in more complex staking applications
*/
function stakeFor(address _accountAddress, uint256 _amount, bytes calldata _data) external isInitialized {
require(msg.sender == stakingOwnerAddress, "Unauthorized staking operation");
_stakeFor(
_accountAddress,
_accountAddress,
_amount,
_data);
}
/**
* @notice Unstakes `_amount` tokens, returning them to the user
* @param _amount Number of tokens staked
* @param _data Used in Unstaked event, to add signalling information in more complex staking applications
*/
function unstake(uint256 _amount, bytes calldata _data) external isInitialized {
// unstaking 0 tokens is not allowed
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(msg.sender, _amount, false);
// checkpoint total supply
_modifyTotalStaked(_amount, false);
// transfer tokens
stakingToken.safeTransfer(msg.sender, _amount);
emit Unstaked(
msg.sender,
_amount,
totalStakedFor(msg.sender),
_data);
}
/**
* @notice Unstakes `_amount` tokens, returning them to the desired account.
* @param _amount Number of tokens staked
* @param _data Used in Unstaked event, to add signalling information in more complex staking applications
*/
function unstakeFor(address _accountAddress, uint256 _amount, bytes calldata _data) external isInitialized {
require(msg.sender == stakingOwnerAddress, "Unauthorized staking operation");
// unstaking 0 tokens is not allowed
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(_accountAddress, _amount, false);
// checkpoint total supply
_modifyTotalStaked(_amount, false);
// transfer tokens
stakingToken.safeTransfer(_accountAddress, _amount);
emit Unstaked(
_accountAddress,
_amount,
totalStakedFor(_accountAddress),
_data);
}
/**
* @notice Get the token used by the contract for staking and locking
* @return The token used by the contract for staking and locking
*/
function token() external view isInitialized returns (address) {
return address(stakingToken);
}
/**
* @notice Check whether it supports history of stakes
* @return Always true
*/
function supportsHistory() external pure returns (bool) {
return true;
}
/**
* @notice Get last time `_accountAddress` modified its staked balance
* @param _accountAddress Account requesting for
* @return Last block number when account's balance was modified
*/
function lastStakedFor(address _accountAddress) external view isInitialized returns (uint256) {
return accounts[_accountAddress].stakedHistory.lastUpdated();
}
/**
* @notice Get last time `_accountAddress` claimed a staking reward
* @param _accountAddress Account requesting for
* @return Last block number when claim requested
*/
function lastClaimedFor(address _accountAddress) external view isInitialized returns (uint256) {
return accounts[_accountAddress].claimHistory.lastUpdated();
}
/**
* @notice Get info relating to current claim status
*/
function getClaimInfo() external view isInitialized returns (uint256, uint256) {
return (currentClaimableAmount, currentClaimBlock);
}
/**
* @notice Get the total amount of tokens staked by `_accountAddress` at block number `_blockNumber`
* @param _accountAddress Account requesting for
* @param _blockNumber Block number at which we are requesting
* @return The amount of tokens staked by the account at the given block number
*/
function totalStakedForAt(address _accountAddress, uint256 _blockNumber) external view returns (uint256) {
return accounts[_accountAddress].stakedHistory.get(_blockNumber);
}
/**
* @notice Get the total amount of tokens staked by all users at block number `_blockNumber`
* @param _blockNumber Block number at which we are requesting
* @return The amount of tokens staked at the given block number
*/
function totalStakedAt(uint256 _blockNumber) external view returns (uint256) {
return totalStakedHistory.get(_blockNumber);
}
/**
* @notice Return the minimum stake configuration
* @return min stake
*/
function getMinStakeAmount() external view returns (uint256) {
return minStakeAmount;
}
/**
* @notice Return the maximum stake configuration
* @return max stake
*/
function getMaxStakeAmount() external view returns (uint256) {
return maxStakeAmount;
}
/* Public functions */
/**
* @notice Get the amount of tokens staked by `_accountAddress`
* @param _accountAddress The owner of the tokens
* @return The amount of tokens staked by the given account
*/
function totalStakedFor(address _accountAddress) public view returns (uint256) {
// we assume it's not possible to stake in the future
return accounts[_accountAddress].stakedHistory.getLatestValue();
}
/**
* @notice Get the total amount of tokens staked by all users
* @return The total amount of tokens staked by all users
*/
function totalStaked() public view returns (uint256) {
// we assume it's not possible to stake in the future
return totalStakedHistory.getLatestValue();
}
/*
function multicall(bytes[] _calls) public {
for(uint i = 0; i < _calls.length; i++) {
require(address(this).delegatecall(_calls[i]), ERROR_MULTICALL_DELEGATECALL);
}
}
*/
/* Internal functions */
function _stakeFor(
address _stakeAccount,
address _transferAccount,
uint256 _amount,
bytes memory _data) internal
{
// staking 0 tokens is invalid
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, true);
// checkpoint total supply
_modifyTotalStaked(_amount, true);
// pull tokens into Staking contract
stakingToken.safeTransferFrom(_transferAccount, address(this), _amount);
emit Staked(
_stakeAccount,
_amount,
totalStakedFor(_stakeAccount),
_data);
}
function _modifyStakeBalance(address _accountAddress, uint256 _by, bool _increase) internal {
uint256 currentStake = totalStakedFor(_accountAddress);
uint256 newStake;
if (_increase) {
newStake = currentStake.add(_by);
} else {
newStake = currentStake.sub(_by);
}
// Confirm stake is within configured bounds for non-treasury addresses
if (_accountAddress != treasuryAddress) {
require(newStake <= maxStakeAmount, 'Maximum stake threshold exceeded');
require(newStake > minStakeAmount || newStake == 0, 'Minimum stake threshold exceeded');
}
// add new value to account history
accounts[_accountAddress].stakedHistory.add64(getBlockNumber64(), newStake);
}
function _modifyTotalStaked(uint256 _by, bool _increase) internal {
uint256 currentStake = totalStaked();
uint256 newStake;
if (_increase) {
newStake = currentStake.add(_by);
} else {
newStake = currentStake.sub(_by);
}
// add new value to total history
totalStakedHistory.add64(getBlockNumber64(), newStake);
}
function _transfer(address _from, address _to, uint256 _amount) internal {
// transferring 0 staked tokens is invalid
require(_amount > 0, ERROR_AMOUNT_ZERO);
// update stakes
_modifyStakeBalance(_from, _amount, false);
_modifyStakeBalance(_to, _amount, true);
emit StakeTransferred(_from,_amount, _to);
}
}
|
Get the total amount of tokens staked by all users at block number `_blockNumber` _blockNumber Block number at which we are requesting return The amount of tokens staked at the given block number/
|
function totalStakedAt(uint256 _blockNumber) external view returns (uint256) {
return totalStakedHistory.get(_blockNumber);
}
| 1,067,067 |
pragma solidity ^0.4.4;
import "zeppelin/contracts/SafeMath.sol";
import "zeppelin/contracts/ownership/Ownable.sol";
import "./PATToken.sol";
// This ICO contract has been inspired by the EOS one
// https://github.com/EOSIO/eos-token-distribution/blob/master/src/eos_sale.sol
contract ICOSale is Ownable {
using SafeMath for uint;
PATToken public token;
uint public endDate;
uint public startingAt;
// All ether received, by days
mapping (uint => uint) public dailyTotal;
// What each backer invested, by days
mapping (uint => mapping (address => uint)) public userInvests;
// Does the backer got its tokens?
mapping (uint => mapping (address => bool)) public userClaimed;
event Claimed(uint day, address backer, uint nbTokens);
event CollectedUnsold(address collecter, uint unsoldTokens);
event CollectedEth(address collecter, uint ethAmount);
function ICOSale(uint _nbDays, uint _startAt, address _tokenAddress) {
endDate = (now * 1 days) + _nbDays;
startingAt = _startAt;
token = PATToken(_tokenAddress);
}
function () payable {
var currentDay = now * 1 days;
// Check if campaign started
if (currentDay < startingAt) throw;
// Check if campaign is other
if (currentDay >= endDate) throw;
// Now, just save that for future claims
dailyTotal[currentDay] = dailyTotal[currentDay].add(msg.value);
userInvests[currentDay][msg.sender] = msg.value;
}
// Allow backers to get their tokens
function claimByDay(uint day) {
var currentDay = now * 1 days;
// Someone is claiming to early!
if (day > currentDay) throw;
// No need to continue if the total invested of the day is 0
if (dailyTotal[day] == 0) throw;
// Does the sender already claimed its tokens?
if (userClaimed[day][msg.sender]) throw;
var totalInvested = dailyTotal[day];
var senderInvested = userInvests[day][msg.sender];
var price = tokensByDay(day).div(totalInvested);
var nbTokens = price.mul(senderInvested);
userClaimed[day][msg.sender] = true;
// Reward backer
// No need to mint, the contract will own its PAT
token.transfer(msg.sender, nbTokens);
// Log that
Claimed(day, msg.sender, nbTokens);
}
// Convenient function to claim all the different days
function claimAll() {
var currentDay = now * 1 days;
// No need to loop if it is too early
if (currentDay < startingAt) throw;
for (uint day = startingAt; day < currentDay; day++) {
claimByDay(day);
}
}
// Return the amount of tokens available
function tokensByDay(uint day) returns (uint) {
var nbDays = day.sub(startingAt);
if (nbDays < 0 || day > endDate) return 0;
// We sell 2% of 42e9 the first two days, it means 1% a day
if (nbDays <= 2) return 420e6;
// First month: 8% of 42e9, (0.08/42e9)/30 = 112e6
if (nbDays <= 30) return 112e6;
// Next 24 months: 1% a month (420e6), 14e6 a day
if (nbDays <= 720) return 14e6;
}
// Allow the owner to get unsold tokens
function collectUnsold() onlyOwner {
// Is campaign over?
if (now * 1 days <= endDate) throw;
// Send unsold tokens
var balance = token.balanceOf(address(this));
token.transfer(owner, balance);
CollectedUnsold(owner, balance);
}
// allow owner to get its ETH, at any time
function collectEth() onlyOwner {
if (!owner.send(this.balance)) throw;
CollectedEth(owner, this.balance);
}
}
|
Return the amount of tokens available We sell 2% of 42e9 the first two days, it means 1% a day First month: 8% of 42e9, (0.08/42e9)/30 = 112e6 Next 24 months: 1% a month (420e6), 14e6 a day
|
function tokensByDay(uint day) returns (uint) {
var nbDays = day.sub(startingAt);
if (nbDays < 0 || day > endDate) return 0;
if (nbDays <= 2) return 420e6;
if (nbDays <= 30) return 112e6;
if (nbDays <= 720) return 14e6;
}
| 12,668,759 |
//SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
// Libraries / Interfaces
import "../interfaces/IBEP20.sol";
import "../utils/SafeBEP20.sol";
import "../utils/SafeMath.sol";
import "../helpers/Ownable.sol";
import "../utils/Utils360.sol";
// MLX Helpers
import "./MLXEvents.sol";
import "./MLXData.sol";
import "../tokens/bsc/imlx.sol";
import "../tokens/bsc/mlxpos.sol";
// MLX State Contracts
import "./states/govern.sol";
import "./states/limits.sol";
import "./states/info.sol";
contract MLXController is
Ownable,
MLXData,
MLXEvents,
MLXGovern,
MLXLimits,
MLXInfo
{
using SafeBEP20 for IBEP20;
using SafeMath for uint;
IMetaple internal mlx;
MLXPOS internal mlxpos;
// MLX Controller: Data Variables
uint256 public mlxPerBlock = 0.1 ether;
uint256 public totalAllocPoint = 0;
uint256 public startBlock;
uint256 public referralReward = 5;
uint256 internal _depositedMLX = 0;
// MLX Controller: Double Staking Protocol
uint internal stakingAt = 0;
uint internal xPool = 1;
uint internal xRewards = 2;
uint public xLocked = 14 days;
// MLX Controller: Modifiers
modifier onlyPoolAdder() {
require(_poolAdder == _msgSender(), appendADDR("MLXError:", _msgSender()," is not the pool owner"));
_;
}
modifier validatePoolByPid(uint256 _pid) {
require (_pid < poolInfo . length , "Pool does not exist") ;
_;
}
constructor (
address _mlx,
address _mlxpos,
uint _startBlock
) {
mlx = IMetaple(_mlx);
mlxpos = MLXPOS(_mlxpos);
_poolAdder = _msgSender();
startBlock = _startBlock;
// staking pool
_addPool(IBEP20(_mlx), 1000, startBlock, 0);
// pos pool
_addPool(IBEP20(_mlxpos), 2000, startBlock, 0);
totalAllocPoint = 3000;
_poolExists[address(_mlx)] = true;
_poolExists[address(_mlxpos)] = true;
}
// Setter Functions
function setXRewards(uint _rewards) external onlyPoolAdder {
require(_rewards <= 5 && _rewards > 0, "MLXController: not valid");
emit SetNewXRewards(xRewards, _rewards);
xRewards = _rewards;
}
function setXPool(uint _xpool) external onlyPoolAdder {
xPool = _xpool;
}
function setStakePool(uint stakePool) external onlyPoolAdder {
stakingAt = stakePool;
}
// Getter Functions
function getmlx() external view returns (IMetaple) {
return mlx;
}
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) {
return _to.sub(_from).mul(1);
}
function _getMLXPerBlock() internal view returns (uint256) {
return mlxPerBlock;
}
function getMLXPerBlock() external view returns (uint256) {
return _getMLXPerBlock();
}
function getRewards(address _referrer) external view returns (uint256, uint256) {
uint256 _farmRewards = _referrersFarm[_referrer];
uint256 _stakeRewards = _referrersStake[_referrer];
return (_farmRewards, _stakeRewards);
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
function checkReferral(uint256 _amount) internal view returns(uint256){
return _amount.sub(_amount.mul(referralReward).div(1e2));
}
// MLX Controller: Logic Functions
// Add New Pools - Only Operated by Pool Adder
function add( uint256 _allocPoint, IBEP20 _lpToken, bool _withUpdate ) external onlyPoolAdder {
require(!_poolExists[address(_lpToken)], "[!] Pool Already Exists");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accMLXPerShare: 0
})
);
_poolExists[address(_lpToken)] = true;
}
// Update the given pool's MLX allocation point. Can only be called by the owner.
function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate) external onlyPoolAdder validatePoolByPid(_pid) {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
if(_pid == stakingAt) {
poolInfo[xPool].allocPoint = _allocPoint.mul(xRewards);
}
}
// Update Functions
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public validatePoolByPid(_pid) {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (_pid == 0){
lpSupply = _depositedMLX;
}
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 mlxReward = multiplier.mul(_getMLXPerBlock()).mul(pool.allocPoint).div(totalAllocPoint);
mlx.mintMLX(address(mlxpos), mlxReward);
if (_devFee > 0) {
uint256 devFee = mlxReward.mul(_devFee).div(1e4);
mlx.mintMLX(_devAddress, devFee);
}
pool.accMLXPerShare = pool.accMLXPerShare.add(mlxReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// View function to see pending MLXs on frontend.
function pendingMLX(uint256 _pid, address _user) external validatePoolByPid(_pid) view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accMLXPerShare = pool.accMLXPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (_pid == 0){
lpSupply = _depositedMLX;
}
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 mlxReward = multiplier.mul(_getMLXPerBlock()).mul(pool.allocPoint).div(totalAllocPoint);
accMLXPerShare = accMLXPerShare.add(mlxReward.mul(1e12).div(lpSupply));
}
return checkReferral(user.amount.mul(accMLXPerShare).div(1e12).sub(user.rewardDebt));
}
// Initialize Pending Rewards with Referral Rewards
function initPending(address sender, uint256 pending, string memory which) internal returns (uint256) {
address referral = mlx.referrer(sender);
uint256 refRewards = pending.mul(referralReward).div(100);
uint256 pendingRewards = pending.sub(refRewards);
safeMLXTransfer(sender, pendingRewards);
if(referral != address(0)){
safeMLXTransfer(referral, refRewards);
if(compareStrings("farm", which)){
_referrersFarm[referral] = _referrersFarm[referral].add(refRewards);
}else {
_referrersStake[referral] = _referrersStake[referral].add(refRewards);
}
}else{
safeMLXTransfer(_defaultReferral, refRewards);
if(compareStrings("farm", which)){
_referrersFarm[_defaultReferral] = _referrersFarm[_defaultReferral].add(refRewards);
}else {
_referrersStake[_defaultReferral] = _referrersStake[_defaultReferral].add(refRewards);
}
}
return pendingRewards;
}
// Deposit LP tokens to MLX Controller for MLX allocation.
function deposit(uint256 _pid, uint256 _amount) external validatePoolByPid(_pid) {
require(startBlock <= block.number, "[+] Farming not started");
require (_pid != 0, "deposit MLX by stakinge");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accMLXPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0){
initPending(msg.sender, pending, "farm");
}
}
if (_amount > 0){
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user._lastInvested = block.timestamp;
user._blockInvested = block.number;
}
user.rewardDebt = user.amount.mul(pool.accMLXPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MLX Controller.
function withdraw(uint256 _pid, uint256 _amount) external validatePoolByPid(_pid) {
require (_pid != 0, "withdraw MLX by unstaking");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "MLXC: amount > staked");
updatePool(_pid);
if (_pid == xPool) {
require (
block.timestamp.sub(user._lastInvested) > xLocked, "[+] X Pool Locked"
);
}
uint256 pending = user.amount.mul(pool.accMLXPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0){
initPending(msg.sender, pending, "farm");
}
if(_amount > 0){
user.amount = user.amount.sub(_amount);
uint _withdrawFee = _withdrawalFee(_amount, user._lastInvested);
if(_withdrawFee > 0){
pool.lpToken.safeTransfer(_devAddress, _withdrawFee);
_amount = _amount.sub(_withdrawFee);
}
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accMLXPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Stake MLX tokens to MLX Controller
function enterStaking(uint256 _amount) external {
require(startBlock <= block.number, "[+] Staking not started");
PoolInfo storage pool = poolInfo[stakingAt];
UserInfo storage user = userInfo[stakingAt][msg.sender];
updatePool(stakingAt);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accMLXPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
initPending(msg.sender, pending, "Stake");
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user._lastInvested = block.timestamp;
user._blockInvested = block.number;
_depositedMLX = _depositedMLX.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accMLXPerShare).div(1e12);
mlxpos.mint(msg.sender, _amount);
emit Deposit(msg.sender, stakingAt, _amount);
}
// Withdraw MLX tokens from Staking.
function leaveStaking(uint256 _amount) external {
PoolInfo storage pool = poolInfo[stakingAt];
UserInfo storage user = userInfo[stakingAt][msg.sender];
require(user.amount >= _amount, "MLXC: amount > staked");
updatePool(stakingAt);
uint256 pending = user.amount.mul(pool.accMLXPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
initPending(msg.sender, pending, "Stake");
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
mlxpos.burn(msg.sender, _amount);
uint _withdrawFee = _withdrawalFee(_amount, user._lastInvested);
if(_withdrawFee > 0){
pool.lpToken.safeTransfer(_devAddress, _withdrawFee);
_amount = _amount.sub(_withdrawFee);
}
pool.lpToken.safeTransfer(address(msg.sender), _amount);
_depositedMLX = _depositedMLX.sub(_amount);
}
user.rewardDebt = user.amount.mul(pool.accMLXPerShare).div(1e12);
emit Withdraw(msg.sender, stakingAt, _amount);
}
// Withdraw without rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) external validatePoolByPid(_pid) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if(_pid == 0) {
mlxpos.burn(msg.sender, user.amount);
}
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Transfer generated rewards
function safeMLXTransfer(address _to, uint256 _amount) internal {
mlxpos.safeMLXTransfer(_to, _amount);
}
// MLX Controller: Governing Functions
function transferMLXOwner(address owner) external onlyOwner {
mlx.transferOwnership(owner);
}
function transferPOSOwner(address owner) external onlyOwner {
mlxpos.transferOwnership(owner);
}
}
|
Transfer generated rewards
|
function safeMLXTransfer(address _to, uint256 _amount) internal {
mlxpos.safeMLXTransfer(_to, _amount);
}
| 2,541,343 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @custom:security-contact [email protected]
contract PeaceForUkraine is ERC1155, Ownable {
// Token URIs tokenId => URI
mapping (uint => string) public _URIs;
struct Leaderboard {
address buyer;
uint amount;
}
Leaderboard[] leaderboard;
// Sale status
bool public saleIsActive = true;
// Minimal price of token
uint public minimalTokenPrice = 0.05 ether;
uint public soldItems = 0;
uint public totalFunds = 0;
mapping (uint => uint) public itemsStatistic;
uint public tokensCount = 12;
// Initialization
constructor() ERC1155("") {
// Preset of token URLs
setURI(1, "ipfs://QmXQan6aXNmrxdZJkaaHJifUuv5Qh3CaTfh9inKDySukgS/PeaceI.json");
setURI(2, "ipfs://QmXQan6aXNmrxdZJkaaHJifUuv5Qh3CaTfh9inKDySukgS/PeaceII.json");
setURI(3, "ipfs://QmXQan6aXNmrxdZJkaaHJifUuv5Qh3CaTfh9inKDySukgS/PeaceIII.json");
setURI(4, "ipfs://QmXQan6aXNmrxdZJkaaHJifUuv5Qh3CaTfh9inKDySukgS/PeaceIV.json");
setURI(5, "ipfs://QmXQan6aXNmrxdZJkaaHJifUuv5Qh3CaTfh9inKDySukgS/PeaceV.json");
setURI(6, "ipfs://QmXQan6aXNmrxdZJkaaHJifUuv5Qh3CaTfh9inKDySukgS/PeaceVI.json");
setURI(7, "ipfs://QmXQan6aXNmrxdZJkaaHJifUuv5Qh3CaTfh9inKDySukgS/PeaceVII.json");
setURI(8, "ipfs://QmXQan6aXNmrxdZJkaaHJifUuv5Qh3CaTfh9inKDySukgS/PeaceVIII.json");
setURI(9, "ipfs://QmXQan6aXNmrxdZJkaaHJifUuv5Qh3CaTfh9inKDySukgS/PeaceIX.json");
setURI(10,"ipfs://QmXQan6aXNmrxdZJkaaHJifUuv5Qh3CaTfh9inKDySukgS/PeaceX.json");
setURI(11,"ipfs://QmXQan6aXNmrxdZJkaaHJifUuv5Qh3CaTfh9inKDySukgS/PeaceXI.json");
setURI(12,"ipfs://QmXQan6aXNmrxdZJkaaHJifUuv5Qh3CaTfh9inKDySukgS/PeaceXII.json");
// Mint tokens to creators
for (uint i=1; i<=tokensCount; i++)
{
_mint(0x32ff88F42A804dfE2cEE38d67dB20f1eC589eF03, i, 1, "");
_mint(0x46E3ba081A56d157896406074DB47bDd8e0bD34e, i, 1, "");
itemsStatistic[i]+=2;
}
}
// Generate random number
function random(uint i)
private
view
returns (uint)
{
return uint(keccak256(abi.encodePacked(block.timestamp, block.difficulty, i)))%tokensCount+1;
}
// Close sales proces
function closeSales()
public
onlyOwner
{
saleIsActive = false;
}
// Setting minimal Token Price
function setMinimalTokenPrice(uint _price)
public
onlyOwner
{
minimalTokenPrice = _price;
}
// Add buyer to Leaderboard
function addToLeaderboard(address _buyer, uint _amount)
private
{
uint _index = 0;
for (uint i=0; i<leaderboard.length; i++) {
if (leaderboard[i].buyer == _buyer) {
_index = i+1;
}
}
if (_index == 0) {
leaderboard.push(Leaderboard(_buyer, _amount));
}
else {
leaderboard[_index-1].amount += _amount;
}
}
// Get Buyers count
function getBuyersCount()
public
view
returns (uint)
{
return leaderboard.length;
}
// Get Buyer by id
function getBuyer(uint _id)
public
view
returns (address, uint)
{
uint length = leaderboard.length;
if (_id < length) {
return (leaderboard[_id].buyer, leaderboard[_id].amount);
}
else {
return (address(0x00), uint(0));
}
}
// Set tokens count
function addToken(string memory _tokenURI)
public
onlyOwner
{
tokensCount++;
setURI(tokensCount, _tokenURI);
}
// Set token URL
function setURI(uint _id,string memory _newURI)
public
onlyOwner
{
_URIs[_id] = _newURI;
}
// Minting tokens
function mint(uint _amount)
public
payable
returns (uint[] memory)
{
require (saleIsActive == true, "PeaceForUkraine: Sales are not active");
require (msg.value >= _amount*minimalTokenPrice, "PeaceForUkraine: Not enough money");
uint[] memory _tokenIds = new uint[](_amount);
uint _tokenId;
for (uint i=1; i<=_amount; i++)
{
_tokenId = random(i);
_mint(msg.sender, _tokenId, 1, "");
soldItems++;
itemsStatistic[_tokenId]++;
_tokenIds[i-1] = _tokenId;
}
totalFunds += msg.value;
addToLeaderboard(msg.sender, msg.value);
return _tokenIds;
}
// Get URL of token
function uri(uint _id)
public
view
override(ERC1155)
returns (string memory)
{
return _URIs[_id];
}
/**
* @dev Withdraw of money from contract
*/
function withdraw(address _receiver)
public
onlyOwner
{
uint _balance = address(this).balance;
address payable receiver = payable(_receiver);
receiver.transfer(_balance);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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) (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/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// 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/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 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);
}
|
Withdraw of money from contract/
|
function withdraw(address _receiver)
public
onlyOwner
{
uint _balance = address(this).balance;
address payable receiver = payable(_receiver);
receiver.transfer(_balance);
}
| 1,165,887 |
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract Recoverable is Ownable {
/// @dev Empty constructor (for now)
function Recoverable() {
}
/// @dev This will be invoked by the owner, when owner wants to rescue tokens
/// @param token Token which will we rescue to the owner from the contract
function recoverTokens(ERC20Basic token) onlyOwner public {
token.transfer(owner, tokensToBeReturned(token));
}
/// @dev Interface function, can be overwritten by the superclass
/// @param token Token which balance we will check and return
/// @return The amount of tokens (in smallest denominator) the contract owns
function tokensToBeReturned(ERC20Basic token) public returns (uint) {
return token.balanceOf(this);
}
}
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* Safe unsigned safe math.
*
* https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli
*
* Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol
*
* Maintained here until merged to mainline zeppelin-solidity.
*
*/
library SafeMathLib {
function times(uint a, uint b) returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function minus(uint a, uint b) returns (uint) {
assert(b <= a);
return a - b;
}
function plus(uint a, uint b) returns (uint) {
uint c = a + b;
assert(c>=a);
return c;
}
}
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* Standard EIP-20 token with an interface marker.
*
* @notice Interface marker is used by crowdsale contracts to validate that addresses point a good token contract.
*
*/
contract StandardTokenExt is StandardToken, Recoverable {
/* Interface declaration */
function isToken() public constant returns (bool weAre) {
return true;
}
}
/**
* Hold tokens for a group investor of investors until the unlock date.
*
* After the unlock date the investor can claim their tokens.
*
* Steps
*
* - Prepare a spreadsheet for token allocation
* - Deploy this contract, with the sum to tokens to be distributed, from the owner account
* - Call setInvestor for all investors from the owner account using a local script and CSV input
* - Move tokensToBeAllocated in this contract using StandardToken.transfer()
* - Call lock from the owner account
* - Wait until the freeze period is over
* - After the freeze time is over investors can call claim() from their address to get their tokens
*
*/
contract TokenVault is Ownable, Recoverable {
using SafeMathLib for uint;
/** How many investors we have now */
uint public investorCount;
/** Sum from the spreadsheet how much tokens we should get on the contract. If the sum does not match at the time of the lock the vault is faulty and must be recreated.*/
uint public tokensToBeAllocated;
/** How many tokens investors have claimed so far */
uint public totalClaimed;
/** How many tokens our internal book keeping tells us to have at the time of lock() when all investor data has been loaded */
uint public tokensAllocatedTotal;
/** How much we have allocated to the investors invested */
mapping(address => uint) public balances;
/** How many tokens investors have claimed */
mapping(address => uint) public claimed;
/** When was the last claim by an investor **/
mapping(address => uint) public lastClaimedAt;
/** When our claim freeze is over (UNIX timestamp) */
uint public freezeEndsAt;
/** When this vault was locked (UNIX timestamp) */
uint public lockedAt;
/** defining the tap **/
uint public tokensPerSecond;
/** We can also define our own token, which will override the ICO one ***/
StandardTokenExt public token;
/** What is our current state.
*
* Loading: Investor data is being loaded and contract not yet locked
* Holding: Holding tokens for investors
* Distributing: Freeze time is over, investors can claim their tokens
*/
enum State{Unknown, Loading, Holding, Distributing}
/** We allocated tokens for investor */
event Allocated(address investor, uint value);
/** We distributed tokens to an investor */
event Distributed(address investors, uint count);
event Locked();
/**
* Create presale contract where lock up period is given days
*
* @param _owner Who can load investor data and lock
* @param _freezeEndsAt UNIX timestamp when the vault unlocks
* @param _token Token contract address we are distributing
* @param _tokensToBeAllocated Total number of tokens this vault will hold - including decimal multiplication
* @param _tokensPerSecond Define the tap: how many tokens we permit an user to withdraw per second, 0 to disable
*/
function TokenVault(address _owner, uint _freezeEndsAt, StandardTokenExt _token, uint _tokensToBeAllocated, uint _tokensPerSecond) {
owner = _owner;
// Invalid owner
if(owner == 0) {
throw;
}
token = _token;
// Check the address looks like a token contract
if(!token.isToken()) {
throw;
}
// Give argument
if(_freezeEndsAt == 0) {
throw;
}
// Sanity check on _tokensToBeAllocated
if(_tokensToBeAllocated == 0) {
throw;
}
if (_freezeEndsAt < now) {
freezeEndsAt = now;
} else {
freezeEndsAt = _freezeEndsAt;
}
tokensToBeAllocated = _tokensToBeAllocated;
tokensPerSecond = _tokensPerSecond;
}
/// @dev Add a presale participating allocation
function setInvestor(address investor, uint amount) public onlyOwner {
if(lockedAt > 0) {
// Cannot add new investors after the vault is locked
throw;
}
if(amount == 0) throw; // No empty buys
// Don't allow reset
if(balances[investor] > 0) {
throw;
}
balances[investor] = amount;
investorCount++;
tokensAllocatedTotal += amount;
Allocated(investor, amount);
}
/// @dev Lock the vault
/// - All balances have been loaded in correctly
/// - Tokens are transferred on this vault correctly
/// - Checks are in place to prevent creating a vault that is locked with incorrect token balances.
function lock() onlyOwner {
if(lockedAt > 0) {
throw; // Already locked
}
// Spreadsheet sum does not match to what we have loaded to the investor data
if(tokensAllocatedTotal != tokensToBeAllocated) {
throw;
}
// Do not lock the vault if the given tokens are not on this contract
if(token.balanceOf(address(this)) != tokensAllocatedTotal) {
throw;
}
lockedAt = now;
Locked();
}
/// @dev In the case locking failed, then allow the owner to reclaim the tokens on the contract.
function recoverFailedLock() onlyOwner {
if(lockedAt > 0) {
throw;
}
// Transfer all tokens on this contract back to the owner
token.transfer(owner, token.balanceOf(address(this)));
}
/// @dev Get the current balance of tokens in the vault
/// @return uint How many tokens there are currently in vault
function getBalance() public constant returns (uint howManyTokensCurrentlyInVault) {
return token.balanceOf(address(this));
}
/// @dev Check how many tokens "investor" can claim
/// @param investor Address of the investor
/// @return uint How many tokens the investor can claim now
function getCurrentlyClaimableAmount(address investor) public constant returns (uint claimableAmount) {
uint maxTokensLeft = balances[investor] - claimed[investor];
if (now < freezeEndsAt) {
return 0;
}
if (tokensPerSecond > 0) {
uint previousClaimAt = lastClaimedAt[investor];
uint maxClaim;
if (previousClaimAt == 0) {
previousClaimAt = freezeEndsAt;
}
maxClaim = (now - previousClaimAt) * tokensPerSecond;
if (maxClaim > maxTokensLeft) {
return maxTokensLeft;
} else {
return maxClaim;
}
} else {
return maxTokensLeft;
}
}
/// @dev Claim N bought tokens to the investor as the msg sender
function claim() {
address investor = msg.sender;
if(lockedAt == 0) {
throw; // We were never locked
}
if(now < freezeEndsAt) {
throw; // Trying to claim early
}
if(balances[investor] == 0) {
// Not our investor
throw;
}
uint amount = getCurrentlyClaimableAmount(investor);
require (amount > 0);
lastClaimedAt[investor] = now;
claimed[investor] += amount;
totalClaimed += amount;
token.transfer(investor, amount);
Distributed(investor, amount);
}
/// @dev This function is prototyped in Recoverable contract
function tokensToBeReturned(ERC20Basic tokenToClaim) public returns (uint) {
if (address(tokenToClaim) == address(token)) {
return getBalance().minus(tokensAllocatedTotal);
} else {
return tokenToClaim.balanceOf(this);
}
}
/// @dev Resolve the contract umambigious state
function getState() public constant returns(State) {
if(lockedAt == 0) {
return State.Loading;
} else if(now > freezeEndsAt) {
return State.Distributing;
} else {
return State.Holding;
}
}
}
|
Add a presale participating allocation Cannot add new investors after the vault is locked Don't allow reset
|
function setInvestor(address investor, uint amount) public onlyOwner {
if(lockedAt > 0) {
throw;
}
if(balances[investor] > 0) {
throw;
}
balances[investor] = amount;
investorCount++;
tokensAllocatedTotal += amount;
Allocated(investor, amount);
}
| 4,811,300 |
./full_match/1/0xE292B17018189aDAc3321E95494520F35859b9df/sources/contracts/pool/DittoPoolMain.sol
|
@inheritdoc OwnerTwoStep
|
function acceptOwnership() public override (IOwnerTwoStep, OwnerTwoStep) nonReentrant onlyPendingOwner {
if(_isPrivatePool) {
revert DittoPoolMainInvalidOwnerOperation();
}
super.acceptOwnership();
_lpNft.emitMetadataUpdateForAll();
}
| 16,496,951 |
pragma solidity >0.5.0;
/** @title Classic QuickSort. See https://blog.cotten.io/thinking-in-solidity-6670c06390a9 */
contract QuickSort {
function sort(uint[] memory data) public pure returns(uint[] memory) {
quickSort(data, int(0), int(data.length - 1));
return data;
}
/** @dev Classic quicksort sorting algorithm.
* @param arr array to be sorted
* @param left left-most index of array items needing. Array items to the left of left are already sorted.
* @param right right-most index of array of items needing sorting. Array items to the right of right are already sorted.
*
*/
function quickSort(uint[] memory arr, int left, int right) internal pure {
int i = left;
int j = right;
if (i==j) return;
uint pivot = arr[uint(left + (right - left) / 2)];
while (i <= j) {
while (arr[uint(i)] < pivot) i++;
while (pivot < arr[uint(j)]) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
}
|
Classic quicksort sorting algorithm. arr array to be sorted left left-most index of array items needing. Array items to the left of left are already sorted. right right-most index of array of items needing sorting. Array items to the right of right are already sorted./
|
function quickSort(uint[] memory arr, int left, int right) internal pure {
int i = left;
int j = right;
if (i==j) return;
uint pivot = arr[uint(left + (right - left) / 2)];
while (i <= j) {
while (arr[uint(i)] < pivot) i++;
while (pivot < arr[uint(j)]) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
| 12,585,914 |
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.1;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./interfaces/IRecipe.sol";
contract Oven is AccessControl {
using SafeERC20 for IERC20;
using Math for uint256;
bytes32 constant public BAKER_ROLE = keccak256(abi.encode("BAKER_ROLE"));
uint256 constant public MAX_FEE = 10 * 10**16; //10%
IERC20 public inputToken;
IERC20 public outputToken;
uint256 public roundSizeInputAmount;
IRecipe public recipe;
struct Round {
uint256 totalDeposited;
mapping(address => uint256) deposits;
uint256 totalBakedInput;
uint256 totalOutput;
}
struct ViewRound {
uint256 totalDeposited;
uint256 totalBakedInput;
uint256 totalOutput;
}
Round[] public rounds;
mapping(address => uint256[]) userRounds;
uint256 public fee = 0; //default 0% (10**16 == 1%)
address public feeReceiver;
event Deposit(address indexed from, address indexed to, uint256 amount);
event Withdraw(address indexed from, address indexed to, uint256 inputAmount, uint256 outputAmount);
event FeeReceiverUpdate(address indexed previousReceiver, address indexed newReceiver);
event FeeUpdate(uint256 previousFee, uint256 newFee);
event RecipeUpdate(address indexed oldRecipe, address indexed newRecipe);
event RoundSizeUpdate(uint256 oldRoundSize, uint256 newRoundSize);
modifier onlyBaker() {
require(hasRole(BAKER_ROLE, _msgSender()), "NOT_BAKER");
_;
}
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NOT_ADMIN");
_;
}
function initialize(address _inputToken, address _outputToken, uint256 _roundSizeInputAmount, address _recipe) external {
require(address(inputToken) == address(0), "Oven.initializer: Already initialized");
require(_inputToken != address(0), "INPUT_TOKEN_ZERO");
require(_outputToken != address(0), "OUTPUT_TOKEN_ZERO");
require(_recipe != address(0), "RECIPE_ZERO");
inputToken = IERC20(_inputToken);
outputToken = IERC20(_outputToken);
roundSizeInputAmount = _roundSizeInputAmount;
recipe = IRecipe(_recipe);
// create first empty round
rounds.push();
// approve input token
IERC20(_inputToken).safeApprove(_recipe, type(uint256).max);
//grant default admin role
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
//grant baker role
_setRoleAdmin(BAKER_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(BAKER_ROLE, _msgSender());
}
function deposit(uint256 _amount) external {
depositTo(_amount, _msgSender());
}
function depositTo(uint256 _amount, address _to) public {
IERC20 inputToken_ = inputToken;
inputToken_.safeTransferFrom(_msgSender(), address(this), _amount);
_depositTo(_amount, _to);
}
function _depositTo(uint256 _amount, address _to) internal {
// if amount is zero return early
if(_amount == 0) {
return;
}
uint256 roundSizeInputAmount_ = roundSizeInputAmount; //gas saving
uint256 currentRound = rounds.length - 1;
uint256 deposited = 0;
while(deposited < _amount) {
//if the current round does not exist create it
if(currentRound >= rounds.length) {
rounds.push();
}
//if the round is already partially baked create a new round
if(rounds[currentRound].totalBakedInput != 0) {
currentRound ++;
rounds.push();
}
Round storage round = rounds[currentRound];
uint256 roundDeposit = (_amount - deposited).min(roundSizeInputAmount_ - round.totalDeposited);
round.totalDeposited += roundDeposit;
round.deposits[_to] += roundDeposit;
deposited += roundDeposit;
// only push rounds we are actually in
if(roundDeposit != 0) {
pushUserRound(_to, currentRound);
}
// if full amount assigned to rounds break the loop
if(deposited == _amount) {
break;
}
currentRound ++;
}
emit Deposit(_msgSender(), _to, _amount);
}
function pushUserRound(address _to, uint256 _roundId) internal {
// only push when its not already added
if(userRounds[_to].length == 0 || userRounds[_to][userRounds[_to].length - 1] != _roundId) {
userRounds[_to].push(_roundId);
}
}
function withdraw(uint256 _roundsLimit) public {
withdrawTo(_msgSender(), _roundsLimit);
}
function withdrawTo(address _to, uint256 _roundsLimit) public {
uint256 inputAmount;
uint256 outputAmount;
uint256 userRoundsLength = userRounds[_msgSender()].length;
uint256 numRounds = userRoundsLength.min(_roundsLimit);
for(uint256 i = 0; i < numRounds; i ++) {
// start at end of array for efficient popping of elements
uint256 roundIndex = userRounds[_msgSender()][userRoundsLength - i - 1];
Round storage round = rounds[roundIndex];
//amount of input of user baked
uint256 bakedInput = round.deposits[_msgSender()] * round.totalBakedInput / round.totalDeposited;
//amount of output the user is entitled to
uint256 userRoundOutput;
if(bakedInput == 0) {
userRoundOutput = 0;
} else {
userRoundOutput = round.totalOutput * bakedInput / round.totalBakedInput;
}
// unbaked input
inputAmount += round.deposits[_msgSender()] - bakedInput;
//amount of output the user is entitled to
outputAmount += userRoundOutput;
round.totalDeposited -= round.deposits[_msgSender()] - bakedInput;
round.deposits[_msgSender()] = 0;
round.totalBakedInput -= bakedInput;
round.totalOutput -= userRoundOutput;
//pop of user round
userRounds[_msgSender()].pop();
}
if(inputAmount != 0) {
// handle rounding issues due to integer division inaccuracies
inputAmount = inputAmount.min(inputToken.balanceOf(address(this)));
inputToken.safeTransfer(_to, inputAmount);
}
if(outputAmount != 0) {
// handle rounding issues due to integer division inaccuracies
outputAmount = outputAmount.min(outputToken.balanceOf(address(this)));
outputToken.safeTransfer(_to, outputAmount);
}
emit Withdraw(_msgSender(), _to, inputAmount, outputAmount);
}
function bake(bytes calldata _data, uint256[] memory _rounds) external onlyBaker {
uint256 maxInputAmount;
//get input amount
for(uint256 i = 0; i < _rounds.length; i ++) {
// prevent round from being baked twice
if(i != 0) {
require(_rounds[i] > _rounds[i - 1], "Rounds out of order");
}
Round storage round = rounds[_rounds[i]];
maxInputAmount += (round.totalDeposited - round.totalBakedInput);
}
// subtract fee amount from input
uint256 maxInputAmountMinusFee = maxInputAmount * (10**18 - fee) / 10**18;
//bake
(uint256 inputUsed, uint256 outputAmount) = recipe.bake(address(inputToken), address(outputToken), maxInputAmountMinusFee, _data);
uint256 inputUsedRemaining = inputUsed;
for(uint256 i = 0; i < _rounds.length; i ++) {
Round storage round = rounds[_rounds[i]];
uint256 roundInputBaked = (round.totalDeposited - round.totalBakedInput).min(inputUsedRemaining);
// skip round if it is already baked
if(roundInputBaked == 0) {
continue;
}
uint256 roundInputBakedWithFee = roundInputBaked * 10**18 / (10**18 - fee);
uint256 roundOutputBaked = outputAmount * roundInputBaked / inputUsed;
round.totalBakedInput += roundInputBakedWithFee;
inputUsedRemaining -= roundInputBaked;
round.totalOutput += roundOutputBaked;
//sanity check
require(round.totalBakedInput <= round.totalDeposited, "Input sanity check failed");
}
uint256 feeAmount = (inputUsed * 10**18 / (10**18 - fee)) - inputUsed;
address feeReceiver_ = feeReceiver; //gas saving
if(feeAmount != 0) {
// if no fee receiver is set send it to the baker
if(feeReceiver == address(0)) {
feeReceiver_ = _msgSender();
}
inputToken.safeTransfer(feeReceiver_, feeAmount);
}
}
function setFee(uint256 _newFee) external onlyAdmin {
require(_newFee <= MAX_FEE, "INVALID_FEE");
emit FeeUpdate(fee, _newFee);
fee = _newFee;
}
function setRoundSize(uint256 _roundSize) external onlyAdmin {
emit RoundSizeUpdate(roundSizeInputAmount, _roundSize);
roundSizeInputAmount = _roundSize;
}
function setRecipe(address _recipe) external onlyAdmin {
emit RecipeUpdate(address(recipe), _recipe);
//revoke old approval
if(address(recipe) != address(0)) {
inputToken.approve(address(recipe), 0);
}
recipe = IRecipe(_recipe);
//set new approval
if(address(recipe) != address(0)) {
inputToken.approve(address(recipe), type(uint256).max);
}
}
function saveToken(address _token, address _to, uint256 _amount) external onlyAdmin {
IERC20(_token).transfer(_to, _amount);
}
function saveEth(address payable _to, uint256 _amount) external onlyAdmin {
_to.call{value: _amount}("");
}
function setFeeReceiver(address _feeReceiver) external onlyAdmin {
emit FeeReceiverUpdate(feeReceiver, _feeReceiver);
feeReceiver = _feeReceiver;
}
function roundInputBalanceOf(uint256 _round, address _of) public view returns(uint256) {
Round storage round = rounds[_round];
// if there are zero deposits the input balance of `_of` would be zero too
if(round.totalDeposited == 0) {
return 0;
}
uint256 bakedInput = round.deposits[_of] * round.totalBakedInput / round.totalDeposited;
return round.deposits[_of] - bakedInput;
}
function inputBalanceOf(address _of) public view returns(uint256) {
uint256 roundsCount = userRounds[_of].length;
uint256 balance;
for(uint256 i = 0; i < roundsCount; i ++) {
balance += roundInputBalanceOf(userRounds[_of][i], _of);
}
return balance;
}
function roundOutputBalanceOf(uint256 _round, address _of) public view returns(uint256) {
Round storage round = rounds[_round];
if(round.totalBakedInput == 0) {
return 0;
}
//amount of input of user baked
uint256 bakedInput = round.deposits[_of] * round.totalBakedInput / round.totalDeposited;
//amount of output the user is entitled to
uint256 userRoundOutput = round.totalOutput * bakedInput / round.totalBakedInput;
return userRoundOutput;
}
function outputBalanceOf(address _of) external view returns(uint256) {
uint256 roundsCount = userRounds[_of].length;
uint256 balance;
for(uint256 i = 0; i < roundsCount; i ++) {
balance += roundOutputBalanceOf(userRounds[_of][i], _of);
}
return balance;
}
function getUserRoundsCount(address _user) external view returns(uint256) {
return userRounds[_user].length;
}
function getRoundsCount() external view returns(uint256) {
return rounds.length;
}
// Gets all rounds. Might run out of gas after many rounds
function getRounds() external view returns (ViewRound[] memory) {
return getRoundsRange(0, rounds.length -1);
}
function getRoundsRange(uint256 _from, uint256 _to) public view returns(ViewRound[] memory) {
ViewRound[] memory result = new ViewRound[](_to - _from + 1);
for(uint256 i = _from; i <= _to; i ++) {
Round storage round = rounds[i];
result[i].totalDeposited = round.totalDeposited;
result[i].totalBakedInput = round.totalBakedInput;
result[i].totalOutput = round.totalOutput;
}
return result;
}
}
|
if amount is zero return earlyif the current round does not exist create itif the round is already partially baked create a new round only push rounds we are actually in if full amount assigned to rounds break the loop
|
function _depositTo(uint256 _amount, address _to) internal {
if(_amount == 0) {
return;
}
uint256 currentRound = rounds.length - 1;
uint256 deposited = 0;
while(deposited < _amount) {
if(currentRound >= rounds.length) {
rounds.push();
}
if(rounds[currentRound].totalBakedInput != 0) {
currentRound ++;
rounds.push();
}
Round storage round = rounds[currentRound];
uint256 roundDeposit = (_amount - deposited).min(roundSizeInputAmount_ - round.totalDeposited);
round.totalDeposited += roundDeposit;
round.deposits[_to] += roundDeposit;
deposited += roundDeposit;
if(roundDeposit != 0) {
pushUserRound(_to, currentRound);
}
if(deposited == _amount) {
break;
}
currentRound ++;
}
emit Deposit(_msgSender(), _to, _amount);
}
| 988,159 |
// SPDX-License-Identifier: MIT
// solhint-disable
/*
This is copied from OZ preset: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/release-v3.0.0/contracts/presets/ERC721PresetMinterPauserAutoId.sol
Alterations:
* Make the counter public, so that we can use it in our custom mint function
* Removed ERC721Burnable parent contract, but added our own custom burn function.
* Removed original "mint" function, because we have a custom one.
* Removed default initialization functions, because they set msg.sender as the owner, which
we do not want, because we use a deployer account, which is separate from the protocol owner.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Counters.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721Pausable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
/**
* @dev {ERC721} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
* - token ID and URI autogeneration
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to aother accounts
*/
contract ERC721PresetMinterPauserAutoIdUpgradeSafe is
Initializable,
ContextUpgradeSafe,
AccessControlUpgradeSafe,
ERC721PausableUpgradeSafe
{
using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
Counters.Counter public _tokenIdTracker;
/**
* @dev Pauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721PausableUpgradeSafe) {
super._beforeTokenTransfer(from, to, tokenId);
}
uint256[49] 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 "../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.6.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
import "../../Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721UpgradeSafe is Initializable, ContextUpgradeSafe, ERC165UpgradeSafe, 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 ^ 0xe985e9c ^ 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;
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;
// 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 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 override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @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 override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If a base URI is set (via {_setBaseURI}), it is added as a prefix to the
* token's own URI (via {_setTokenURI}).
*
* If there is a base URI but no token URI, the token's ID will be used as
* its URI when appending it to the base URI. This pattern for autogenerated
* token URIs can lead to large gas savings.
*
* .Examples
* |===
* |`_setBaseURI()` |`_setTokenURI()` |`tokenURI()`
* | ""
* | ""
* | ""
* | ""
* | "token.uri/123"
* | "token.uri/123"
* | "token.uri/"
* | "123"
* | "token.uri/123"
* | "token.uri/"
* | ""
* | "token.uri/<tokenId>"
* |===
*
* Requirements:
*
* - `tokenId` must exist.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).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(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, 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 returns (string memory) {
return _baseURI;
}
/**
* @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 override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.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 override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @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 virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(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 override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param operator operator address to set the approval
* @param approved representing the status of the approval to be set
*/
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 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 override 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 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 Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _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 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) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal 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 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 virtual {
address owner = ownerOf(tokenId);
_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 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 _transfer(address from, address to, uint256 tokenId) internal virtual {
require(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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: If all token IDs share a prefix (for example, if your URIs look like
* `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
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;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @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[41] private __gap;
}
pragma solidity ^0.6.0;
import "./ERC721.sol";
import "../../utils/Pausable.sol";
import "../../Initializable.sol";
/**
* @dev ERC721 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC721PausableUpgradeSafe is Initializable, ERC721UpgradeSafe, PausableUpgradeSafe {
function __ERC721Pausable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
}
function __ERC721Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
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;
/**
* @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.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 Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.2;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
pragma solidity ^0.6.2;
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 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
pragma solidity ^0.6.2;
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 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
pragma solidity ^0.6.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
pragma solidity ^0.6.0;
import "./IERC165.sol";
import "../Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165UpgradeSafe is Initializable, 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;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// 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 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;
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev 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) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(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(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(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
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);
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import "../external/ERC721PresetMinterPauserAutoId.sol";
import "../interfaces/IERC20withDec.sol";
import "../interfaces/ISeniorPool.sol";
import "../protocol/core/GoldfinchConfig.sol";
import "../protocol/core/ConfigHelper.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../library/StakingRewardsVesting.sol";
contract StakingRewards is ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20withDec;
using ConfigHelper for GoldfinchConfig;
using StakingRewardsVesting for StakingRewardsVesting.Rewards;
enum LockupPeriod {
SixMonths,
TwelveMonths,
TwentyFourMonths
}
struct StakedPosition {
// @notice Staked amount denominated in `stakingToken().decimals()`
uint256 amount;
// @notice Struct describing rewards owed with vesting
StakingRewardsVesting.Rewards rewards;
// @notice Multiplier applied to staked amount when locking up position
uint256 leverageMultiplier;
// @notice Time in seconds after which position can be unstaked
uint256 lockedUntil;
}
/* ========== EVENTS =================== */
event RewardsParametersUpdated(
address indexed who,
uint256 targetCapacity,
uint256 minRate,
uint256 maxRate,
uint256 minRateAtPercent,
uint256 maxRateAtPercent
);
event TargetCapacityUpdated(address indexed who, uint256 targetCapacity);
event VestingScheduleUpdated(address indexed who, uint256 vestingLength);
event MinRateUpdated(address indexed who, uint256 minRate);
event MaxRateUpdated(address indexed who, uint256 maxRate);
event MinRateAtPercentUpdated(address indexed who, uint256 minRateAtPercent);
event MaxRateAtPercentUpdated(address indexed who, uint256 maxRateAtPercent);
event LeverageMultiplierUpdated(address indexed who, LockupPeriod lockupPeriod, uint256 leverageMultiplier);
/* ========== STATE VARIABLES ========== */
uint256 private constant MULTIPLIER_DECIMALS = 1e18;
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
GoldfinchConfig public config;
/// @notice The block timestamp when rewards were last checkpointed
uint256 public lastUpdateTime;
/// @notice Accumulated rewards per token at the last checkpoint
uint256 public accumulatedRewardsPerToken;
/// @notice Total rewards available for disbursement at the last checkpoint, denominated in `rewardsToken()`
uint256 public rewardsAvailable;
/// @notice StakedPosition tokenId => accumulatedRewardsPerToken at the position's last checkpoint
mapping(uint256 => uint256) public positionToAccumulatedRewardsPerToken;
/// @notice Desired supply of staked tokens. The reward rate adjusts in a range
/// around this value to incentivize staking or unstaking to maintain it.
uint256 public targetCapacity;
/// @notice The minimum total disbursed rewards per second, denominated in `rewardsToken()`
uint256 public minRate;
/// @notice The maximum total disbursed rewards per second, denominated in `rewardsToken()`
uint256 public maxRate;
/// @notice The percent of `targetCapacity` at which the reward rate reaches `maxRate`.
/// Represented with `MULTIPLIER_DECIMALS`.
uint256 public maxRateAtPercent;
/// @notice The percent of `targetCapacity` at which the reward rate reaches `minRate`.
/// Represented with `MULTIPLIER_DECIMALS`.
uint256 public minRateAtPercent;
/// @notice The duration in seconds over which rewards vest
uint256 public vestingLength;
/// @dev Supply of staked tokens, excluding leverage due to lock-up boosting, denominated in
/// `stakingToken().decimals()`
uint256 public totalStakedSupply;
/// @dev Supply of staked tokens, including leverage due to lock-up boosting, denominated in
/// `stakingToken().decimals()`
uint256 private totalLeveragedStakedSupply;
/// @dev A mapping from lockup periods to leverage multipliers used to boost rewards.
/// See `stakeWithLockup`.
mapping(LockupPeriod => uint256) private leverageMultipliers;
/// @dev NFT tokenId => staked position
mapping(uint256 => StakedPosition) public positions;
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) external initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained("Goldfinch V2 LP Staking Tokens", "GFI-V2-LPS");
__ERC721Pausable_init_unchained();
__AccessControl_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(OWNER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
config = _config;
vestingLength = 365 days;
// Set defaults for leverage multipliers (no boosting)
leverageMultipliers[LockupPeriod.SixMonths] = MULTIPLIER_DECIMALS; // 1x
leverageMultipliers[LockupPeriod.TwelveMonths] = MULTIPLIER_DECIMALS; // 1x
leverageMultipliers[LockupPeriod.TwentyFourMonths] = MULTIPLIER_DECIMALS; // 1x
}
/* ========== VIEWS ========== */
/// @notice Returns the staked balance of a given position token
/// @param tokenId A staking position token ID
/// @return Amount of staked tokens denominated in `stakingToken().decimals()`
function stakedBalanceOf(uint256 tokenId) external view returns (uint256) {
return positions[tokenId].amount;
}
/// @notice The address of the token being disbursed as rewards
function rewardsToken() public view returns (IERC20withDec) {
return config.getGFI();
}
/// @notice The address of the token that can be staked
function stakingToken() public view returns (IERC20withDec) {
return config.getFidu();
}
/// @notice The additional rewards earned per token, between the provided time and the last
/// time rewards were checkpointed, given the prevailing `rewardRate()`. This amount is limited
/// by the amount of rewards that are available for distribution; if there aren't enough
/// rewards in the balance of this contract, then we shouldn't be giving them out.
/// @return Amount of rewards denominated in `rewardsToken().decimals()`.
function additionalRewardsPerTokenSinceLastUpdate(uint256 time) internal view returns (uint256) {
require(time >= lastUpdateTime, "Invalid end time for range");
if (totalLeveragedStakedSupply == 0) {
return 0;
}
uint256 rewardsSinceLastUpdate = Math.min(time.sub(lastUpdateTime).mul(rewardRate()), rewardsAvailable);
uint256 additionalRewardsPerToken = rewardsSinceLastUpdate.mul(stakingTokenMantissa()).div(
totalLeveragedStakedSupply
);
// Prevent perverse, infinite-mint scenario where totalLeveragedStakedSupply is a fraction of a token.
// Since it's used as the denominator, this could make additionalRewardPerToken larger than the total number
// of tokens that should have been disbursed in the elapsed time. The attacker would need to find
// a way to reduce totalLeveragedStakedSupply while maintaining a staked position of >= 1.
// See: https://twitter.com/Mudit__Gupta/status/1409463917290557440
if (additionalRewardsPerToken > rewardsSinceLastUpdate) {
return 0;
}
return additionalRewardsPerToken;
}
/// @notice Returns accumulated rewards per token up to the current block timestamp
/// @return Amount of rewards denominated in `rewardsToken().decimals()`
function rewardPerToken() public view returns (uint256) {
uint256 additionalRewardsPerToken = additionalRewardsPerTokenSinceLastUpdate(block.timestamp);
return accumulatedRewardsPerToken.add(additionalRewardsPerToken);
}
/// @notice Returns rewards earned by a given position token from its last checkpoint up to the
/// current block timestamp.
/// @param tokenId A staking position token ID
/// @return Amount of rewards denominated in `rewardsToken().decimals()`
function earnedSinceLastCheckpoint(uint256 tokenId) public view returns (uint256) {
StakedPosition storage position = positions[tokenId];
uint256 leveredAmount = positionToLeveredAmount(position);
return
leveredAmount.mul(rewardPerToken().sub(positionToAccumulatedRewardsPerToken[tokenId])).div(
stakingTokenMantissa()
);
}
/// @notice Returns the rewards claimable by a given position token at the most recent checkpoint, taking into
/// account vesting schedule.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function claimableRewards(uint256 tokenId) public view returns (uint256 rewards) {
return positions[tokenId].rewards.claimable();
}
/// @notice Returns the rewards that will have vested for some position with the given params.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function totalVestedAt(
uint256 start,
uint256 end,
uint256 time,
uint256 grantedAmount
) external pure returns (uint256 rewards) {
return StakingRewardsVesting.totalVestedAt(start, end, time, grantedAmount);
}
/// @notice Number of rewards, in `rewardsToken().decimals()`, to disburse each second
function rewardRate() internal view returns (uint256) {
// The reward rate can be thought of as a piece-wise function:
//
// let intervalStart = (maxRateAtPercent * targetCapacity),
// intervalEnd = (minRateAtPercent * targetCapacity),
// x = totalStakedSupply
// in
// if x < intervalStart
// y = maxRate
// if x > intervalEnd
// y = minRate
// else
// y = maxRate - (maxRate - minRate) * (x - intervalStart) / (intervalEnd - intervalStart)
//
// See an example here:
// solhint-disable-next-line max-line-length
// https://www.wolframalpha.com/input/?i=Piecewise%5B%7B%7B1000%2C+x+%3C+50%7D%2C+%7B100%2C+x+%3E+300%7D%2C+%7B1000+-+%281000+-+100%29+*+%28x+-+50%29+%2F+%28300+-+50%29+%2C+50+%3C+x+%3C+300%7D%7D%5D
//
// In that example:
// maxRateAtPercent = 0.5, minRateAtPercent = 3, targetCapacity = 100, maxRate = 1000, minRate = 100
uint256 intervalStart = targetCapacity.mul(maxRateAtPercent).div(MULTIPLIER_DECIMALS);
uint256 intervalEnd = targetCapacity.mul(minRateAtPercent).div(MULTIPLIER_DECIMALS);
uint256 x = totalStakedSupply;
// Subsequent computation would overflow
if (intervalEnd <= intervalStart) {
return 0;
}
if (x < intervalStart) {
return maxRate;
}
if (x > intervalEnd) {
return minRate;
}
return maxRate.sub(maxRate.sub(minRate).mul(x.sub(intervalStart)).div(intervalEnd.sub(intervalStart)));
}
function positionToLeveredAmount(StakedPosition storage position) internal view returns (uint256) {
return toLeveredAmount(position.amount, position.leverageMultiplier);
}
function toLeveredAmount(uint256 amount, uint256 leverageMultiplier) internal pure returns (uint256) {
return amount.mul(leverageMultiplier).div(MULTIPLIER_DECIMALS);
}
function stakingTokenMantissa() internal view returns (uint256) {
return uint256(10)**stakingToken().decimals();
}
/// @notice The amount of rewards currently being earned per token per second. This amount takes into
/// account how many rewards are actually available for disbursal -- unlike `rewardRate()` which does not.
/// This function is intended for public consumption, to know the rate at which rewards are being
/// earned, and not as an input to the mutative calculations in this contract.
/// @return Amount of rewards denominated in `rewardsToken().decimals()`.
function currentEarnRatePerToken() public view returns (uint256) {
uint256 time = block.timestamp == lastUpdateTime ? block.timestamp + 1 : block.timestamp;
uint256 elapsed = time.sub(lastUpdateTime);
return additionalRewardsPerTokenSinceLastUpdate(time).div(elapsed);
}
/// @notice The amount of rewards currently being earned per second, for a given position. This function
/// is intended for public consumption, to know the rate at which rewards are being earned
/// for a given position, and not as an input to the mutative calculations in this contract.
/// @return Amount of rewards denominated in `rewardsToken().decimals()`.
function positionCurrentEarnRate(uint256 tokenId) external view returns (uint256) {
StakedPosition storage position = positions[tokenId];
uint256 leveredAmount = positionToLeveredAmount(position);
return currentEarnRatePerToken().mul(leveredAmount).div(stakingTokenMantissa());
}
/* ========== MUTATIVE FUNCTIONS ========== */
/// @notice Stake `stakingToken()` to earn rewards. When you call this function, you'll receive an
/// an NFT representing your staked position. You can present your NFT to `getReward` or `unstake`
/// to claim rewards or unstake your tokens respectively. Rewards vest over a schedule.
/// @dev This function checkpoints rewards.
/// @param amount The amount of `stakingToken()` to stake
function stake(uint256 amount) external nonReentrant whenNotPaused updateReward(0) {
_stakeWithLockup(msg.sender, msg.sender, amount, 0, MULTIPLIER_DECIMALS);
}
/// @notice Stake `stakingToken()` and lock your position for a period of time to boost your rewards.
/// When you call this function, you'll receive an an NFT representing your staked position.
/// You can present your NFT to `getReward` or `unstake` to claim rewards or unstake your tokens
/// respectively. Rewards vest over a schedule.
///
/// A locked position's rewards are boosted using a multiplier on the staked balance. For example,
/// if I lock 100 tokens for a 2x multiplier, my rewards will be calculated as if I staked 200 tokens.
/// This mechanism is similar to curve.fi's CRV-boosting vote-locking. Locked positions cannot be
/// unstaked until after the position's lockedUntil timestamp.
/// @dev This function checkpoints rewards.
/// @param amount The amount of `stakingToken()` to stake
/// @param lockupPeriod The period over which to lock staked tokens
function stakeWithLockup(uint256 amount, LockupPeriod lockupPeriod)
external
nonReentrant
whenNotPaused
updateReward(0)
{
uint256 lockDuration = lockupPeriodToDuration(lockupPeriod);
uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod);
uint256 lockedUntil = block.timestamp.add(lockDuration);
_stakeWithLockup(msg.sender, msg.sender, amount, lockedUntil, leverageMultiplier);
}
/// @notice Deposit to SeniorPool and stake your shares in the same transaction.
/// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit
/// will be staked.
function depositAndStake(uint256 usdcAmount) public nonReentrant whenNotPaused updateReward(0) {
uint256 fiduAmount = depositToSeniorPool(usdcAmount);
uint256 lockedUntil = 0;
uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS);
emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS);
}
function depositToSeniorPool(uint256 usdcAmount) internal returns (uint256 fiduAmount) {
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
IERC20withDec usdc = config.getUSDC();
usdc.safeTransferFrom(msg.sender, address(this), usdcAmount);
ISeniorPool seniorPool = config.getSeniorPool();
usdc.safeIncreaseAllowance(address(seniorPool), usdcAmount);
return seniorPool.deposit(usdcAmount);
}
/// @notice Identical to `depositAndStake`, except it allows for a signature to be passed that permits
/// this contract to move funds on behalf of the user.
/// @param usdcAmount The amount of USDC to deposit
/// @param v secp256k1 signature component
/// @param r secp256k1 signature component
/// @param s secp256k1 signature component
function depositWithPermitAndStake(
uint256 usdcAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s);
depositAndStake(usdcAmount);
}
/// @notice Deposit to the `SeniorPool` and stake your shares with a lock-up in the same transaction.
/// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit
/// will be staked.
/// @param lockupPeriod The period over which to lock staked tokens
function depositAndStakeWithLockup(uint256 usdcAmount, LockupPeriod lockupPeriod)
public
nonReentrant
whenNotPaused
updateReward(0)
{
uint256 fiduAmount = depositToSeniorPool(usdcAmount);
uint256 lockDuration = lockupPeriodToDuration(lockupPeriod);
uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod);
uint256 lockedUntil = block.timestamp.add(lockDuration);
uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, leverageMultiplier);
emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, leverageMultiplier);
}
function lockupPeriodToDuration(LockupPeriod lockupPeriod) internal pure returns (uint256 lockDuration) {
if (lockupPeriod == LockupPeriod.SixMonths) {
return 365 days / 2;
} else if (lockupPeriod == LockupPeriod.TwelveMonths) {
return 365 days;
} else if (lockupPeriod == LockupPeriod.TwentyFourMonths) {
return 365 days * 2;
} else {
revert("unsupported LockupPeriod");
}
}
/// @notice Get the leverage multiplier used to boost rewards for a given lockup period.
/// See `stakeWithLockup`. The leverage multiplier is denominated in `MULTIPLIER_DECIMALS`.
function getLeverageMultiplier(LockupPeriod lockupPeriod) public view returns (uint256) {
uint256 leverageMultiplier = leverageMultipliers[lockupPeriod];
require(leverageMultiplier > 0, "unsupported LockupPeriod");
return leverageMultiplier;
}
/// @notice Identical to `depositAndStakeWithLockup`, except it allows for a signature to be passed that permits
/// this contract to move funds on behalf of the user.
/// @param usdcAmount The amount of USDC to deposit
/// @param lockupPeriod The period over which to lock staked tokens
/// @param v secp256k1 signature component
/// @param r secp256k1 signature component
/// @param s secp256k1 signature component
function depositWithPermitAndStakeWithLockup(
uint256 usdcAmount,
LockupPeriod lockupPeriod,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s);
depositAndStakeWithLockup(usdcAmount, lockupPeriod);
}
function _stakeWithLockup(
address staker,
address nftRecipient,
uint256 amount,
uint256 lockedUntil,
uint256 leverageMultiplier
) internal returns (uint256 tokenId) {
require(amount > 0, "Cannot stake 0");
_tokenIdTracker.increment();
tokenId = _tokenIdTracker.current();
// Ensure we snapshot accumulatedRewardsPerToken for tokenId after it is available
// We do this before setting the position, because we don't want `earned` to (incorrectly) account for
// position.amount yet. This is equivalent to using the updateReward(msg.sender) modifier in the original
// synthetix contract, where the modifier is called before any staking balance for that address is recorded
_updateReward(tokenId);
positions[tokenId] = StakedPosition({
amount: amount,
rewards: StakingRewardsVesting.Rewards({
totalUnvested: 0,
totalVested: 0,
totalPreviouslyVested: 0,
totalClaimed: 0,
startTime: block.timestamp,
endTime: block.timestamp.add(vestingLength)
}),
leverageMultiplier: leverageMultiplier,
lockedUntil: lockedUntil
});
_mint(nftRecipient, tokenId);
uint256 leveredAmount = positionToLeveredAmount(positions[tokenId]);
totalLeveragedStakedSupply = totalLeveragedStakedSupply.add(leveredAmount);
totalStakedSupply = totalStakedSupply.add(amount);
// Staker is address(this) when using depositAndStake or other convenience functions
if (staker != address(this)) {
stakingToken().safeTransferFrom(staker, address(this), amount);
}
emit Staked(nftRecipient, tokenId, amount, lockedUntil, leverageMultiplier);
return tokenId;
}
/// @notice Unstake an amount of `stakingToken()` associated with a given position and transfer to msg.sender.
/// Unvested rewards will be forfeited, but remaining staked amount will continue to accrue rewards.
/// Positions that are still locked cannot be unstaked until the position's lockedUntil time has passed.
/// @dev This function checkpoints rewards
/// @param tokenId A staking position token ID
/// @param amount Amount of `stakingToken()` to be unstaked from the position
function unstake(uint256 tokenId, uint256 amount) public nonReentrant whenNotPaused updateReward(tokenId) {
_unstake(tokenId, amount);
stakingToken().safeTransfer(msg.sender, amount);
}
function unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) public nonReentrant whenNotPaused {
(uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenId, usdcAmount);
emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount);
}
function _unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount)
internal
updateReward(tokenId)
returns (uint256 usdcAmountReceived, uint256 fiduUsed)
{
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
ISeniorPool seniorPool = config.getSeniorPool();
IFidu fidu = config.getFidu();
uint256 fiduBalanceBefore = fidu.balanceOf(address(this));
usdcAmountReceived = seniorPool.withdraw(usdcAmount);
fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this)));
_unstake(tokenId, fiduUsed);
config.getUSDC().safeTransfer(msg.sender, usdcAmountReceived);
return (usdcAmountReceived, fiduUsed);
}
function unstakeAndWithdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata usdcAmounts)
public
nonReentrant
whenNotPaused
{
require(tokenIds.length == usdcAmounts.length, "tokenIds and usdcAmounts must be the same length");
uint256 usdcReceivedAmountTotal = 0;
uint256[] memory fiduAmounts = new uint256[](usdcAmounts.length);
for (uint256 i = 0; i < usdcAmounts.length; i++) {
(uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenIds[i], usdcAmounts[i]);
usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount);
fiduAmounts[i] = fiduAmount;
}
emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts);
}
function unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) public nonReentrant whenNotPaused {
uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenId, fiduAmount);
emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount);
}
function _unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount)
internal
updateReward(tokenId)
returns (uint256 usdcReceivedAmount)
{
usdcReceivedAmount = config.getSeniorPool().withdrawInFidu(fiduAmount);
_unstake(tokenId, fiduAmount);
config.getUSDC().safeTransfer(msg.sender, usdcReceivedAmount);
return usdcReceivedAmount;
}
function unstakeAndWithdrawMultipleInFidu(uint256[] calldata tokenIds, uint256[] calldata fiduAmounts)
public
nonReentrant
whenNotPaused
{
require(tokenIds.length == fiduAmounts.length, "tokenIds and usdcAmounts must be the same length");
uint256 usdcReceivedAmountTotal = 0;
for (uint256 i = 0; i < fiduAmounts.length; i++) {
uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenIds[i], fiduAmounts[i]);
usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount);
}
emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts);
}
function _unstake(uint256 tokenId, uint256 amount) internal {
require(ownerOf(tokenId) == msg.sender, "access denied");
require(amount > 0, "Cannot unstake 0");
StakedPosition storage position = positions[tokenId];
uint256 prevAmount = position.amount;
require(amount <= prevAmount, "cannot unstake more than staked balance");
require(block.timestamp >= position.lockedUntil, "staked funds are locked");
// By this point, leverageMultiplier should always be 1x due to the reset logic in updateReward.
// But we subtract leveredAmount from totalLeveragedStakedSupply anyway, since that is technically correct.
uint256 leveredAmount = toLeveredAmount(amount, position.leverageMultiplier);
totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(leveredAmount);
totalStakedSupply = totalStakedSupply.sub(amount);
position.amount = prevAmount.sub(amount);
// Slash unvested rewards
uint256 slashingPercentage = amount.mul(StakingRewardsVesting.PERCENTAGE_DECIMALS).div(prevAmount);
position.rewards.slash(slashingPercentage);
emit Unstaked(msg.sender, tokenId, amount);
}
/// @notice "Kick" a user's reward multiplier. If they are past their lock-up period, their reward
/// multipler will be reset to 1x.
/// @dev This will also checkpoint their rewards up to the current time.
// solhint-disable-next-line no-empty-blocks
function kick(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) {}
/// @notice Claim rewards for a given staked position
/// @param tokenId A staking position token ID
function getReward(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) {
require(ownerOf(tokenId) == msg.sender, "access denied");
uint256 reward = claimableRewards(tokenId);
if (reward > 0) {
positions[tokenId].rewards.claim(reward);
rewardsToken().safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, tokenId, reward);
}
}
/// @notice Unstake the position's full amount and claim all rewards
/// @param tokenId A staking position token ID
function exit(uint256 tokenId) external {
unstake(tokenId, positions[tokenId].amount);
getReward(tokenId);
}
function exitAndWithdraw(uint256 tokenId) external {
unstakeAndWithdrawInFidu(tokenId, positions[tokenId].amount);
getReward(tokenId);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/// @notice Transfer rewards from msg.sender, to be used for reward distribution
function loadRewards(uint256 rewards) public onlyAdmin updateReward(0) {
rewardsToken().safeTransferFrom(msg.sender, address(this), rewards);
rewardsAvailable = rewardsAvailable.add(rewards);
emit RewardAdded(rewards);
}
function setRewardsParameters(
uint256 _targetCapacity,
uint256 _minRate,
uint256 _maxRate,
uint256 _minRateAtPercent,
uint256 _maxRateAtPercent
) public onlyAdmin updateReward(0) {
require(_maxRate >= _minRate, "maxRate must be >= then minRate");
require(_maxRateAtPercent <= _minRateAtPercent, "maxRateAtPercent must be <= minRateAtPercent");
targetCapacity = _targetCapacity;
minRate = _minRate;
maxRate = _maxRate;
minRateAtPercent = _minRateAtPercent;
maxRateAtPercent = _maxRateAtPercent;
emit RewardsParametersUpdated(msg.sender, targetCapacity, minRate, maxRate, minRateAtPercent, maxRateAtPercent);
}
function setLeverageMultiplier(LockupPeriod lockupPeriod, uint256 leverageMultiplier)
public
onlyAdmin
updateReward(0)
{
leverageMultipliers[lockupPeriod] = leverageMultiplier;
emit LeverageMultiplierUpdated(msg.sender, lockupPeriod, leverageMultiplier);
}
function setVestingSchedule(uint256 _vestingLength) public onlyAdmin updateReward(0) {
vestingLength = _vestingLength;
emit VestingScheduleUpdated(msg.sender, vestingLength);
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(_msgSender(), address(config));
}
/* ========== MODIFIERS ========== */
modifier updateReward(uint256 tokenId) {
_updateReward(tokenId);
_;
}
function _updateReward(uint256 tokenId) internal {
uint256 prevAccumulatedRewardsPerToken = accumulatedRewardsPerToken;
accumulatedRewardsPerToken = rewardPerToken();
uint256 rewardsJustDistributed = totalLeveragedStakedSupply
.mul(accumulatedRewardsPerToken.sub(prevAccumulatedRewardsPerToken))
.div(stakingTokenMantissa());
rewardsAvailable = rewardsAvailable.sub(rewardsJustDistributed);
lastUpdateTime = block.timestamp;
if (tokenId != 0) {
uint256 additionalRewards = earnedSinceLastCheckpoint(tokenId);
StakedPosition storage position = positions[tokenId];
StakingRewardsVesting.Rewards storage rewards = position.rewards;
rewards.totalUnvested = rewards.totalUnvested.add(additionalRewards);
rewards.checkpoint();
positionToAccumulatedRewardsPerToken[tokenId] = accumulatedRewardsPerToken;
// If position is unlocked, reset its leverageMultiplier back to 1x
uint256 lockedUntil = position.lockedUntil;
uint256 leverageMultiplier = position.leverageMultiplier;
uint256 amount = position.amount;
if (lockedUntil > 0 && block.timestamp >= lockedUntil && leverageMultiplier > MULTIPLIER_DECIMALS) {
uint256 prevLeveredAmount = toLeveredAmount(amount, leverageMultiplier);
uint256 newLeveredAmount = toLeveredAmount(amount, MULTIPLIER_DECIMALS);
position.leverageMultiplier = MULTIPLIER_DECIMALS;
totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(prevLeveredAmount).add(newLeveredAmount);
}
}
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 indexed tokenId, uint256 amount, uint256 lockedUntil, uint256 multiplier);
event DepositedAndStaked(
address indexed user,
uint256 depositedAmount,
uint256 indexed tokenId,
uint256 amount,
uint256 lockedUntil,
uint256 multiplier
);
event Unstaked(address indexed user, uint256 indexed tokenId, uint256 amount);
event UnstakedAndWithdrew(address indexed user, uint256 usdcReceivedAmount, uint256 indexed tokenId, uint256 amount);
event UnstakedAndWithdrewMultiple(
address indexed user,
uint256 usdcReceivedAmount,
uint256[] tokenIds,
uint256[] amounts
);
event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
}
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.6.0;
import "../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].
*/
contract ReentrancyGuardUpgradeSafe is Initializable {
bool private _notEntered;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
/*
Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's.
*/
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20withDec is IERC20 {
/**
* @dev Returns the number of decimals used for the token
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ITranchedPool.sol";
abstract contract ISeniorPool {
uint256 public sharePrice;
uint256 public totalLoansOutstanding;
uint256 public totalWritedowns;
function deposit(uint256 amount) external virtual returns (uint256 depositShares);
function depositWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual returns (uint256 depositShares);
function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount);
function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount);
function sweepToCompound() public virtual;
function sweepFromCompound() public virtual;
function invest(ITranchedPool pool) public virtual;
function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256);
function redeem(uint256 tokenId) public virtual;
function writedown(uint256 tokenId) public virtual;
function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount);
function assets() public view virtual returns (uint256);
function getNumShares(uint256 amount) public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "../../interfaces/IGoldfinchConfig.sol";
import "./ConfigOptions.sol";
/**
* @title GoldfinchConfig
* @notice This contract stores mappings of useful "protocol config state", giving a central place
* for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars
* are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol.
* Note: While this inherits from BaseUpgradeablePausable, it is not deployed as an upgradeable contract (this
* is mostly to save gas costs of having each call go through a proxy)
* @author Goldfinch
*/
contract GoldfinchConfig is BaseUpgradeablePausable {
bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE");
mapping(uint256 => address) public addresses;
mapping(uint256 => uint256) public numbers;
mapping(address => bool) public goList;
event AddressUpdated(address owner, uint256 index, address oldValue, address newValue);
event NumberUpdated(address owner, uint256 index, uint256 oldValue, uint256 newValue);
event GoListed(address indexed member);
event NoListed(address indexed member);
bool public valuesInitialized;
function initialize(address owner) public initializer {
require(owner != address(0), "Owner address cannot be empty");
__BaseUpgradeablePausable__init(owner);
_setupRole(GO_LISTER_ROLE, owner);
_setRoleAdmin(GO_LISTER_ROLE, OWNER_ROLE);
}
function setAddress(uint256 addressIndex, address newAddress) public onlyAdmin {
require(addresses[addressIndex] == address(0), "Address has already been initialized");
emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress);
addresses[addressIndex] = newAddress;
}
function setNumber(uint256 index, uint256 newNumber) public onlyAdmin {
emit NumberUpdated(msg.sender, index, numbers[index], newNumber);
numbers[index] = newNumber;
}
function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve);
emit AddressUpdated(msg.sender, key, addresses[key], newTreasuryReserve);
addresses[key] = newTreasuryReserve;
}
function setSeniorPoolStrategy(address newStrategy) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.SeniorPoolStrategy);
emit AddressUpdated(msg.sender, key, addresses[key], newStrategy);
addresses[key] = newStrategy;
}
function setCreditLineImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.CreditLineImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setTranchedPoolImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.TranchedPoolImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setBorrowerImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.BorrowerImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setGoldfinchConfig(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function initializeFromOtherConfig(
address _initialConfig,
uint256 numbersLength,
uint256 addressesLength
) public onlyAdmin {
require(!valuesInitialized, "Already initialized values");
IGoldfinchConfig initialConfig = IGoldfinchConfig(_initialConfig);
for (uint256 i = 0; i < numbersLength; i++) {
setNumber(i, initialConfig.getNumber(i));
}
for (uint256 i = 0; i < addressesLength; i++) {
if (getAddress(i) == address(0)) {
setAddress(i, initialConfig.getAddress(i));
}
}
valuesInitialized = true;
}
/**
* @dev Adds a user to go-list
* @param _member address to add to go-list
*/
function addToGoList(address _member) public onlyGoListerRole {
goList[_member] = true;
emit GoListed(_member);
}
/**
* @dev removes a user from go-list
* @param _member address to remove from go-list
*/
function removeFromGoList(address _member) public onlyGoListerRole {
goList[_member] = false;
emit NoListed(_member);
}
/**
* @dev adds many users to go-list at once
* @param _members addresses to ad to go-list
*/
function bulkAddToGoList(address[] calldata _members) external onlyGoListerRole {
for (uint256 i = 0; i < _members.length; i++) {
addToGoList(_members[i]);
}
}
/**
* @dev removes many users from go-list at once
* @param _members addresses to remove from go-list
*/
function bulkRemoveFromGoList(address[] calldata _members) external onlyGoListerRole {
for (uint256 i = 0; i < _members.length; i++) {
removeFromGoList(_members[i]);
}
}
/*
Using custom getters in case we want to change underlying implementation later,
or add checks or validations later on.
*/
function getAddress(uint256 index) public view returns (address) {
return addresses[index];
}
function getNumber(uint256 index) public view returns (uint256) {
return numbers[index];
}
modifier onlyGoListerRole() {
require(hasRole(GO_LISTER_ROLE, _msgSender()), "Must have go-lister role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "../../interfaces/IPool.sol";
import "../../interfaces/IFidu.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ICreditDesk.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ICUSDCContract.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../interfaces/IBackerRewards.sol";
import "../../interfaces/IGoldfinchFactory.sol";
import "../../interfaces/IGo.sol";
/**
* @title ConfigHelper
* @notice A convenience library for getting easy access to other contracts and constants within the
* protocol, through the use of the GoldfinchConfig contract
* @author Goldfinch
*/
library ConfigHelper {
function getPool(GoldfinchConfig config) internal view returns (IPool) {
return IPool(poolAddress(config));
}
function getSeniorPool(GoldfinchConfig config) internal view returns (ISeniorPool) {
return ISeniorPool(seniorPoolAddress(config));
}
function getSeniorPoolStrategy(GoldfinchConfig config) internal view returns (ISeniorPoolStrategy) {
return ISeniorPoolStrategy(seniorPoolStrategyAddress(config));
}
function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) {
return IERC20withDec(usdcAddress(config));
}
function getCreditDesk(GoldfinchConfig config) internal view returns (ICreditDesk) {
return ICreditDesk(creditDeskAddress(config));
}
function getFidu(GoldfinchConfig config) internal view returns (IFidu) {
return IFidu(fiduAddress(config));
}
function getCUSDCContract(GoldfinchConfig config) internal view returns (ICUSDCContract) {
return ICUSDCContract(cusdcContractAddress(config));
}
function getPoolTokens(GoldfinchConfig config) internal view returns (IPoolTokens) {
return IPoolTokens(poolTokensAddress(config));
}
function getBackerRewards(GoldfinchConfig config) internal view returns (IBackerRewards) {
return IBackerRewards(backerRewardsAddress(config));
}
function getGoldfinchFactory(GoldfinchConfig config) internal view returns (IGoldfinchFactory) {
return IGoldfinchFactory(goldfinchFactoryAddress(config));
}
function getGFI(GoldfinchConfig config) internal view returns (IERC20withDec) {
return IERC20withDec(gfiAddress(config));
}
function getGo(GoldfinchConfig config) internal view returns (IGo) {
return IGo(goAddress(config));
}
function oneInchAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.OneInch));
}
function creditLineImplementationAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CreditLineImplementation));
}
function trustedForwarderAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TrustedForwarder));
}
function configAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig));
}
function poolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Pool));
}
function poolTokensAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.PoolTokens));
}
function backerRewardsAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.BackerRewards));
}
function seniorPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPool));
}
function seniorPoolStrategyAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPoolStrategy));
}
function creditDeskAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CreditDesk));
}
function goldfinchFactoryAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory));
}
function gfiAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GFI));
}
function fiduAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Fidu));
}
function cusdcContractAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CUSDCContract));
}
function usdcAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.USDC));
}
function tranchedPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementation));
}
function migratedTranchedPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.MigratedTranchedPoolImplementation));
}
function reserveAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve));
}
function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin));
}
function borrowerImplementationAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.BorrowerImplementation));
}
function goAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Go));
}
function stakingRewardsAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.StakingRewards));
}
function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator));
}
function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator));
}
function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays));
}
function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays));
}
function getDrawdownPeriodInSeconds(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds));
}
function getTransferRestrictionPeriodInDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays));
}
function getLeverageRatio(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LeverageRatio));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./PauserPausable.sol";
/**
* @title BaseUpgradeablePausable contract
* @notice This is our Base contract that most other contracts inherit from. It includes many standard
* useful abilities like ugpradeability, pausability, access control, and re-entrancy guards.
* @author Goldfinch
*/
contract BaseUpgradeablePausable is
Initializable,
AccessControlUpgradeSafe,
PauserPausable,
ReentrancyGuardUpgradeSafe
{
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
using SafeMath for uint256;
// Pre-reserving a few slots in the base contract in case we need to add things in the future.
// This does not actually take up gas cost or storage cost, but it does reserve the storage slots.
// See OpenZeppelin's use of this pattern here:
// https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37
uint256[50] private __gap1;
uint256[50] private __gap2;
uint256[50] private __gap3;
uint256[50] private __gap4;
// solhint-disable-next-line func-name-mixedcase
function __BaseUpgradeablePausable__init(address owner) public initializer {
require(owner != address(0), "Owner cannot be the zero address");
__AccessControl_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(OWNER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
library StakingRewardsVesting {
using SafeMath for uint256;
using StakingRewardsVesting for Rewards;
uint256 internal constant PERCENTAGE_DECIMALS = 1e18;
struct Rewards {
uint256 totalUnvested;
uint256 totalVested;
uint256 totalPreviouslyVested;
uint256 totalClaimed;
uint256 startTime;
uint256 endTime;
}
function claim(Rewards storage rewards, uint256 reward) internal {
rewards.totalClaimed = rewards.totalClaimed.add(reward);
}
function claimable(Rewards storage rewards) internal view returns (uint256) {
return rewards.totalVested.add(rewards.totalPreviouslyVested).sub(rewards.totalClaimed);
}
function currentGrant(Rewards storage rewards) internal view returns (uint256) {
return rewards.totalUnvested.add(rewards.totalVested);
}
/// @notice Slash the vesting rewards by `percentage`. `percentage` of the unvested portion
/// of the grant is forfeited. The remaining unvested portion continues to vest over the rest
/// of the vesting schedule. The already vested portion continues to be claimable.
///
/// A motivating example:
///
/// Let's say we're 50% through vesting, with 100 tokens granted. Thus, 50 tokens are vested and 50 are unvested.
/// Now let's say the grant is slashed by 90% (e.g. for StakingRewards, because the user unstaked 90% of their
/// position). 45 of the unvested tokens will be forfeited. 5 of the unvested tokens and 5 of the vested tokens
/// will be considered as the "new grant", which is 50% through vesting. The remaining 45 vested tokens will be
/// still be claimable at any time.
function slash(Rewards storage rewards, uint256 percentage) internal {
require(percentage <= PERCENTAGE_DECIMALS, "slashing percentage cannot be greater than 100%");
uint256 unvestedToSlash = rewards.totalUnvested.mul(percentage).div(PERCENTAGE_DECIMALS);
uint256 vestedToMove = rewards.totalVested.mul(percentage).div(PERCENTAGE_DECIMALS);
rewards.totalUnvested = rewards.totalUnvested.sub(unvestedToSlash);
rewards.totalVested = rewards.totalVested.sub(vestedToMove);
rewards.totalPreviouslyVested = rewards.totalPreviouslyVested.add(vestedToMove);
}
function checkpoint(Rewards storage rewards) internal {
uint256 newTotalVested = totalVestedAt(rewards.startTime, rewards.endTime, block.timestamp, rewards.currentGrant());
if (newTotalVested > rewards.totalVested) {
uint256 difference = newTotalVested.sub(rewards.totalVested);
rewards.totalUnvested = rewards.totalUnvested.sub(difference);
rewards.totalVested = newTotalVested;
}
}
function totalVestedAt(
uint256 start,
uint256 end,
uint256 time,
uint256 grantedAmount
) internal pure returns (uint256) {
if (end <= start) {
return grantedAmount;
}
return Math.min(grantedAmount.mul(time.sub(start)).div(end.sub(start)), grantedAmount);
}
}
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);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IV2CreditLine.sol";
abstract contract ITranchedPool {
IV2CreditLine public creditLine;
uint256 public createdAt;
enum Tranches {
Reserved,
Senior,
Junior
}
struct TrancheInfo {
uint256 id;
uint256 principalDeposited;
uint256 principalSharePrice;
uint256 interestSharePrice;
uint256 lockedUntil;
}
struct PoolSlice {
TrancheInfo seniorTranche;
TrancheInfo juniorTranche;
uint256 totalInterestAccrued;
uint256 principalDeployed;
}
struct SliceInfo {
uint256 reserveFeePercent;
uint256 interestAccrued;
uint256 principalAccrued;
}
struct ApplyResult {
uint256 interestRemaining;
uint256 principalRemaining;
uint256 reserveDeduction;
uint256 oldInterestSharePrice;
uint256 oldPrincipalSharePrice;
}
function initialize(
address _config,
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) public virtual;
function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory);
function pay(uint256 amount) external virtual;
function lockJuniorCapital() external virtual;
function lockPool() external virtual;
function initializeNextSlice(uint256 _fundableAt) external virtual;
function totalJuniorDeposits() external view virtual returns (uint256);
function drawdown(uint256 amount) external virtual;
function setFundableAt(uint256 timestamp) external virtual;
function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId);
function assess() external virtual;
function depositWithPermit(
uint256 tranche,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual returns (uint256 tokenId);
function availableToWithdraw(uint256 tokenId)
external
view
virtual
returns (uint256 interestRedeemable, uint256 principalRedeemable);
function withdraw(uint256 tokenId, uint256 amount)
external
virtual
returns (uint256 interestWithdrawn, uint256 principalWithdrawn);
function withdrawMax(uint256 tokenId)
external
virtual
returns (uint256 interestWithdrawn, uint256 principalWithdrawn);
function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ICreditLine.sol";
abstract contract IV2CreditLine is ICreditLine {
function principal() external view virtual returns (uint256);
function totalInterestAccrued() external view virtual returns (uint256);
function termStartTime() external view virtual returns (uint256);
function setLimit(uint256 newAmount) external virtual;
function setMaxLimit(uint256 newAmount) external virtual;
function setBalance(uint256 newBalance) external virtual;
function setPrincipal(uint256 _principal) external virtual;
function setTotalInterestAccrued(uint256 _interestAccrued) external virtual;
function drawdown(uint256 amount) external virtual;
function assess()
external
virtual
returns (
uint256,
uint256,
uint256
);
function initialize(
address _config,
address owner,
address _borrower,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) public virtual;
function setTermEndTime(uint256 newTermEndTime) external virtual;
function setNextDueTime(uint256 newNextDueTime) external virtual;
function setInterestOwed(uint256 newInterestOwed) external virtual;
function setPrincipalOwed(uint256 newPrincipalOwed) external virtual;
function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual;
function setWritedownAmount(uint256 newWritedownAmount) external virtual;
function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual;
function setLateFeeApr(uint256 newLateFeeApr) external virtual;
function updateGoldfinchConfig() external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface ICreditLine {
function borrower() external view returns (address);
function limit() external view returns (uint256);
function maxLimit() external view returns (uint256);
function interestApr() external view returns (uint256);
function paymentPeriodInDays() external view returns (uint256);
function principalGracePeriodInDays() external view returns (uint256);
function termInDays() external view returns (uint256);
function lateFeeApr() external view returns (uint256);
function isLate() external view returns (bool);
function withinPrincipalGracePeriod() external view returns (bool);
// Accounting variables
function balance() external view returns (uint256);
function interestOwed() external view returns (uint256);
function principalOwed() external view returns (uint256);
function termEndTime() external view returns (uint256);
function nextDueTime() external view returns (uint256);
function interestAccruedAsOf() external view returns (uint256);
function lastFullPaymentTime() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IGoldfinchConfig {
function getNumber(uint256 index) external returns (uint256);
function getAddress(uint256 index) external returns (address);
function setAddress(uint256 index, address newAddress) external returns (address);
function setNumber(uint256 index, uint256 newNumber) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/**
* @title ConfigOptions
* @notice A central place for enumerating the configurable options of our GoldfinchConfig contract
* @author Goldfinch
*/
library ConfigOptions {
// NEVER EVER CHANGE THE ORDER OF THESE!
// You can rename or append. But NEVER change the order.
enum Numbers {
TransactionLimit,
TotalFundsLimit,
MaxUnderwriterLimit,
ReserveDenominator,
WithdrawFeeDenominator,
LatenessGracePeriodInDays,
LatenessMaxDays,
DrawdownPeriodInSeconds,
TransferRestrictionPeriodInDays,
LeverageRatio
}
enum Addresses {
Pool,
CreditLineImplementation,
GoldfinchFactory,
CreditDesk,
Fidu,
USDC,
TreasuryReserve,
ProtocolAdmin,
OneInch,
TrustedForwarder,
CUSDCContract,
GoldfinchConfig,
PoolTokens,
TranchedPoolImplementation,
SeniorPool,
SeniorPoolStrategy,
MigratedTranchedPoolImplementation,
BorrowerImplementation,
GFI,
Go,
BackerRewards,
StakingRewards
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
/**
* @title PauserPausable
* @notice Inheriting from OpenZeppelin's Pausable contract, this does small
* augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract.
* It is meant to be inherited.
* @author Goldfinch
*/
contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
// solhint-disable-next-line func-name-mixedcase
function __PauserPausable__init() public initializer {
__Pausable_init_unchained();
}
/**
* @dev Pauses all functions guarded by Pause
*
* See {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the PAUSER_ROLE.
*/
function pause() public onlyPauserRole {
_pause();
}
/**
* @dev Unpauses the contract
*
* See {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the Pauser role
*/
function unpause() public onlyPauserRole {
_unpause();
}
modifier onlyPauserRole() {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IPool {
uint256 public sharePrice;
function deposit(uint256 amount) external virtual;
function withdraw(uint256 usdcAmount) external virtual;
function withdrawInFidu(uint256 fiduAmount) external virtual;
function collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) public virtual;
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool);
function drawdown(address to, uint256 amount) public virtual returns (bool);
function sweepToCompound() public virtual;
function sweepFromCompound() public virtual;
function distributeLosses(address creditlineAddress, int256 writedownDelta) external virtual;
function assets() public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IERC20withDec.sol";
interface IFidu is IERC20withDec {
function mintTo(address to, uint256 amount) external;
function burnFrom(address to, uint256 amount) external;
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ISeniorPool.sol";
import "./ITranchedPool.sol";
abstract contract ISeniorPoolStrategy {
function getLeverageRatio(ITranchedPool pool) public view virtual returns (uint256);
function invest(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256 amount);
function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract ICreditDesk {
uint256 public totalWritedowns;
uint256 public totalLoansOutstanding;
function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external virtual;
function drawdown(address creditLineAddress, uint256 amount) external virtual;
function pay(address creditLineAddress, uint256 amount) external virtual;
function assessCreditLine(address creditLineAddress) external virtual;
function applyPayment(address creditLineAddress, uint256 amount) external virtual;
function getNextPaymentAmount(address creditLineAddress, uint256 asOfBLock) external view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
// Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IERC20withDec.sol";
interface ICUSDCContract is IERC20withDec {
/*** User Interface ***/
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address cTokenCollateral
) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function balanceOfUnderlying(address owner) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
/*** Admin Functions ***/
function _addReserves(uint256 addAmount) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol";
interface IPoolTokens is IERC721 {
event TokenMinted(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 amount,
uint256 tranche
);
event TokenRedeemed(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed,
uint256 tranche
);
event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId);
struct TokenInfo {
address pool;
uint256 tranche;
uint256 principalAmount;
uint256 principalRedeemed;
uint256 interestRedeemed;
}
struct MintParams {
uint256 principalAmount;
uint256 tranche;
}
function mint(MintParams calldata params, address to) external returns (uint256);
function redeem(
uint256 tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed
) external;
function burn(uint256 tokenId) external;
function onPoolCreated(address newPool) external;
function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory);
function validPool(address sender) external view returns (bool);
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IBackerRewards {
function allocateRewards(uint256 _interestPaymentAmount) external;
function setPoolTokenAccRewardsPerPrincipalDollarAtMint(address poolAddress, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IGoldfinchFactory {
function createCreditLine() external returns (address);
function createBorrower(address owner) external returns (address);
function createPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256[] calldata _allowedUIDTypes
) external returns (address);
function createMigratedPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256[] calldata _allowedUIDTypes
) external returns (address);
function updateGoldfinchConfig() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IGo {
uint256 public constant ID_TYPE_0 = 0;
uint256 public constant ID_TYPE_1 = 1;
uint256 public constant ID_TYPE_2 = 2;
uint256 public constant ID_TYPE_3 = 3;
uint256 public constant ID_TYPE_4 = 4;
uint256 public constant ID_TYPE_5 = 5;
uint256 public constant ID_TYPE_6 = 6;
uint256 public constant ID_TYPE_7 = 7;
uint256 public constant ID_TYPE_8 = 8;
uint256 public constant ID_TYPE_9 = 9;
uint256 public constant ID_TYPE_10 = 10;
/// @notice Returns the address of the UniqueIdentity contract.
function uniqueIdentity() external virtual returns (address);
function go(address account) public view virtual returns (bool);
function goOnlyIdTypes(address account, uint256[] calldata onlyIdTypes) public view virtual returns (bool);
function goSeniorPool(address account) public view virtual returns (bool);
function updateGoldfinchConfig() external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../protocol/core/Pool.sol";
import "../protocol/core/Accountant.sol";
import "../protocol/core/CreditLine.sol";
import "../protocol/core/GoldfinchConfig.sol";
contract FakeV2CreditDesk is BaseUpgradeablePausable {
uint256 public totalWritedowns;
uint256 public totalLoansOutstanding;
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
GoldfinchConfig public config;
struct Underwriter {
uint256 governanceLimit;
address[] creditLines;
}
struct Borrower {
address[] creditLines;
}
event PaymentMade(
address indexed payer,
address indexed creditLine,
uint256 interestAmount,
uint256 principalAmount,
uint256 remainingAmount
);
event PrepaymentMade(address indexed payer, address indexed creditLine, uint256 prepaymentAmount);
event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount);
event CreditLineCreated(address indexed borrower, address indexed creditLine);
event PoolAddressUpdated(address indexed oldAddress, address indexed newAddress);
event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit);
event LimitChanged(address indexed owner, string limitType, uint256 amount);
mapping(address => Underwriter) public underwriters;
mapping(address => Borrower) private borrowers;
function initialize(address owner, GoldfinchConfig _config) public initializer {
owner;
_config;
return;
}
function someBrandNewFunction() public pure returns (uint256) {
return 5;
}
function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) {
return underwriters[underwriterAddress].creditLines;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
/**
* @title Goldfinch's Pool contract
* @notice Main entry point for LP's (a.k.a. capital providers)
* Handles key logic for depositing and withdrawing funds from the Pool
* @author Goldfinch
*/
contract Pool is BaseUpgradeablePausable, IPool {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
uint256 public compoundBalance;
event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares);
event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount);
event TransferMade(address indexed from, address indexed to, uint256 amount);
event InterestCollected(address indexed payer, uint256 poolAmount, uint256 reserveAmount);
event PrincipalCollected(address indexed payer, uint256 amount);
event ReserveFundsCollected(address indexed user, uint256 amount);
event PrincipalWrittendown(address indexed creditline, int256 amount);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
/**
* @notice Run only once, on initialization
* @param owner The address of who should have the "OWNER_ROLE" of this contract
* @param _config The address of the GoldfinchConfig contract
*/
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
sharePrice = fiduMantissa();
IERC20withDec usdc = config.getUSDC();
// Sanity check the address
usdc.totalSupply();
// Unlock self for infinite amount
bool success = usdc.approve(address(this), uint256(-1));
require(success, "Failed to approve USDC");
}
/**
* @notice Deposits `amount` USDC from msg.sender into the Pool, and returns you the equivalent value of FIDU tokens
* @param amount The amount of USDC to deposit
*/
function deposit(uint256 amount) external override whenNotPaused withinTransactionLimit(amount) nonReentrant {
require(amount > 0, "Must deposit more than zero");
// Check if the amount of new shares to be added is within limits
uint256 depositShares = getNumShares(amount);
uint256 potentialNewTotalShares = totalShares().add(depositShares);
require(poolWithinLimit(potentialNewTotalShares), "Deposit would put the Pool over the total limit.");
emit DepositMade(msg.sender, amount, depositShares);
bool success = doUSDCTransfer(msg.sender, address(this), amount);
require(success, "Failed to transfer for deposit");
config.getFidu().mintTo(msg.sender, depositShares);
}
/**
* @notice Withdraws USDC from the Pool to msg.sender, and burns the equivalent value of FIDU tokens
* @param usdcAmount The amount of USDC to withdraw
*/
function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant {
require(usdcAmount > 0, "Must withdraw more than zero");
// This MUST happen before calculating withdrawShares, otherwise the share price
// changes between calculation and burning of Fidu, which creates a asset/liability mismatch
if (compoundBalance > 0) {
_sweepFromCompound();
}
uint256 withdrawShares = getNumShares(usdcAmount);
_withdraw(usdcAmount, withdrawShares);
}
/**
* @notice Withdraws USDC (denominated in FIDU terms) from the Pool to msg.sender
* @param fiduAmount The amount of USDC to withdraw in terms of fidu shares
*/
function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant {
require(fiduAmount > 0, "Must withdraw more than zero");
if (compoundBalance > 0) {
_sweepFromCompound();
}
uint256 usdcAmount = getUSDCAmountFromShares(fiduAmount);
uint256 withdrawShares = fiduAmount;
_withdraw(usdcAmount, withdrawShares);
}
/**
* @notice Collects `interest` USDC in interest and `principal` in principal from `from` and sends it to the Pool.
* This also increases the share price accordingly. A portion is sent to the Goldfinch Reserve address
* @param from The address to take the USDC from. Implicitly, the Pool
* must be authorized to move USDC on behalf of `from`.
* @param interest the interest amount of USDC to move to the Pool
* @param principal the principal amount of USDC to move to the Pool
*
* Requirements:
* - The caller must be the Credit Desk. Not even the owner can call this function.
*/
function collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) public override onlyCreditDesk whenNotPaused {
_collectInterestAndPrincipal(from, interest, principal);
}
function distributeLosses(address creditlineAddress, int256 writedownDelta)
external
override
onlyCreditDesk
whenNotPaused
{
if (writedownDelta > 0) {
uint256 delta = usdcToSharePrice(uint256(writedownDelta));
sharePrice = sharePrice.add(delta);
} else {
// If delta is negative, convert to positive uint, and sub from sharePrice
uint256 delta = usdcToSharePrice(uint256(writedownDelta * -1));
sharePrice = sharePrice.sub(delta);
}
emit PrincipalWrittendown(creditlineAddress, writedownDelta);
}
/**
* @notice Moves `amount` USDC from `from`, to `to`.
* @param from The address to take the USDC from. Implicitly, the Pool
* must be authorized to move USDC on behalf of `from`.
* @param to The address that the USDC should be moved to
* @param amount the amount of USDC to move to the Pool
*
* Requirements:
* - The caller must be the Credit Desk. Not even the owner can call this function.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public override onlyCreditDesk whenNotPaused returns (bool) {
bool result = doUSDCTransfer(from, to, amount);
require(result, "USDC Transfer failed");
emit TransferMade(from, to, amount);
return result;
}
/**
* @notice Moves `amount` USDC from the pool, to `to`. This is similar to transferFrom except we sweep any
* balance we have from compound first and recognize interest. Meant to be called only by the credit desk on drawdown
* @param to The address that the USDC should be moved to
* @param amount the amount of USDC to move to the Pool
*
* Requirements:
* - The caller must be the Credit Desk. Not even the owner can call this function.
*/
function drawdown(address to, uint256 amount) public override onlyCreditDesk whenNotPaused returns (bool) {
if (compoundBalance > 0) {
_sweepFromCompound();
}
return transferFrom(address(this), to, amount);
}
function assets() public view override returns (uint256) {
ICreditDesk creditDesk = config.getCreditDesk();
return
compoundBalance.add(config.getUSDC().balanceOf(address(this))).add(creditDesk.totalLoansOutstanding()).sub(
creditDesk.totalWritedowns()
);
}
function migrateToSeniorPool() external onlyAdmin {
// Bring back all USDC
if (compoundBalance > 0) {
sweepFromCompound();
}
// Pause deposits/withdrawals
if (!paused()) {
pause();
}
// Remove special priveldges from Fidu
bytes32 minterRole = keccak256("MINTER_ROLE");
bytes32 pauserRole = keccak256("PAUSER_ROLE");
config.getFidu().renounceRole(minterRole, address(this));
config.getFidu().renounceRole(pauserRole, address(this));
// Move all USDC to the SeniorPool
address seniorPoolAddress = config.seniorPoolAddress();
uint256 balance = config.getUSDC().balanceOf(address(this));
bool success = doUSDCTransfer(address(this), seniorPoolAddress, balance);
require(success, "Failed to transfer USDC balance to the senior pool");
// Claim our COMP!
address compoundController = address(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
bytes memory data = abi.encodeWithSignature("claimComp(address)", address(this));
bytes memory _res;
// solhint-disable-next-line avoid-low-level-calls
(success, _res) = compoundController.call(data);
require(success, "Failed to claim COMP");
// Send our balance of COMP!
address compToken = address(0xc00e94Cb662C3520282E6f5717214004A7f26888);
data = abi.encodeWithSignature("balanceOf(address)", address(this));
// solhint-disable-next-line avoid-low-level-calls
(success, _res) = compToken.call(data);
uint256 compBalance = toUint256(_res);
data = abi.encodeWithSignature("transfer(address,uint256)", seniorPoolAddress, compBalance);
// solhint-disable-next-line avoid-low-level-calls
(success, _res) = compToken.call(data);
require(success, "Failed to transfer COMP");
}
function toUint256(bytes memory _bytes) internal pure returns (uint256 value) {
assembly {
value := mload(add(_bytes, 0x20))
}
}
/**
* @notice Moves any USDC still in the Pool to Compound, and tracks the amount internally.
* This is done to earn interest on latent funds until we have other borrowers who can use it.
*
* Requirements:
* - The caller must be an admin.
*/
function sweepToCompound() public override onlyAdmin whenNotPaused {
IERC20 usdc = config.getUSDC();
uint256 usdcBalance = usdc.balanceOf(address(this));
ICUSDCContract cUSDC = config.getCUSDCContract();
// Approve compound to the exact amount
bool success = usdc.approve(address(cUSDC), usdcBalance);
require(success, "Failed to approve USDC for compound");
sweepToCompound(cUSDC, usdcBalance);
// Remove compound approval to be extra safe
success = config.getUSDC().approve(address(cUSDC), 0);
require(success, "Failed to approve USDC for compound");
}
/**
* @notice Moves any USDC from Compound back to the Pool, and recognizes interest earned.
* This is done automatically on drawdown or withdraw, but can be called manually if necessary.
*
* Requirements:
* - The caller must be an admin.
*/
function sweepFromCompound() public override onlyAdmin whenNotPaused {
_sweepFromCompound();
}
/* Internal Functions */
function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal withinTransactionLimit(usdcAmount) {
IFidu fidu = config.getFidu();
// Determine current shares the address has and the shares requested to withdraw
uint256 currentShares = fidu.balanceOf(msg.sender);
// Ensure the address has enough value in the pool
require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns");
uint256 reserveAmount = usdcAmount.div(config.getWithdrawFeeDenominator());
uint256 userAmount = usdcAmount.sub(reserveAmount);
emit WithdrawalMade(msg.sender, userAmount, reserveAmount);
// Send the amounts
bool success = doUSDCTransfer(address(this), msg.sender, userAmount);
require(success, "Failed to transfer for withdraw");
sendToReserve(address(this), reserveAmount, msg.sender);
// Burn the shares
fidu.burnFrom(msg.sender, withdrawShares);
}
function sweepToCompound(ICUSDCContract cUSDC, uint256 usdcAmount) internal {
// Our current design requires we re-normalize by withdrawing everything and recognizing interest gains
// before we can add additional capital to Compound
require(compoundBalance == 0, "Cannot sweep when we already have a compound balance");
require(usdcAmount != 0, "Amount to sweep cannot be zero");
uint256 error = cUSDC.mint(usdcAmount);
require(error == 0, "Sweep to compound failed");
compoundBalance = usdcAmount;
}
function sweepFromCompound(ICUSDCContract cUSDC, uint256 cUSDCAmount) internal {
uint256 cBalance = compoundBalance;
require(cBalance != 0, "No funds on compound");
require(cUSDCAmount != 0, "Amount to sweep cannot be zero");
IERC20 usdc = config.getUSDC();
uint256 preRedeemUSDCBalance = usdc.balanceOf(address(this));
uint256 cUSDCExchangeRate = cUSDC.exchangeRateCurrent();
uint256 redeemedUSDC = cUSDCToUSDC(cUSDCExchangeRate, cUSDCAmount);
uint256 error = cUSDC.redeem(cUSDCAmount);
uint256 postRedeemUSDCBalance = usdc.balanceOf(address(this));
require(error == 0, "Sweep from compound failed");
require(postRedeemUSDCBalance.sub(preRedeemUSDCBalance) == redeemedUSDC, "Unexpected redeem amount");
uint256 interestAccrued = redeemedUSDC.sub(cBalance);
_collectInterestAndPrincipal(address(this), interestAccrued, 0);
compoundBalance = 0;
}
function _collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) internal {
uint256 reserveAmount = interest.div(config.getReserveDenominator());
uint256 poolAmount = interest.sub(reserveAmount);
uint256 increment = usdcToSharePrice(poolAmount);
sharePrice = sharePrice.add(increment);
if (poolAmount > 0) {
emit InterestCollected(from, poolAmount, reserveAmount);
}
if (principal > 0) {
emit PrincipalCollected(from, principal);
}
if (reserveAmount > 0) {
sendToReserve(from, reserveAmount, from);
}
// Gas savings: No need to transfer to yourself, which happens in sweepFromCompound
if (from != address(this)) {
bool success = doUSDCTransfer(from, address(this), principal.add(poolAmount));
require(success, "Failed to collect principal repayment");
}
}
function _sweepFromCompound() internal {
ICUSDCContract cUSDC = config.getCUSDCContract();
sweepFromCompound(cUSDC, cUSDC.balanceOf(address(this)));
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
function fiduMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(18);
}
function usdcMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(6);
}
function usdcToFidu(uint256 amount) internal pure returns (uint256) {
return amount.mul(fiduMantissa()).div(usdcMantissa());
}
function cUSDCToUSDC(uint256 exchangeRate, uint256 amount) internal pure returns (uint256) {
// See https://compound.finance/docs#protocol-math
// But note, the docs and reality do not agree. Docs imply that that exchange rate is
// scaled by 1e18, but tests and mainnet forking make it appear to be scaled by 1e16
// 1e16 is also what Sheraz at Certik said.
uint256 usdcDecimals = 6;
uint256 cUSDCDecimals = 8;
// We multiply in the following order, for the following reasons...
// Amount in cToken (1e8)
// Amount in USDC (but scaled by 1e16, cause that's what exchange rate decimals are)
// Downscale to cToken decimals (1e8)
// Downscale from cToken to USDC decimals (8 to 6)
return amount.mul(exchangeRate).div(10**(18 + usdcDecimals - cUSDCDecimals)).div(10**2);
}
function totalShares() internal view returns (uint256) {
return config.getFidu().totalSupply();
}
function usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) {
return usdcToFidu(usdcAmount).mul(fiduMantissa()).div(totalShares());
}
function poolWithinLimit(uint256 _totalShares) internal view returns (bool) {
return
_totalShares.mul(sharePrice).div(fiduMantissa()) <=
usdcToFidu(config.getNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit)));
}
function transactionWithinLimit(uint256 amount) internal view returns (bool) {
return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit));
}
function getNumShares(uint256 amount) internal view returns (uint256) {
return usdcToFidu(amount).mul(fiduMantissa()).div(sharePrice);
}
function getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) {
return fiduToUSDC(fiduAmount.mul(sharePrice).div(fiduMantissa()));
}
function fiduToUSDC(uint256 amount) internal pure returns (uint256) {
return amount.div(fiduMantissa().div(usdcMantissa()));
}
function sendToReserve(
address from,
uint256 amount,
address userForEvent
) internal {
emit ReserveFundsCollected(userForEvent, amount);
bool success = doUSDCTransfer(from, config.reserveAddress(), amount);
require(success, "Reserve transfer was not successful");
}
function doUSDCTransfer(
address from,
address to,
uint256 amount
) internal returns (bool) {
require(to != address(0), "Can't send to zero address");
IERC20withDec usdc = config.getUSDC();
return usdc.transferFrom(from, to, amount);
}
modifier withinTransactionLimit(uint256 amount) {
require(transactionWithinLimit(amount), "Amount is over the per-transaction limit");
_;
}
modifier onlyCreditDesk() {
require(msg.sender == config.creditDeskAddress(), "Only the credit desk is allowed to call this function");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./CreditLine.sol";
import "../../interfaces/ICreditLine.sol";
import "../../external/FixedPoint.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title The Accountant
* @notice Library for handling key financial calculations, such as interest and principal accrual.
* @author Goldfinch
*/
library Accountant {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Signed;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for int256;
using FixedPoint for uint256;
// Scaling factor used by FixedPoint.sol. We need this to convert the fixed point raw values back to unscaled
uint256 public constant FP_SCALING_FACTOR = 10**18;
uint256 public constant INTEREST_DECIMALS = 1e18;
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
uint256 public constant SECONDS_PER_YEAR = (SECONDS_PER_DAY * 365);
struct PaymentAllocation {
uint256 interestPayment;
uint256 principalPayment;
uint256 additionalBalancePayment;
}
function calculateInterestAndPrincipalAccrued(
CreditLine cl,
uint256 timestamp,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
uint256 balance = cl.balance(); // gas optimization
uint256 interestAccrued = calculateInterestAccrued(cl, balance, timestamp, lateFeeGracePeriod);
uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, timestamp);
return (interestAccrued, principalAccrued);
}
function calculateInterestAndPrincipalAccruedOverPeriod(
CreditLine cl,
uint256 balance,
uint256 startTime,
uint256 endTime,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
uint256 interestAccrued = calculateInterestAccruedOverPeriod(cl, balance, startTime, endTime, lateFeeGracePeriod);
uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, endTime);
return (interestAccrued, principalAccrued);
}
function calculatePrincipalAccrued(
ICreditLine cl,
uint256 balance,
uint256 timestamp
) public view returns (uint256) {
// If we've already accrued principal as of the term end time, then don't accrue more principal
uint256 termEndTime = cl.termEndTime();
if (cl.interestAccruedAsOf() >= termEndTime) {
return 0;
}
if (timestamp >= termEndTime) {
return balance;
} else {
return 0;
}
}
function calculateWritedownFor(
ICreditLine cl,
uint256 timestamp,
uint256 gracePeriodInDays,
uint256 maxDaysLate
) public view returns (uint256, uint256) {
return calculateWritedownForPrincipal(cl, cl.balance(), timestamp, gracePeriodInDays, maxDaysLate);
}
function calculateWritedownForPrincipal(
ICreditLine cl,
uint256 principal,
uint256 timestamp,
uint256 gracePeriodInDays,
uint256 maxDaysLate
) public view returns (uint256, uint256) {
FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl);
if (amountOwedPerDay.isEqual(0)) {
return (0, 0);
}
FixedPoint.Unsigned memory fpGracePeriod = FixedPoint.fromUnscaledUint(gracePeriodInDays);
FixedPoint.Unsigned memory daysLate;
// Excel math: =min(1,max(0,periods_late_in_days-graceperiod_in_days)/MAX_ALLOWED_DAYS_LATE) grace_period = 30,
// Before the term end date, we use the interestOwed to calculate the periods late. However, after the loan term
// has ended, since the interest is a much smaller fraction of the principal, we cannot reliably use interest to
// calculate the periods later.
uint256 totalOwed = cl.interestOwed().add(cl.principalOwed());
daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay);
if (timestamp > cl.termEndTime()) {
uint256 secondsLate = timestamp.sub(cl.termEndTime());
daysLate = daysLate.add(FixedPoint.fromUnscaledUint(secondsLate).div(SECONDS_PER_DAY));
}
FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate);
FixedPoint.Unsigned memory writedownPercent;
if (daysLate.isLessThanOrEqual(fpGracePeriod)) {
// Within the grace period, we don't have to write down, so assume 0%
writedownPercent = FixedPoint.fromUnscaledUint(0);
} else {
writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate));
}
FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(principal).div(FP_SCALING_FACTOR);
// This will return a number between 0-100 representing the write down percent with no decimals
uint256 unscaledWritedownPercent = writedownPercent.mul(100).div(FP_SCALING_FACTOR).rawValue;
return (unscaledWritedownPercent, writedownAmount.rawValue);
}
function calculateAmountOwedForOneDay(ICreditLine cl) public view returns (FixedPoint.Unsigned memory interestOwed) {
// Determine theoretical interestOwed for one full day
uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS);
interestOwed = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365);
return interestOwed;
}
function calculateInterestAccrued(
CreditLine cl,
uint256 balance,
uint256 timestamp,
uint256 lateFeeGracePeriodInDays
) public view returns (uint256) {
// We use Math.min here to prevent integer overflow (ie. go negative) when calculating
// numSecondsElapsed. Typically this shouldn't be possible, because
// the interestAccruedAsOf couldn't be *after* the current timestamp. However, when assessing
// we allow this function to be called with a past timestamp, which raises the possibility
// of overflow.
// This use of min should not generate incorrect interest calculations, since
// this function's purpose is just to normalize balances, and handing in a past timestamp
// will necessarily return zero interest accrued (because zero elapsed time), which is correct.
uint256 startTime = Math.min(timestamp, cl.interestAccruedAsOf());
return calculateInterestAccruedOverPeriod(cl, balance, startTime, timestamp, lateFeeGracePeriodInDays);
}
function calculateInterestAccruedOverPeriod(
CreditLine cl,
uint256 balance,
uint256 startTime,
uint256 endTime,
uint256 lateFeeGracePeriodInDays
) public view returns (uint256 interestOwed) {
uint256 secondsElapsed = endTime.sub(startTime);
uint256 totalInterestPerYear = balance.mul(cl.interestApr()).div(INTEREST_DECIMALS);
interestOwed = totalInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR);
if (lateFeeApplicable(cl, endTime, lateFeeGracePeriodInDays)) {
uint256 lateFeeInterestPerYear = balance.mul(cl.lateFeeApr()).div(INTEREST_DECIMALS);
uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR);
interestOwed = interestOwed.add(additionalLateFeeInterest);
}
return interestOwed;
}
function lateFeeApplicable(
CreditLine cl,
uint256 timestamp,
uint256 gracePeriodInDays
) public view returns (bool) {
uint256 secondsLate = timestamp.sub(cl.lastFullPaymentTime());
return cl.lateFeeApr() > 0 && secondsLate > gracePeriodInDays.mul(SECONDS_PER_DAY);
}
function allocatePayment(
uint256 paymentAmount,
uint256 balance,
uint256 interestOwed,
uint256 principalOwed
) public pure returns (PaymentAllocation memory) {
uint256 paymentRemaining = paymentAmount;
uint256 interestPayment = Math.min(interestOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(interestPayment);
uint256 principalPayment = Math.min(principalOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(principalPayment);
uint256 balanceRemaining = balance.sub(principalPayment);
uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining);
return
PaymentAllocation({
interestPayment: interestPayment,
principalPayment: principalPayment,
additionalBalancePayment: additionalBalancePayment
});
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "./ConfigHelper.sol";
import "./BaseUpgradeablePausable.sol";
import "./Accountant.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ICreditLine.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
/**
* @title CreditLine
* @notice A contract that represents the agreement between Backers and
* a Borrower. Includes the terms of the loan, as well as the current accounting state, such as interest owed.
* A CreditLine belongs to a TranchedPool, and is fully controlled by that TranchedPool. It does not
* operate in any standalone capacity. It should generally be considered internal to the TranchedPool.
* @author Goldfinch
*/
// solhint-disable-next-line max-states-count
contract CreditLine is BaseUpgradeablePausable, ICreditLine {
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
event GoldfinchConfigUpdated(address indexed who, address configAddress);
// Credit line terms
address public override borrower;
uint256 public currentLimit;
uint256 public override maxLimit;
uint256 public override interestApr;
uint256 public override paymentPeriodInDays;
uint256 public override termInDays;
uint256 public override principalGracePeriodInDays;
uint256 public override lateFeeApr;
// Accounting variables
uint256 public override balance;
uint256 public override interestOwed;
uint256 public override principalOwed;
uint256 public override termEndTime;
uint256 public override nextDueTime;
uint256 public override interestAccruedAsOf;
uint256 public override lastFullPaymentTime;
uint256 public totalInterestAccrued;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
function initialize(
address _config,
address owner,
address _borrower,
uint256 _maxLimit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) public initializer {
require(_config != address(0) && owner != address(0) && _borrower != address(0), "Zero address passed in");
__BaseUpgradeablePausable__init(owner);
config = GoldfinchConfig(_config);
borrower = _borrower;
maxLimit = _maxLimit;
interestApr = _interestApr;
paymentPeriodInDays = _paymentPeriodInDays;
termInDays = _termInDays;
lateFeeApr = _lateFeeApr;
principalGracePeriodInDays = _principalGracePeriodInDays;
interestAccruedAsOf = block.timestamp;
// Unlock owner, which is a TranchedPool, for infinite amount
bool success = config.getUSDC().approve(owner, uint256(-1));
require(success, "Failed to approve USDC");
}
function limit() external view override returns (uint256) {
return currentLimit;
}
/**
* @notice Updates the internal accounting to track a drawdown as of current block timestamp.
* Does not move any money
* @param amount The amount in USDC that has been drawndown
*/
function drawdown(uint256 amount) external onlyAdmin {
require(amount.add(balance) <= currentLimit, "Cannot drawdown more than the limit");
require(amount > 0, "Invalid drawdown amount");
uint256 timestamp = currentTime();
if (balance == 0) {
setInterestAccruedAsOf(timestamp);
setLastFullPaymentTime(timestamp);
setTotalInterestAccrued(0);
setTermEndTime(timestamp.add(SECONDS_PER_DAY.mul(termInDays)));
}
(uint256 _interestOwed, uint256 _principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp);
balance = balance.add(amount);
updateCreditLineAccounting(balance, _interestOwed, _principalOwed);
require(!_isLate(timestamp), "Cannot drawdown when payments are past due");
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
function setLateFeeApr(uint256 newLateFeeApr) external onlyAdmin {
lateFeeApr = newLateFeeApr;
}
function setLimit(uint256 newAmount) external onlyAdmin {
require(newAmount <= maxLimit, "Cannot be more than the max limit");
currentLimit = newAmount;
}
function setMaxLimit(uint256 newAmount) external onlyAdmin {
maxLimit = newAmount;
}
function termStartTime() external view returns (uint256) {
return _termStartTime();
}
function isLate() external view override returns (bool) {
return _isLate(block.timestamp);
}
function withinPrincipalGracePeriod() external view override returns (bool) {
if (termEndTime == 0) {
// Loan hasn't started yet
return true;
}
return block.timestamp < _termStartTime().add(principalGracePeriodInDays.mul(SECONDS_PER_DAY));
}
function setTermEndTime(uint256 newTermEndTime) public onlyAdmin {
termEndTime = newTermEndTime;
}
function setNextDueTime(uint256 newNextDueTime) public onlyAdmin {
nextDueTime = newNextDueTime;
}
function setBalance(uint256 newBalance) public onlyAdmin {
balance = newBalance;
}
function setTotalInterestAccrued(uint256 _totalInterestAccrued) public onlyAdmin {
totalInterestAccrued = _totalInterestAccrued;
}
function setInterestOwed(uint256 newInterestOwed) public onlyAdmin {
interestOwed = newInterestOwed;
}
function setPrincipalOwed(uint256 newPrincipalOwed) public onlyAdmin {
principalOwed = newPrincipalOwed;
}
function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) public onlyAdmin {
interestAccruedAsOf = newInterestAccruedAsOf;
}
function setLastFullPaymentTime(uint256 newLastFullPaymentTime) public onlyAdmin {
lastFullPaymentTime = newLastFullPaymentTime;
}
/**
* @notice Triggers an assessment of the creditline. Any USDC balance available in the creditline is applied
* towards the interest and principal.
* @return Any amount remaining after applying payments towards the interest and principal
* @return Amount applied towards interest
* @return Amount applied towards principal
*/
function assess()
public
onlyAdmin
returns (
uint256,
uint256,
uint256
)
{
// Do not assess until a full period has elapsed or past due
require(balance > 0, "Must have balance to assess credit line");
// Don't assess credit lines early!
if (currentTime() < nextDueTime && !_isLate(currentTime())) {
return (0, 0, 0);
}
uint256 timeToAssess = calculateNextDueTime();
setNextDueTime(timeToAssess);
// We always want to assess for the most recently *past* nextDueTime.
// So if the recalculation above sets the nextDueTime into the future,
// then ensure we pass in the one just before this.
if (timeToAssess > currentTime()) {
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
timeToAssess = timeToAssess.sub(secondsPerPeriod);
}
return handlePayment(getUSDCBalance(address(this)), timeToAssess);
}
function calculateNextDueTime() internal view returns (uint256) {
uint256 newNextDueTime = nextDueTime;
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
uint256 curTimestamp = currentTime();
// You must have just done your first drawdown
if (newNextDueTime == 0 && balance > 0) {
return curTimestamp.add(secondsPerPeriod);
}
// Active loan that has entered a new period, so return the *next* newNextDueTime.
// But never return something after the termEndTime
if (balance > 0 && curTimestamp >= newNextDueTime) {
uint256 secondsToAdvance = (curTimestamp.sub(newNextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod);
newNextDueTime = newNextDueTime.add(secondsToAdvance);
return Math.min(newNextDueTime, termEndTime);
}
// You're paid off, or have not taken out a loan yet, so no next due time.
if (balance == 0 && newNextDueTime != 0) {
return 0;
}
// Active loan in current period, where we've already set the newNextDueTime correctly, so should not change.
if (balance > 0 && curTimestamp < newNextDueTime) {
return newNextDueTime;
}
revert("Error: could not calculate next due time.");
}
function currentTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function _isLate(uint256 timestamp) internal view returns (bool) {
uint256 secondsElapsedSinceFullPayment = timestamp.sub(lastFullPaymentTime);
return balance > 0 && secondsElapsedSinceFullPayment > paymentPeriodInDays.mul(SECONDS_PER_DAY);
}
function _termStartTime() internal view returns (uint256) {
return termEndTime.sub(SECONDS_PER_DAY.mul(termInDays));
}
/**
* @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool.
* It also updates all the accounting variables. Note that interest is always paid back first, then principal.
* Any extra after paying the minimum will go towards existing principal (reducing the
* effective interest rate). Any extra after the full loan has been paid off will remain in the
* USDC Balance of the creditLine, where it will be automatically used for the next drawdown.
* @param paymentAmount The amount, in USDC atomic units, to be applied
* @param timestamp The timestamp on which accrual calculations should be based. This allows us
* to be precise when we assess a Credit Line
*/
function handlePayment(uint256 paymentAmount, uint256 timestamp)
internal
returns (
uint256,
uint256,
uint256
)
{
(uint256 newInterestOwed, uint256 newPrincipalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp);
Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(
paymentAmount,
balance,
newInterestOwed,
newPrincipalOwed
);
uint256 newBalance = balance.sub(pa.principalPayment);
// Apply any additional payment towards the balance
newBalance = newBalance.sub(pa.additionalBalancePayment);
uint256 totalPrincipalPayment = balance.sub(newBalance);
uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment);
updateCreditLineAccounting(
newBalance,
newInterestOwed.sub(pa.interestPayment),
newPrincipalOwed.sub(pa.principalPayment)
);
assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount);
return (paymentRemaining, pa.interestPayment, totalPrincipalPayment);
}
function updateAndGetInterestAndPrincipalOwedAsOf(uint256 timestamp) internal returns (uint256, uint256) {
(uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(
this,
timestamp,
config.getLatenessGracePeriodInDays()
);
if (interestAccrued > 0) {
// If we've accrued any interest, update interestAccruedAsOf to the time that we've
// calculated interest for. If we've not accrued any interest, then we keep the old value so the next
// time the entire period is taken into account.
setInterestAccruedAsOf(timestamp);
totalInterestAccrued = totalInterestAccrued.add(interestAccrued);
}
return (interestOwed.add(interestAccrued), principalOwed.add(principalAccrued));
}
function updateCreditLineAccounting(
uint256 newBalance,
uint256 newInterestOwed,
uint256 newPrincipalOwed
) internal nonReentrant {
setBalance(newBalance);
setInterestOwed(newInterestOwed);
setPrincipalOwed(newPrincipalOwed);
// This resets lastFullPaymentTime. These conditions assure that they have
// indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown)
uint256 _nextDueTime = nextDueTime;
if (newInterestOwed == 0 && _nextDueTime != 0) {
// If interest was fully paid off, then set the last full payment as the previous due time
uint256 mostRecentLastDueTime;
if (currentTime() < _nextDueTime) {
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
mostRecentLastDueTime = _nextDueTime.sub(secondsPerPeriod);
} else {
mostRecentLastDueTime = _nextDueTime;
}
setLastFullPaymentTime(mostRecentLastDueTime);
}
setNextDueTime(calculateNextDueTime());
}
function getUSDCBalance(address _address) internal view returns (uint256) {
return config.getUSDC().balanceOf(_address);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
// solhint-disable
// Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5**18`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../interfaces/IERC20withDec.sol";
import "../protocol/core/GoldfinchConfig.sol";
import "../protocol/core/ConfigHelper.sol";
import "../protocol/core/TranchedPool.sol";
contract TestTranchedPool is TranchedPool {
function _collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) public {
collectInterestAndPrincipal(from, interest, principal);
}
function _setSeniorTranchePrincipalDeposited(uint256 principalDeposited) public {
poolSlices[poolSlices.length - 1].seniorTranche.principalDeposited = principalDeposited;
}
function _setLimit(uint256 limit) public {
creditLine.setLimit(limit);
}
function _modifyJuniorTrancheLockedUntil(uint256 lockedUntil) public {
poolSlices[poolSlices.length - 1].juniorTranche.lockedUntil = lockedUntil;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/IV2CreditLine.sol";
import "../../interfaces/IPoolTokens.sol";
import "./GoldfinchConfig.sol";
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "../../library/SafeERC20Transfer.sol";
import "./TranchingLogic.sol";
contract TranchedPool is BaseUpgradeablePausable, ITranchedPool, SafeERC20Transfer {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
using TranchingLogic for PoolSlice;
using TranchingLogic for TrancheInfo;
bytes32 public constant LOCKER_ROLE = keccak256("LOCKER_ROLE");
bytes32 public constant SENIOR_ROLE = keccak256("SENIOR_ROLE");
uint256 public constant FP_SCALING_FACTOR = 1e18;
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
uint256 public constant ONE_HUNDRED = 100; // Need this because we cannot call .div on a literal 100
uint256 public constant NUM_TRANCHES_PER_SLICE = 2;
uint256 public juniorFeePercent;
bool public drawdownsPaused;
uint256[] public allowedUIDTypes;
uint256 public totalDeployed;
uint256 public fundableAt;
PoolSlice[] public poolSlices;
event DepositMade(address indexed owner, uint256 indexed tranche, uint256 indexed tokenId, uint256 amount);
event WithdrawalMade(
address indexed owner,
uint256 indexed tranche,
uint256 indexed tokenId,
uint256 interestWithdrawn,
uint256 principalWithdrawn
);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
event TranchedPoolAssessed(address indexed pool);
event PaymentApplied(
address indexed payer,
address indexed pool,
uint256 interestAmount,
uint256 principalAmount,
uint256 remainingAmount,
uint256 reserveAmount
);
// Note: This has to exactly match the even in the TranchingLogic library for events to be emitted
// correctly
event SharePriceUpdated(
address indexed pool,
uint256 indexed tranche,
uint256 principalSharePrice,
int256 principalDelta,
uint256 interestSharePrice,
int256 interestDelta
);
event ReserveFundsCollected(address indexed from, uint256 amount);
event CreditLineMigrated(address indexed oldCreditLine, address indexed newCreditLine);
event DrawdownMade(address indexed borrower, uint256 amount);
event DrawdownsPaused(address indexed pool);
event DrawdownsUnpaused(address indexed pool);
event EmergencyShutdown(address indexed pool);
event TrancheLocked(address indexed pool, uint256 trancheId, uint256 lockedUntil);
event SliceCreated(address indexed pool, uint256 sliceId);
function initialize(
address _config,
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) public override initializer {
require(address(_config) != address(0) && address(_borrower) != address(0), "Config/borrower invalid");
config = GoldfinchConfig(_config);
address owner = config.protocolAdminAddress();
require(owner != address(0), "Owner invalid");
__BaseUpgradeablePausable__init(owner);
_initializeNextSlice(_fundableAt);
createAndSetCreditLine(
_borrower,
_limit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays
);
createdAt = block.timestamp;
juniorFeePercent = _juniorFeePercent;
if (_allowedUIDTypes.length == 0) {
uint256[1] memory defaultAllowedUIDTypes = [config.getGo().ID_TYPE_0()];
allowedUIDTypes = defaultAllowedUIDTypes;
} else {
allowedUIDTypes = _allowedUIDTypes;
}
_setupRole(LOCKER_ROLE, _borrower);
_setupRole(LOCKER_ROLE, owner);
_setRoleAdmin(LOCKER_ROLE, OWNER_ROLE);
_setRoleAdmin(SENIOR_ROLE, OWNER_ROLE);
// Give the senior pool the ability to deposit into the senior pool
_setupRole(SENIOR_ROLE, address(config.getSeniorPool()));
// Unlock self for infinite amount
bool success = config.getUSDC().approve(address(this), uint256(-1));
require(success, "Failed to approve USDC");
}
function setAllowedUIDTypes(uint256[] calldata ids) public onlyLocker {
require(
poolSlices[0].juniorTranche.principalDeposited == 0 && poolSlices[0].seniorTranche.principalDeposited == 0,
"Must not have balance"
);
allowedUIDTypes = ids;
}
/**
* @notice Deposit a USDC amount into the pool for a tranche. Mints an NFT to the caller representing the position
* @param tranche The number representing the tranche to deposit into
* @param amount The USDC amount to tranfer from the caller to the pool
* @return tokenId The tokenId of the NFT
*/
function deposit(uint256 tranche, uint256 amount)
public
override
nonReentrant
whenNotPaused
returns (uint256 tokenId)
{
TrancheInfo storage trancheInfo = getTrancheInfo(tranche);
require(trancheInfo.lockedUntil == 0, "Tranche locked");
require(amount > 0, "Must deposit > zero");
require(config.getGo().goOnlyIdTypes(msg.sender, allowedUIDTypes), "Address not go-listed");
require(block.timestamp > fundableAt, "Not open for funding");
// senior tranche ids are always odd numbered
if (_isSeniorTrancheId(trancheInfo.id)) {
require(hasRole(SENIOR_ROLE, _msgSender()), "Req SENIOR_ROLE");
}
trancheInfo.principalDeposited = trancheInfo.principalDeposited.add(amount);
IPoolTokens.MintParams memory params = IPoolTokens.MintParams({tranche: tranche, principalAmount: amount});
tokenId = config.getPoolTokens().mint(params, msg.sender);
safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount);
emit DepositMade(msg.sender, tranche, tokenId, amount);
return tokenId;
}
function depositWithPermit(
uint256 tranche,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public override returns (uint256 tokenId) {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s);
return deposit(tranche, amount);
}
/**
* @notice Withdraw an already deposited amount if the funds are available
* @param tokenId The NFT representing the position
* @param amount The amount to withdraw (must be <= interest+principal currently available to withdraw)
* @return interestWithdrawn The interest amount that was withdrawn
* @return principalWithdrawn The principal amount that was withdrawn
*/
function withdraw(uint256 tokenId, uint256 amount)
public
override
nonReentrant
whenNotPaused
returns (uint256 interestWithdrawn, uint256 principalWithdrawn)
{
IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche);
return _withdraw(trancheInfo, tokenInfo, tokenId, amount);
}
/**
* @notice Withdraw from many tokens (that the sender owns) in a single transaction
* @param tokenIds An array of tokens ids representing the position
* @param amounts An array of amounts to withdraw from the corresponding tokenIds
*/
function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) public override {
require(tokenIds.length == amounts.length, "TokensIds and Amounts mismatch");
for (uint256 i = 0; i < amounts.length; i++) {
withdraw(tokenIds[i], amounts[i]);
}
}
/**
* @notice Similar to withdraw but will withdraw all available funds
* @param tokenId The NFT representing the position
* @return interestWithdrawn The interest amount that was withdrawn
* @return principalWithdrawn The principal amount that was withdrawn
*/
function withdrawMax(uint256 tokenId)
external
override
nonReentrant
whenNotPaused
returns (uint256 interestWithdrawn, uint256 principalWithdrawn)
{
IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche);
(uint256 interestRedeemable, uint256 principalRedeemable) = redeemableInterestAndPrincipal(trancheInfo, tokenInfo);
uint256 amount = interestRedeemable.add(principalRedeemable);
return _withdraw(trancheInfo, tokenInfo, tokenId, amount);
}
/**
* @notice Draws down the funds (and locks the pool) to the borrower address. Can only be called by the borrower
* @param amount The amount to drawdown from the creditline (must be < limit)
*/
function drawdown(uint256 amount) external override onlyLocker whenNotPaused {
require(!drawdownsPaused, "Drawdowns are paused");
if (!locked()) {
// Assumes the senior pool has invested already (saves the borrower a separate transaction to lock the pool)
_lockPool();
}
// Drawdown only draws down from the current slice for simplicity. It's harder to account for how much
// money is available from previous slices since depositors can redeem after unlock.
PoolSlice storage currentSlice = poolSlices[poolSlices.length.sub(1)];
uint256 amountAvailable = sharePriceToUsdc(
currentSlice.juniorTranche.principalSharePrice,
currentSlice.juniorTranche.principalDeposited
);
amountAvailable = amountAvailable.add(
sharePriceToUsdc(currentSlice.seniorTranche.principalSharePrice, currentSlice.seniorTranche.principalDeposited)
);
require(amount <= amountAvailable, "Insufficient funds in slice");
creditLine.drawdown(amount);
// Update the share price to reflect the amount remaining in the pool
uint256 amountRemaining = amountAvailable.sub(amount);
uint256 oldJuniorPrincipalSharePrice = currentSlice.juniorTranche.principalSharePrice;
uint256 oldSeniorPrincipalSharePrice = currentSlice.seniorTranche.principalSharePrice;
currentSlice.juniorTranche.principalSharePrice = currentSlice.juniorTranche.calculateExpectedSharePrice(
amountRemaining,
currentSlice
);
currentSlice.seniorTranche.principalSharePrice = currentSlice.seniorTranche.calculateExpectedSharePrice(
amountRemaining,
currentSlice
);
currentSlice.principalDeployed = currentSlice.principalDeployed.add(amount);
totalDeployed = totalDeployed.add(amount);
address borrower = creditLine.borrower();
safeERC20TransferFrom(config.getUSDC(), address(this), borrower, amount);
emit DrawdownMade(borrower, amount);
emit SharePriceUpdated(
address(this),
currentSlice.juniorTranche.id,
currentSlice.juniorTranche.principalSharePrice,
int256(oldJuniorPrincipalSharePrice.sub(currentSlice.juniorTranche.principalSharePrice)) * -1,
currentSlice.juniorTranche.interestSharePrice,
0
);
emit SharePriceUpdated(
address(this),
currentSlice.seniorTranche.id,
currentSlice.seniorTranche.principalSharePrice,
int256(oldSeniorPrincipalSharePrice.sub(currentSlice.seniorTranche.principalSharePrice)) * -1,
currentSlice.seniorTranche.interestSharePrice,
0
);
}
/**
* @notice Locks the junior tranche, preventing more junior deposits. Gives time for the senior to determine how
* much to invest (ensure leverage ratio cannot change for the period)
*/
function lockJuniorCapital() external override onlyLocker whenNotPaused {
_lockJuniorCapital(poolSlices.length.sub(1));
}
/**
* @notice Locks the pool (locks both senior and junior tranches and starts the drawdown period). Beyond the drawdown
* period, any unused capital is available to withdraw by all depositors
*/
function lockPool() external override onlyLocker whenNotPaused {
_lockPool();
}
function setFundableAt(uint256 newFundableAt) external override onlyLocker {
fundableAt = newFundableAt;
}
function initializeNextSlice(uint256 _fundableAt) external override onlyLocker whenNotPaused {
require(locked(), "Current slice still active");
require(!creditLine.isLate(), "Creditline is late");
require(creditLine.withinPrincipalGracePeriod(), "Beyond principal grace period");
_initializeNextSlice(_fundableAt);
emit SliceCreated(address(this), poolSlices.length.sub(1));
}
/**
* @notice Triggers an assessment of the creditline and the applies the payments according the tranche waterfall
*/
function assess() external override whenNotPaused {
_assess();
}
/**
* @notice Allows repaying the creditline. Collects the USDC amount from the sender and triggers an assess
* @param amount The amount to repay
*/
function pay(uint256 amount) external override whenNotPaused {
require(amount > 0, "Must pay more than zero");
collectPayment(amount);
_assess();
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
creditLine.updateGoldfinchConfig();
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
/**
* @notice Pauses the pool and sweeps any remaining funds to the treasury reserve.
*/
function emergencyShutdown() public onlyAdmin {
if (!paused()) {
pause();
}
IERC20withDec usdc = config.getUSDC();
address reserveAddress = config.reserveAddress();
// Sweep any funds to community reserve
uint256 poolBalance = usdc.balanceOf(address(this));
if (poolBalance > 0) {
safeERC20Transfer(usdc, reserveAddress, poolBalance);
}
uint256 clBalance = usdc.balanceOf(address(creditLine));
if (clBalance > 0) {
safeERC20TransferFrom(usdc, address(creditLine), reserveAddress, clBalance);
}
emit EmergencyShutdown(address(this));
}
/**
* @notice Pauses all drawdowns (but not deposits/withdraws)
*/
function pauseDrawdowns() public onlyAdmin {
drawdownsPaused = true;
emit DrawdownsPaused(address(this));
}
/**
* @notice Unpause drawdowns
*/
function unpauseDrawdowns() public onlyAdmin {
drawdownsPaused = false;
emit DrawdownsUnpaused(address(this));
}
/**
* @notice Migrates the accounting variables from the current creditline to a brand new one
* @param _borrower The borrower address
* @param _maxLimit The new max limit
* @param _interestApr The new interest APR
* @param _paymentPeriodInDays The new payment period in days
* @param _termInDays The new term in days
* @param _lateFeeApr The new late fee APR
*/
function migrateCreditLine(
address _borrower,
uint256 _maxLimit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) public onlyAdmin {
require(_borrower != address(0), "Borrower must not be empty");
require(_paymentPeriodInDays != 0, "Payment period invalid");
require(_termInDays != 0, "Term must not be empty");
address originalClAddr = address(creditLine);
createAndSetCreditLine(
_borrower,
_maxLimit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays
);
address newClAddr = address(creditLine);
TranchingLogic.migrateAccountingVariables(originalClAddr, newClAddr);
TranchingLogic.closeCreditLine(originalClAddr);
address originalBorrower = IV2CreditLine(originalClAddr).borrower();
address newBorrower = IV2CreditLine(newClAddr).borrower();
// Ensure Roles
if (originalBorrower != newBorrower) {
revokeRole(LOCKER_ROLE, originalBorrower);
grantRole(LOCKER_ROLE, newBorrower);
}
// Transfer any funds to new CL
uint256 clBalance = config.getUSDC().balanceOf(originalClAddr);
if (clBalance > 0) {
safeERC20TransferFrom(config.getUSDC(), originalClAddr, newClAddr, clBalance);
}
emit CreditLineMigrated(originalClAddr, newClAddr);
}
/**
* @notice Migrates to a new creditline without copying the accounting variables
*/
function migrateAndSetNewCreditLine(address newCl) public onlyAdmin {
require(newCl != address(0), "Creditline cannot be empty");
address originalClAddr = address(creditLine);
// Transfer any funds to new CL
uint256 clBalance = config.getUSDC().balanceOf(originalClAddr);
if (clBalance > 0) {
safeERC20TransferFrom(config.getUSDC(), originalClAddr, newCl, clBalance);
}
TranchingLogic.closeCreditLine(originalClAddr);
// set new CL
creditLine = IV2CreditLine(newCl);
// sanity check that the new address is in fact a creditline
creditLine.limit();
emit CreditLineMigrated(originalClAddr, address(creditLine));
}
// CreditLine proxy method
function setLimit(uint256 newAmount) external onlyAdmin {
return creditLine.setLimit(newAmount);
}
function setMaxLimit(uint256 newAmount) external onlyAdmin {
return creditLine.setMaxLimit(newAmount);
}
function getTranche(uint256 tranche) public view override returns (TrancheInfo memory) {
return getTrancheInfo(tranche);
}
function numSlices() public view returns (uint256) {
return poolSlices.length;
}
/**
* @notice Converts USDC amounts to share price
* @param amount The USDC amount to convert
* @param totalShares The total shares outstanding
* @return The share price of the input amount
*/
function usdcToSharePrice(uint256 amount, uint256 totalShares) public pure returns (uint256) {
return TranchingLogic.usdcToSharePrice(amount, totalShares);
}
/**
* @notice Converts share price to USDC amounts
* @param sharePrice The share price to convert
* @param totalShares The total shares outstanding
* @return The USDC amount of the input share price
*/
function sharePriceToUsdc(uint256 sharePrice, uint256 totalShares) public pure returns (uint256) {
return TranchingLogic.sharePriceToUsdc(sharePrice, totalShares);
}
/**
* @notice Returns the total junior capital deposited
* @return The total USDC amount deposited into all junior tranches
*/
function totalJuniorDeposits() external view override returns (uint256) {
uint256 total;
for (uint256 i = 0; i < poolSlices.length; i++) {
total = total.add(poolSlices[i].juniorTranche.principalDeposited);
}
return total;
}
/**
* @notice Determines the amount of interest and principal redeemable by a particular tokenId
* @param tokenId The token representing the position
* @return interestRedeemable The interest available to redeem
* @return principalRedeemable The principal available to redeem
*/
function availableToWithdraw(uint256 tokenId)
public
view
override
returns (uint256 interestRedeemable, uint256 principalRedeemable)
{
IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche);
if (currentTime() > trancheInfo.lockedUntil) {
return redeemableInterestAndPrincipal(trancheInfo, tokenInfo);
} else {
return (0, 0);
}
}
/* Internal functions */
function _withdraw(
TrancheInfo storage trancheInfo,
IPoolTokens.TokenInfo memory tokenInfo,
uint256 tokenId,
uint256 amount
) internal returns (uint256 interestWithdrawn, uint256 principalWithdrawn) {
require(config.getPoolTokens().isApprovedOrOwner(msg.sender, tokenId), "Not token owner");
require(config.getGo().goOnlyIdTypes(msg.sender, allowedUIDTypes), "Address not go-listed");
require(amount > 0, "Must withdraw more than zero");
(uint256 interestRedeemable, uint256 principalRedeemable) = redeemableInterestAndPrincipal(trancheInfo, tokenInfo);
uint256 netRedeemable = interestRedeemable.add(principalRedeemable);
require(amount <= netRedeemable, "Invalid redeem amount");
require(currentTime() > trancheInfo.lockedUntil, "Tranche is locked");
// If the tranche has not been locked, ensure the deposited amount is correct
if (trancheInfo.lockedUntil == 0) {
trancheInfo.principalDeposited = trancheInfo.principalDeposited.sub(amount);
}
uint256 interestToRedeem = Math.min(interestRedeemable, amount);
uint256 principalToRedeem = Math.min(principalRedeemable, amount.sub(interestToRedeem));
config.getPoolTokens().redeem(tokenId, principalToRedeem, interestToRedeem);
safeERC20TransferFrom(config.getUSDC(), address(this), msg.sender, principalToRedeem.add(interestToRedeem));
emit WithdrawalMade(msg.sender, tokenInfo.tranche, tokenId, interestToRedeem, principalToRedeem);
return (interestToRedeem, principalToRedeem);
}
function _isSeniorTrancheId(uint256 trancheId) internal pure returns (bool) {
return trancheId.mod(NUM_TRANCHES_PER_SLICE) == 1;
}
function redeemableInterestAndPrincipal(TrancheInfo storage trancheInfo, IPoolTokens.TokenInfo memory tokenInfo)
internal
view
returns (uint256 interestRedeemable, uint256 principalRedeemable)
{
// This supports withdrawing before or after locking because principal share price starts at 1
// and is set to 0 on lock. Interest share price is always 0 until interest payments come back, when it increases
uint256 maxPrincipalRedeemable = sharePriceToUsdc(trancheInfo.principalSharePrice, tokenInfo.principalAmount);
// The principalAmount is used as the totalShares because we want the interestSharePrice to be expressed as a
// percent of total loan value e.g. if the interest is 10% APR, the interestSharePrice should approach a max of 0.1.
uint256 maxInterestRedeemable = sharePriceToUsdc(trancheInfo.interestSharePrice, tokenInfo.principalAmount);
interestRedeemable = maxInterestRedeemable.sub(tokenInfo.interestRedeemed);
principalRedeemable = maxPrincipalRedeemable.sub(tokenInfo.principalRedeemed);
return (interestRedeemable, principalRedeemable);
}
function _lockJuniorCapital(uint256 sliceId) internal {
require(!locked(), "Pool already locked");
require(poolSlices[sliceId].juniorTranche.lockedUntil == 0, "Junior tranche already locked");
uint256 lockedUntil = currentTime().add(config.getDrawdownPeriodInSeconds());
poolSlices[sliceId].juniorTranche.lockedUntil = lockedUntil;
emit TrancheLocked(address(this), poolSlices[sliceId].juniorTranche.id, lockedUntil);
}
function _lockPool() internal {
uint256 sliceId = poolSlices.length.sub(1);
require(poolSlices[sliceId].juniorTranche.lockedUntil > 0, "Junior tranche must be locked");
// Allow locking the pool only once; do not allow extending the lock of an
// already-locked pool. Otherwise the locker could keep the pool locked
// indefinitely, preventing withdrawals.
require(poolSlices[sliceId].seniorTranche.lockedUntil == 0, "Lock cannot be extended");
uint256 currentTotal = poolSlices[sliceId].juniorTranche.principalDeposited.add(
poolSlices[sliceId].seniorTranche.principalDeposited
);
creditLine.setLimit(Math.min(creditLine.limit().add(currentTotal), creditLine.maxLimit()));
// We start the drawdown period, so backers can withdraw unused capital after borrower draws down
uint256 lockPeriod = config.getDrawdownPeriodInSeconds();
poolSlices[sliceId].seniorTranche.lockedUntil = currentTime().add(lockPeriod);
poolSlices[sliceId].juniorTranche.lockedUntil = currentTime().add(lockPeriod);
emit TrancheLocked(
address(this),
poolSlices[sliceId].seniorTranche.id,
poolSlices[sliceId].seniorTranche.lockedUntil
);
emit TrancheLocked(
address(this),
poolSlices[sliceId].juniorTranche.id,
poolSlices[sliceId].juniorTranche.lockedUntil
);
}
function _initializeNextSlice(uint256 newFundableAt) internal {
uint256 numSlices = poolSlices.length;
require(numSlices < 5, "Cannot exceed 5 slices");
poolSlices.push(
PoolSlice({
seniorTranche: TrancheInfo({
id: numSlices.mul(NUM_TRANCHES_PER_SLICE).add(1),
principalSharePrice: usdcToSharePrice(1, 1),
interestSharePrice: 0,
principalDeposited: 0,
lockedUntil: 0
}),
juniorTranche: TrancheInfo({
id: numSlices.mul(NUM_TRANCHES_PER_SLICE).add(2),
principalSharePrice: usdcToSharePrice(1, 1),
interestSharePrice: 0,
principalDeposited: 0,
lockedUntil: 0
}),
totalInterestAccrued: 0,
principalDeployed: 0
})
);
fundableAt = newFundableAt;
}
function collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) internal returns (uint256 totalReserveAmount) {
safeERC20TransferFrom(config.getUSDC(), from, address(this), principal.add(interest), "Failed to collect payment");
uint256 reserveFeePercent = ONE_HUNDRED.div(config.getReserveDenominator()); // Convert the denonminator to percent
ApplyResult memory result = TranchingLogic.applyToAllSeniorTranches(
poolSlices,
interest,
principal,
reserveFeePercent,
totalDeployed,
creditLine,
juniorFeePercent
);
totalReserveAmount = result.reserveDeduction.add(
TranchingLogic.applyToAllJuniorTranches(
poolSlices,
result.interestRemaining,
result.principalRemaining,
reserveFeePercent,
totalDeployed,
creditLine
)
);
sendToReserve(totalReserveAmount);
return totalReserveAmount;
}
// If the senior tranche of the current slice is locked, then the pool is not open to any more deposits
// (could throw off leverage ratio)
function locked() internal view returns (bool) {
return poolSlices[poolSlices.length.sub(1)].seniorTranche.lockedUntil > 0;
}
function createAndSetCreditLine(
address _borrower,
uint256 _maxLimit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) internal {
address _creditLine = config.getGoldfinchFactory().createCreditLine();
creditLine = IV2CreditLine(_creditLine);
creditLine.initialize(
address(config),
address(this), // Set self as the owner
_borrower,
_maxLimit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays
);
}
function getTrancheInfo(uint256 trancheId) internal view returns (TrancheInfo storage) {
require(trancheId > 0 && trancheId <= poolSlices.length.mul(NUM_TRANCHES_PER_SLICE), "Unsupported tranche");
uint256 sliceId = ((trancheId.add(trancheId.mod(NUM_TRANCHES_PER_SLICE))).div(NUM_TRANCHES_PER_SLICE)).sub(1);
PoolSlice storage slice = poolSlices[sliceId];
TrancheInfo storage trancheInfo = trancheId.mod(NUM_TRANCHES_PER_SLICE) == 1
? slice.seniorTranche
: slice.juniorTranche;
return trancheInfo;
}
function currentTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function sendToReserve(uint256 amount) internal {
emit ReserveFundsCollected(address(this), amount);
safeERC20TransferFrom(
config.getUSDC(),
address(this),
config.reserveAddress(),
amount,
"Failed to send to reserve"
);
}
function collectPayment(uint256 amount) internal {
safeERC20TransferFrom(config.getUSDC(), msg.sender, address(creditLine), amount, "Failed to collect payment");
}
function _assess() internal {
// We need to make sure the pool is locked before we allocate rewards to ensure it's not
// possible to game rewards by sandwiching an interest payment to an unlocked pool
// It also causes issues trying to allocate payments to an empty slice (divide by zero)
require(locked(), "Pool is not locked");
uint256 interestAccrued = creditLine.totalInterestAccrued();
(uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = creditLine.assess();
interestAccrued = creditLine.totalInterestAccrued().sub(interestAccrued);
// Split the interest accrued proportionally across slices so we know how much interest goes to each slice
// We need this because the slice start at different times, so we cannot retroactively allocate the interest
// linearly
uint256[] memory principalPaymentsPerSlice = new uint256[](poolSlices.length);
for (uint256 i = 0; i < poolSlices.length; i++) {
uint256 interestForSlice = TranchingLogic.scaleByFraction(
interestAccrued,
poolSlices[i].principalDeployed,
totalDeployed
);
principalPaymentsPerSlice[i] = TranchingLogic.scaleByFraction(
principalPayment,
poolSlices[i].principalDeployed,
totalDeployed
);
poolSlices[i].totalInterestAccrued = poolSlices[i].totalInterestAccrued.add(interestForSlice);
}
if (interestPayment > 0 || principalPayment > 0) {
uint256 reserveAmount = collectInterestAndPrincipal(
address(creditLine),
interestPayment,
principalPayment.add(paymentRemaining)
);
for (uint256 i = 0; i < poolSlices.length; i++) {
poolSlices[i].principalDeployed = poolSlices[i].principalDeployed.sub(principalPaymentsPerSlice[i]);
totalDeployed = totalDeployed.sub(principalPaymentsPerSlice[i]);
}
config.getBackerRewards().allocateRewards(interestPayment);
emit PaymentApplied(
creditLine.borrower(),
address(this),
interestPayment,
principalPayment,
paymentRemaining,
reserveAmount
);
}
emit TranchedPoolAssessed(address(this));
}
modifier onlyLocker() {
require(hasRole(LOCKER_ROLE, msg.sender), "Must have locker role");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
/**
* @title Safe ERC20 Transfer
* @notice Reverts when transfer is not successful
* @author Goldfinch
*/
abstract contract SafeERC20Transfer {
function safeERC20Transfer(
IERC20 erc20,
address to,
uint256 amount,
string memory message
) internal {
require(to != address(0), "Can't send to zero address");
bool success = erc20.transfer(to, amount);
require(success, message);
}
function safeERC20Transfer(
IERC20 erc20,
address to,
uint256 amount
) internal {
safeERC20Transfer(erc20, to, amount, "Failed to transfer ERC20");
}
function safeERC20TransferFrom(
IERC20 erc20,
address from,
address to,
uint256 amount,
string memory message
) internal {
require(to != address(0), "Can't send to zero address");
bool success = erc20.transferFrom(from, to, amount);
require(success, message);
}
function safeERC20TransferFrom(
IERC20 erc20,
address from,
address to,
uint256 amount
) internal {
string memory message = "Failed to transfer ERC20";
safeERC20TransferFrom(erc20, from, to, amount, message);
}
function safeERC20Approve(
IERC20 erc20,
address spender,
uint256 allowance,
string memory message
) internal {
bool success = erc20.approve(spender, allowance);
require(success, message);
}
function safeERC20Approve(
IERC20 erc20,
address spender,
uint256 allowance
) internal {
string memory message = "Failed to approve ERC20";
safeERC20Approve(erc20, spender, allowance, message);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../interfaces/IV2CreditLine.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../external/FixedPoint.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title TranchingLogic
* @notice Library for handling the payments waterfall
* @author Goldfinch
*/
library TranchingLogic {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
event SharePriceUpdated(
address indexed pool,
uint256 indexed tranche,
uint256 principalSharePrice,
int256 principalDelta,
uint256 interestSharePrice,
int256 interestDelta
);
uint256 public constant FP_SCALING_FACTOR = 1e18;
uint256 public constant ONE_HUNDRED = 100; // Need this because we cannot call .div on a literal 100
function usdcToSharePrice(uint256 amount, uint256 totalShares) public pure returns (uint256) {
return totalShares == 0 ? 0 : amount.mul(FP_SCALING_FACTOR).div(totalShares);
}
function sharePriceToUsdc(uint256 sharePrice, uint256 totalShares) public pure returns (uint256) {
return sharePrice.mul(totalShares).div(FP_SCALING_FACTOR);
}
function redeemableInterestAndPrincipal(
ITranchedPool.TrancheInfo storage trancheInfo,
IPoolTokens.TokenInfo memory tokenInfo
) public view returns (uint256 interestRedeemable, uint256 principalRedeemable) {
// This supports withdrawing before or after locking because principal share price starts at 1
// and is set to 0 on lock. Interest share price is always 0 until interest payments come back, when it increases
uint256 maxPrincipalRedeemable = sharePriceToUsdc(trancheInfo.principalSharePrice, tokenInfo.principalAmount);
// The principalAmount is used as the totalShares because we want the interestSharePrice to be expressed as a
// percent of total loan value e.g. if the interest is 10% APR, the interestSharePrice should approach a max of 0.1.
uint256 maxInterestRedeemable = sharePriceToUsdc(trancheInfo.interestSharePrice, tokenInfo.principalAmount);
interestRedeemable = maxInterestRedeemable.sub(tokenInfo.interestRedeemed);
principalRedeemable = maxPrincipalRedeemable.sub(tokenInfo.principalRedeemed);
return (interestRedeemable, principalRedeemable);
}
function calculateExpectedSharePrice(
ITranchedPool.TrancheInfo memory tranche,
uint256 amount,
ITranchedPool.PoolSlice memory slice
) public pure returns (uint256) {
uint256 sharePrice = usdcToSharePrice(amount, tranche.principalDeposited);
return scaleByPercentOwnership(tranche, sharePrice, slice);
}
function scaleForSlice(
ITranchedPool.PoolSlice memory slice,
uint256 amount,
uint256 totalDeployed
) public pure returns (uint256) {
return scaleByFraction(amount, slice.principalDeployed, totalDeployed);
}
// We need to create this struct so we don't run into a stack too deep error due to too many variables
function getSliceInfo(
ITranchedPool.PoolSlice memory slice,
IV2CreditLine creditLine,
uint256 totalDeployed,
uint256 reserveFeePercent
) public view returns (ITranchedPool.SliceInfo memory) {
(uint256 interestAccrued, uint256 principalAccrued) = getTotalInterestAndPrincipal(
slice,
creditLine,
totalDeployed
);
return
ITranchedPool.SliceInfo({
reserveFeePercent: reserveFeePercent,
interestAccrued: interestAccrued,
principalAccrued: principalAccrued
});
}
function getTotalInterestAndPrincipal(
ITranchedPool.PoolSlice memory slice,
IV2CreditLine creditLine,
uint256 totalDeployed
) public view returns (uint256 interestAccrued, uint256 principalAccrued) {
principalAccrued = creditLine.principalOwed();
// In addition to principal actually owed, we need to account for early principal payments
// If the borrower pays back 5K early on a 10K loan, the actual principal accrued should be
// 5K (balance- deployed) + 0 (principal owed)
principalAccrued = totalDeployed.sub(creditLine.balance()).add(principalAccrued);
// Now we need to scale that correctly for the slice we're interested in
principalAccrued = scaleForSlice(slice, principalAccrued, totalDeployed);
// Finally, we need to account for partial drawdowns. e.g. If 20K was deposited, and only 10K was drawn down,
// Then principal accrued should start at 10K (total deposited - principal deployed), not 0. This is because
// share price starts at 1, and is decremented by what was drawn down.
uint256 totalDeposited = slice.seniorTranche.principalDeposited.add(slice.juniorTranche.principalDeposited);
principalAccrued = totalDeposited.sub(slice.principalDeployed).add(principalAccrued);
return (slice.totalInterestAccrued, principalAccrued);
}
function scaleByFraction(
uint256 amount,
uint256 fraction,
uint256 total
) public pure returns (uint256) {
FixedPoint.Unsigned memory totalAsFixedPoint = FixedPoint.fromUnscaledUint(total);
FixedPoint.Unsigned memory fractionAsFixedPoint = FixedPoint.fromUnscaledUint(fraction);
return fractionAsFixedPoint.div(totalAsFixedPoint).mul(amount).div(FP_SCALING_FACTOR).rawValue;
}
function applyToAllSeniorTranches(
ITranchedPool.PoolSlice[] storage poolSlices,
uint256 interest,
uint256 principal,
uint256 reserveFeePercent,
uint256 totalDeployed,
IV2CreditLine creditLine,
uint256 juniorFeePercent
) public returns (ITranchedPool.ApplyResult memory) {
ITranchedPool.ApplyResult memory seniorApplyResult;
for (uint256 i = 0; i < poolSlices.length; i++) {
ITranchedPool.SliceInfo memory sliceInfo = getSliceInfo(
poolSlices[i],
creditLine,
totalDeployed,
reserveFeePercent
);
// Since slices cannot be created when the loan is late, all interest collected can be assumed to split
// pro-rata across the slices. So we scale the interest and principal to the slice
ITranchedPool.ApplyResult memory applyResult = applyToSeniorTranche(
poolSlices[i],
scaleForSlice(poolSlices[i], interest, totalDeployed),
scaleForSlice(poolSlices[i], principal, totalDeployed),
juniorFeePercent,
sliceInfo
);
emitSharePriceUpdatedEvent(poolSlices[i].seniorTranche, applyResult);
seniorApplyResult.interestRemaining = seniorApplyResult.interestRemaining.add(applyResult.interestRemaining);
seniorApplyResult.principalRemaining = seniorApplyResult.principalRemaining.add(applyResult.principalRemaining);
seniorApplyResult.reserveDeduction = seniorApplyResult.reserveDeduction.add(applyResult.reserveDeduction);
}
return seniorApplyResult;
}
function applyToAllJuniorTranches(
ITranchedPool.PoolSlice[] storage poolSlices,
uint256 interest,
uint256 principal,
uint256 reserveFeePercent,
uint256 totalDeployed,
IV2CreditLine creditLine
) public returns (uint256 totalReserveAmount) {
for (uint256 i = 0; i < poolSlices.length; i++) {
ITranchedPool.SliceInfo memory sliceInfo = getSliceInfo(
poolSlices[i],
creditLine,
totalDeployed,
reserveFeePercent
);
// Any remaining interest and principal is then shared pro-rata with the junior slices
ITranchedPool.ApplyResult memory applyResult = applyToJuniorTranche(
poolSlices[i],
scaleForSlice(poolSlices[i], interest, totalDeployed),
scaleForSlice(poolSlices[i], principal, totalDeployed),
sliceInfo
);
emitSharePriceUpdatedEvent(poolSlices[i].juniorTranche, applyResult);
totalReserveAmount = totalReserveAmount.add(applyResult.reserveDeduction);
}
return totalReserveAmount;
}
function emitSharePriceUpdatedEvent(
ITranchedPool.TrancheInfo memory tranche,
ITranchedPool.ApplyResult memory applyResult
) internal {
emit SharePriceUpdated(
address(this),
tranche.id,
tranche.principalSharePrice,
int256(tranche.principalSharePrice.sub(applyResult.oldPrincipalSharePrice)),
tranche.interestSharePrice,
int256(tranche.interestSharePrice.sub(applyResult.oldInterestSharePrice))
);
}
function applyToSeniorTranche(
ITranchedPool.PoolSlice storage slice,
uint256 interestRemaining,
uint256 principalRemaining,
uint256 juniorFeePercent,
ITranchedPool.SliceInfo memory sliceInfo
) public returns (ITranchedPool.ApplyResult memory) {
// First determine the expected share price for the senior tranche. This is the gross amount the senior
// tranche should receive.
uint256 expectedInterestSharePrice = calculateExpectedSharePrice(
slice.seniorTranche,
sliceInfo.interestAccrued,
slice
);
uint256 expectedPrincipalSharePrice = calculateExpectedSharePrice(
slice.seniorTranche,
sliceInfo.principalAccrued,
slice
);
// Deduct the junior fee and the protocol reserve
uint256 desiredNetInterestSharePrice = scaleByFraction(
expectedInterestSharePrice,
ONE_HUNDRED.sub(juniorFeePercent.add(sliceInfo.reserveFeePercent)),
ONE_HUNDRED
);
// Collect protocol fee interest received (we've subtracted this from the senior portion above)
uint256 reserveDeduction = scaleByFraction(interestRemaining, sliceInfo.reserveFeePercent, ONE_HUNDRED);
interestRemaining = interestRemaining.sub(reserveDeduction);
uint256 oldInterestSharePrice = slice.seniorTranche.interestSharePrice;
uint256 oldPrincipalSharePrice = slice.seniorTranche.principalSharePrice;
// Apply the interest remaining so we get up to the netInterestSharePrice
(interestRemaining, principalRemaining) = applyBySharePrice(
slice.seniorTranche,
interestRemaining,
principalRemaining,
desiredNetInterestSharePrice,
expectedPrincipalSharePrice
);
return
ITranchedPool.ApplyResult({
interestRemaining: interestRemaining,
principalRemaining: principalRemaining,
reserveDeduction: reserveDeduction,
oldInterestSharePrice: oldInterestSharePrice,
oldPrincipalSharePrice: oldPrincipalSharePrice
});
}
function applyToJuniorTranche(
ITranchedPool.PoolSlice storage slice,
uint256 interestRemaining,
uint256 principalRemaining,
ITranchedPool.SliceInfo memory sliceInfo
) public returns (ITranchedPool.ApplyResult memory) {
// Then fill up the junior tranche with all the interest remaining, upto the principal share price
uint256 expectedInterestSharePrice = slice.juniorTranche.interestSharePrice.add(
usdcToSharePrice(interestRemaining, slice.juniorTranche.principalDeposited)
);
uint256 expectedPrincipalSharePrice = calculateExpectedSharePrice(
slice.juniorTranche,
sliceInfo.principalAccrued,
slice
);
uint256 oldInterestSharePrice = slice.juniorTranche.interestSharePrice;
uint256 oldPrincipalSharePrice = slice.juniorTranche.principalSharePrice;
(interestRemaining, principalRemaining) = applyBySharePrice(
slice.juniorTranche,
interestRemaining,
principalRemaining,
expectedInterestSharePrice,
expectedPrincipalSharePrice
);
// All remaining interest and principal is applied towards the junior tranche as interest
interestRemaining = interestRemaining.add(principalRemaining);
// Since any principal remaining is treated as interest (there is "extra" interest to be distributed)
// we need to make sure to collect the protocol fee on the additional interest (we only deducted the
// fee on the original interest portion)
uint256 reserveDeduction = scaleByFraction(principalRemaining, sliceInfo.reserveFeePercent, ONE_HUNDRED);
interestRemaining = interestRemaining.sub(reserveDeduction);
principalRemaining = 0;
(interestRemaining, principalRemaining) = applyByAmount(
slice.juniorTranche,
interestRemaining.add(principalRemaining),
0,
interestRemaining.add(principalRemaining),
0
);
return
ITranchedPool.ApplyResult({
interestRemaining: interestRemaining,
principalRemaining: principalRemaining,
reserveDeduction: reserveDeduction,
oldInterestSharePrice: oldInterestSharePrice,
oldPrincipalSharePrice: oldPrincipalSharePrice
});
}
function applyBySharePrice(
ITranchedPool.TrancheInfo storage tranche,
uint256 interestRemaining,
uint256 principalRemaining,
uint256 desiredInterestSharePrice,
uint256 desiredPrincipalSharePrice
) public returns (uint256, uint256) {
uint256 desiredInterestAmount = desiredAmountFromSharePrice(
desiredInterestSharePrice,
tranche.interestSharePrice,
tranche.principalDeposited
);
uint256 desiredPrincipalAmount = desiredAmountFromSharePrice(
desiredPrincipalSharePrice,
tranche.principalSharePrice,
tranche.principalDeposited
);
return applyByAmount(tranche, interestRemaining, principalRemaining, desiredInterestAmount, desiredPrincipalAmount);
}
function applyByAmount(
ITranchedPool.TrancheInfo storage tranche,
uint256 interestRemaining,
uint256 principalRemaining,
uint256 desiredInterestAmount,
uint256 desiredPrincipalAmount
) public returns (uint256, uint256) {
uint256 totalShares = tranche.principalDeposited;
uint256 newSharePrice;
(interestRemaining, newSharePrice) = applyToSharePrice(
interestRemaining,
tranche.interestSharePrice,
desiredInterestAmount,
totalShares
);
tranche.interestSharePrice = newSharePrice;
(principalRemaining, newSharePrice) = applyToSharePrice(
principalRemaining,
tranche.principalSharePrice,
desiredPrincipalAmount,
totalShares
);
tranche.principalSharePrice = newSharePrice;
return (interestRemaining, principalRemaining);
}
function migrateAccountingVariables(address originalClAddr, address newClAddr) public {
IV2CreditLine originalCl = IV2CreditLine(originalClAddr);
IV2CreditLine newCl = IV2CreditLine(newClAddr);
// Copy over all accounting variables
newCl.setBalance(originalCl.balance());
newCl.setLimit(originalCl.limit());
newCl.setInterestOwed(originalCl.interestOwed());
newCl.setPrincipalOwed(originalCl.principalOwed());
newCl.setTermEndTime(originalCl.termEndTime());
newCl.setNextDueTime(originalCl.nextDueTime());
newCl.setInterestAccruedAsOf(originalCl.interestAccruedAsOf());
newCl.setLastFullPaymentTime(originalCl.lastFullPaymentTime());
newCl.setTotalInterestAccrued(originalCl.totalInterestAccrued());
}
function closeCreditLine(address originalCl) public {
// Close out old CL
IV2CreditLine oldCreditLine = IV2CreditLine(originalCl);
oldCreditLine.setBalance(0);
oldCreditLine.setLimit(0);
oldCreditLine.setMaxLimit(0);
}
function desiredAmountFromSharePrice(
uint256 desiredSharePrice,
uint256 actualSharePrice,
uint256 totalShares
) public pure returns (uint256) {
// If the desired share price is lower, then ignore it, and leave it unchanged
if (desiredSharePrice < actualSharePrice) {
desiredSharePrice = actualSharePrice;
}
uint256 sharePriceDifference = desiredSharePrice.sub(actualSharePrice);
return sharePriceToUsdc(sharePriceDifference, totalShares);
}
function applyToSharePrice(
uint256 amountRemaining,
uint256 currentSharePrice,
uint256 desiredAmount,
uint256 totalShares
) public pure returns (uint256, uint256) {
// If no money left to apply, or don't need any changes, return the original amounts
if (amountRemaining == 0 || desiredAmount == 0) {
return (amountRemaining, currentSharePrice);
}
if (amountRemaining < desiredAmount) {
// We don't have enough money to adjust share price to the desired level. So just use whatever amount is left
desiredAmount = amountRemaining;
}
uint256 sharePriceDifference = usdcToSharePrice(desiredAmount, totalShares);
return (amountRemaining.sub(desiredAmount), currentSharePrice.add(sharePriceDifference));
}
function scaleByPercentOwnership(
ITranchedPool.TrancheInfo memory tranche,
uint256 amount,
ITranchedPool.PoolSlice memory slice
) public pure returns (uint256) {
uint256 totalDeposited = slice.juniorTranche.principalDeposited.add(slice.seniorTranche.principalDeposited);
return scaleByFraction(amount, tranche.principalDeposited, totalDeposited);
}
}
// SPDX-License-Identifier: GPL-3.0-only
// solhint-disable-next-line max-line-length
// Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/MerkleDistributor.sol.
pragma solidity 0.6.12;
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IERC20withDec.sol";
import "../interfaces/IMerkleDirectDistributor.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
contract MerkleDirectDistributor is IMerkleDirectDistributor, BaseUpgradeablePausable {
using SafeERC20 for IERC20withDec;
address public override gfi;
bytes32 public override merkleRoot;
// @dev This is a packed array of booleans.
mapping(uint256 => uint256) private acceptedBitMap;
function initialize(
address owner,
address _gfi,
bytes32 _merkleRoot
) public initializer {
require(owner != address(0), "Owner address cannot be empty");
require(_gfi != address(0), "GFI address cannot be empty");
require(_merkleRoot != 0, "Invalid Merkle root");
__BaseUpgradeablePausable__init(owner);
gfi = _gfi;
merkleRoot = _merkleRoot;
}
function isGrantAccepted(uint256 index) public view override returns (bool) {
uint256 acceptedWordIndex = index / 256;
uint256 acceptedBitIndex = index % 256;
uint256 acceptedWord = acceptedBitMap[acceptedWordIndex];
uint256 mask = (1 << acceptedBitIndex);
return acceptedWord & mask == mask;
}
function _setGrantAccepted(uint256 index) private {
uint256 acceptedWordIndex = index / 256;
uint256 acceptedBitIndex = index % 256;
acceptedBitMap[acceptedWordIndex] = acceptedBitMap[acceptedWordIndex] | (1 << acceptedBitIndex);
}
function acceptGrant(
uint256 index,
uint256 amount,
bytes32[] calldata merkleProof
) external override whenNotPaused {
require(!isGrantAccepted(index), "Grant already accepted");
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(index, msg.sender, amount));
require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof");
// Mark it accepted and perform the granting.
_setGrantAccepted(index);
IERC20withDec(gfi).safeTransfer(msg.sender, amount);
emit GrantAccepted(index, msg.sender, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: GPL-3.0-only
// solhint-disable-next-line max-line-length
// Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/interfaces/IMerkleDistributor.sol.
pragma solidity 0.6.12;
/// @notice Enables the transfer of GFI rewards (referred to as a "grant"), if the grant details exist in this
/// contract's Merkle root.
interface IMerkleDirectDistributor {
/// @notice Returns the address of the GFI contract that is the token distributed as rewards by
/// this contract.
function gfi() external view returns (address);
/// @notice Returns the merkle root of the merkle tree containing grant details available to accept.
function merkleRoot() external view returns (bytes32);
/// @notice Returns true if the index has been marked accepted.
function isGrantAccepted(uint256 index) external view returns (bool);
/// @notice Causes the sender to accept the grant consisting of the given details. Reverts if
/// the inputs (which includes who the sender is) are invalid.
function acceptGrant(
uint256 index,
uint256 amount,
bytes32[] calldata merkleProof
) external;
/// @notice This event is triggered whenever a call to #acceptGrant succeeds.
event GrantAccepted(uint256 indexed index, address indexed account, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/Pool.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../protocol/core/CreditLine.sol";
contract TestCreditLine is CreditLine {}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/Accountant.sol";
import "../protocol/core/CreditLine.sol";
contract TestAccountant {
function calculateInterestAndPrincipalAccrued(
address creditLineAddress,
uint256 timestamp,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
CreditLine cl = CreditLine(creditLineAddress);
return Accountant.calculateInterestAndPrincipalAccrued(cl, timestamp, lateFeeGracePeriod);
}
function calculateWritedownFor(
address creditLineAddress,
uint256 blockNumber,
uint256 gracePeriod,
uint256 maxLatePeriods
) public view returns (uint256, uint256) {
CreditLine cl = CreditLine(creditLineAddress);
return Accountant.calculateWritedownFor(cl, blockNumber, gracePeriod, maxLatePeriods);
}
function calculateAmountOwedForOneDay(address creditLineAddress) public view returns (FixedPoint.Unsigned memory) {
CreditLine cl = CreditLine(creditLineAddress);
return Accountant.calculateAmountOwedForOneDay(cl);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/IPoolTokens.sol";
import "./Accountant.sol";
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
/**
* @title Goldfinch's SeniorPool contract
* @notice Main entry point for senior LPs (a.k.a. capital providers)
* Automatically invests across borrower pools using an adjustable strategy.
* @author Goldfinch
*/
contract SeniorPool is BaseUpgradeablePausable, ISeniorPool {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
using SafeMath for uint256;
uint256 public compoundBalance;
mapping(ITranchedPool => uint256) public writedowns;
event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares);
event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount);
event InterestCollected(address indexed payer, uint256 amount);
event PrincipalCollected(address indexed payer, uint256 amount);
event ReserveFundsCollected(address indexed user, uint256 amount);
event PrincipalWrittenDown(address indexed tranchedPool, int256 amount);
event InvestmentMadeInSenior(address indexed tranchedPool, uint256 amount);
event InvestmentMadeInJunior(address indexed tranchedPool, uint256 amount);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
// Initialize sharePrice to be identical to the legacy pool. This is in the initializer
// because it must only ever happen once.
sharePrice = config.getPool().sharePrice();
totalLoansOutstanding = config.getCreditDesk().totalLoansOutstanding();
totalWritedowns = config.getCreditDesk().totalWritedowns();
IERC20withDec usdc = config.getUSDC();
// Sanity check the address
usdc.totalSupply();
bool success = usdc.approve(address(this), uint256(-1));
require(success, "Failed to approve USDC");
}
/**
* @notice Deposits `amount` USDC from msg.sender into the SeniorPool, and grants you the
* equivalent value of FIDU tokens
* @param amount The amount of USDC to deposit
*/
function deposit(uint256 amount) public override whenNotPaused nonReentrant returns (uint256 depositShares) {
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
require(amount > 0, "Must deposit more than zero");
// Check if the amount of new shares to be added is within limits
depositShares = getNumShares(amount);
uint256 potentialNewTotalShares = totalShares().add(depositShares);
require(sharesWithinLimit(potentialNewTotalShares), "Deposit would put the senior pool over the total limit.");
emit DepositMade(msg.sender, amount, depositShares);
bool success = doUSDCTransfer(msg.sender, address(this), amount);
require(success, "Failed to transfer for deposit");
config.getFidu().mintTo(msg.sender, depositShares);
return depositShares;
}
/**
* @notice Identical to deposit, except it allows for a passed up signature to permit
* the Senior Pool to move funds on behalf of the user, all within one transaction.
* @param amount The amount of USDC to deposit
* @param v secp256k1 signature component
* @param r secp256k1 signature component
* @param s secp256k1 signature component
*/
function depositWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public override returns (uint256 depositShares) {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s);
return deposit(amount);
}
/**
* @notice Withdraws USDC from the SeniorPool to msg.sender, and burns the equivalent value of FIDU tokens
* @param usdcAmount The amount of USDC to withdraw
*/
function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant returns (uint256 amount) {
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
require(usdcAmount > 0, "Must withdraw more than zero");
// This MUST happen before calculating withdrawShares, otherwise the share price
// changes between calculation and burning of Fidu, which creates a asset/liability mismatch
if (compoundBalance > 0) {
_sweepFromCompound();
}
uint256 withdrawShares = getNumShares(usdcAmount);
return _withdraw(usdcAmount, withdrawShares);
}
/**
* @notice Withdraws USDC (denominated in FIDU terms) from the SeniorPool to msg.sender
* @param fiduAmount The amount of USDC to withdraw in terms of FIDU shares
*/
function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant returns (uint256 amount) {
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
require(fiduAmount > 0, "Must withdraw more than zero");
// This MUST happen before calculating withdrawShares, otherwise the share price
// changes between calculation and burning of Fidu, which creates a asset/liability mismatch
if (compoundBalance > 0) {
_sweepFromCompound();
}
uint256 usdcAmount = getUSDCAmountFromShares(fiduAmount);
uint256 withdrawShares = fiduAmount;
return _withdraw(usdcAmount, withdrawShares);
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
/**
* @notice Moves any USDC still in the SeniorPool to Compound, and tracks the amount internally.
* This is done to earn interest on latent funds until we have other borrowers who can use it.
*
* Requirements:
* - The caller must be an admin.
*/
function sweepToCompound() public override onlyAdmin whenNotPaused {
IERC20 usdc = config.getUSDC();
uint256 usdcBalance = usdc.balanceOf(address(this));
ICUSDCContract cUSDC = config.getCUSDCContract();
// Approve compound to the exact amount
bool success = usdc.approve(address(cUSDC), usdcBalance);
require(success, "Failed to approve USDC for compound");
sweepToCompound(cUSDC, usdcBalance);
// Remove compound approval to be extra safe
success = config.getUSDC().approve(address(cUSDC), 0);
require(success, "Failed to approve USDC for compound");
}
/**
* @notice Moves any USDC from Compound back to the SeniorPool, and recognizes interest earned.
* This is done automatically on drawdown or withdraw, but can be called manually if necessary.
*
* Requirements:
* - The caller must be an admin.
*/
function sweepFromCompound() public override onlyAdmin whenNotPaused {
_sweepFromCompound();
}
/**
* @notice Invest in an ITranchedPool's senior tranche using the senior pool's strategy
* @param pool An ITranchedPool whose senior tranche should be considered for investment
*/
function invest(ITranchedPool pool) public override whenNotPaused nonReentrant {
require(validPool(pool), "Pool must be valid");
if (compoundBalance > 0) {
_sweepFromCompound();
}
ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy();
uint256 amount = strategy.invest(this, pool);
require(amount > 0, "Investment amount must be positive");
approvePool(pool, amount);
pool.deposit(uint256(ITranchedPool.Tranches.Senior), amount);
emit InvestmentMadeInSenior(address(pool), amount);
totalLoansOutstanding = totalLoansOutstanding.add(amount);
}
function estimateInvestment(ITranchedPool pool) public view override returns (uint256) {
require(validPool(pool), "Pool must be valid");
ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy();
return strategy.estimateInvestment(this, pool);
}
/**
* @notice Redeem interest and/or principal from an ITranchedPool investment
* @param tokenId the ID of an IPoolTokens token to be redeemed
*/
function redeem(uint256 tokenId) public override whenNotPaused nonReentrant {
IPoolTokens poolTokens = config.getPoolTokens();
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
(uint256 interestRedeemed, uint256 principalRedeemed) = pool.withdrawMax(tokenId);
_collectInterestAndPrincipal(address(pool), interestRedeemed, principalRedeemed);
}
/**
* @notice Write down an ITranchedPool investment. This will adjust the senior pool's share price
* down if we're considering the investment a loss, or up if the borrower has subsequently
* made repayments that restore confidence that the full loan will be repaid.
* @param tokenId the ID of an IPoolTokens token to be considered for writedown
*/
function writedown(uint256 tokenId) public override whenNotPaused nonReentrant {
IPoolTokens poolTokens = config.getPoolTokens();
require(address(this) == poolTokens.ownerOf(tokenId), "Only tokens owned by the senior pool can be written down");
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
require(validPool(pool), "Pool must be valid");
uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed);
(uint256 writedownPercent, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining);
uint256 prevWritedownAmount = writedowns[pool];
if (writedownPercent == 0 && prevWritedownAmount == 0) {
return;
}
int256 writedownDelta = int256(prevWritedownAmount) - int256(writedownAmount);
writedowns[pool] = writedownAmount;
distributeLosses(writedownDelta);
if (writedownDelta > 0) {
// If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns.
totalWritedowns = totalWritedowns.sub(uint256(writedownDelta));
} else {
totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1));
}
emit PrincipalWrittenDown(address(pool), writedownDelta);
}
/**
* @notice Calculates the writedown amount for a particular pool position
* @param tokenId The token reprsenting the position
* @return The amount in dollars the principal should be written down by
*/
function calculateWritedown(uint256 tokenId) public view override returns (uint256) {
IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed);
(, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining);
return writedownAmount;
}
/**
* @notice Returns the net assests controlled by and owed to the pool
*/
function assets() public view override returns (uint256) {
return
compoundBalance.add(config.getUSDC().balanceOf(address(this))).add(totalLoansOutstanding).sub(totalWritedowns);
}
/**
* @notice Converts and USDC amount to FIDU amount
* @param amount USDC amount to convert to FIDU
*/
function getNumShares(uint256 amount) public view override returns (uint256) {
return usdcToFidu(amount).mul(fiduMantissa()).div(sharePrice);
}
/* Internal Functions */
function _calculateWritedown(ITranchedPool pool, uint256 principal)
internal
view
returns (uint256 writedownPercent, uint256 writedownAmount)
{
return
Accountant.calculateWritedownForPrincipal(
pool.creditLine(),
principal,
currentTime(),
config.getLatenessGracePeriodInDays(),
config.getLatenessMaxDays()
);
}
function currentTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function distributeLosses(int256 writedownDelta) internal {
if (writedownDelta > 0) {
uint256 delta = usdcToSharePrice(uint256(writedownDelta));
sharePrice = sharePrice.add(delta);
} else {
// If delta is negative, convert to positive uint, and sub from sharePrice
uint256 delta = usdcToSharePrice(uint256(writedownDelta * -1));
sharePrice = sharePrice.sub(delta);
}
}
function fiduMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(18);
}
function usdcMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(6);
}
function usdcToFidu(uint256 amount) internal pure returns (uint256) {
return amount.mul(fiduMantissa()).div(usdcMantissa());
}
function fiduToUSDC(uint256 amount) internal pure returns (uint256) {
return amount.div(fiduMantissa().div(usdcMantissa()));
}
function getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) {
return fiduToUSDC(fiduAmount.mul(sharePrice).div(fiduMantissa()));
}
function sharesWithinLimit(uint256 _totalShares) internal view returns (bool) {
return
_totalShares.mul(sharePrice).div(fiduMantissa()) <=
usdcToFidu(config.getNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit)));
}
function doUSDCTransfer(
address from,
address to,
uint256 amount
) internal returns (bool) {
require(to != address(0), "Can't send to zero address");
IERC20withDec usdc = config.getUSDC();
return usdc.transferFrom(from, to, amount);
}
function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal returns (uint256 userAmount) {
IFidu fidu = config.getFidu();
// Determine current shares the address has and the shares requested to withdraw
uint256 currentShares = fidu.balanceOf(msg.sender);
// Ensure the address has enough value in the pool
require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns");
uint256 reserveAmount = usdcAmount.div(config.getWithdrawFeeDenominator());
userAmount = usdcAmount.sub(reserveAmount);
emit WithdrawalMade(msg.sender, userAmount, reserveAmount);
// Send the amounts
bool success = doUSDCTransfer(address(this), msg.sender, userAmount);
require(success, "Failed to transfer for withdraw");
sendToReserve(reserveAmount, msg.sender);
// Burn the shares
fidu.burnFrom(msg.sender, withdrawShares);
return userAmount;
}
function sweepToCompound(ICUSDCContract cUSDC, uint256 usdcAmount) internal {
// Our current design requires we re-normalize by withdrawing everything and recognizing interest gains
// before we can add additional capital to Compound
require(compoundBalance == 0, "Cannot sweep when we already have a compound balance");
require(usdcAmount != 0, "Amount to sweep cannot be zero");
uint256 error = cUSDC.mint(usdcAmount);
require(error == 0, "Sweep to compound failed");
compoundBalance = usdcAmount;
}
function _sweepFromCompound() internal {
ICUSDCContract cUSDC = config.getCUSDCContract();
sweepFromCompound(cUSDC, cUSDC.balanceOf(address(this)));
}
function sweepFromCompound(ICUSDCContract cUSDC, uint256 cUSDCAmount) internal {
uint256 cBalance = compoundBalance;
require(cBalance != 0, "No funds on compound");
require(cUSDCAmount != 0, "Amount to sweep cannot be zero");
IERC20 usdc = config.getUSDC();
uint256 preRedeemUSDCBalance = usdc.balanceOf(address(this));
uint256 cUSDCExchangeRate = cUSDC.exchangeRateCurrent();
uint256 redeemedUSDC = cUSDCToUSDC(cUSDCExchangeRate, cUSDCAmount);
uint256 error = cUSDC.redeem(cUSDCAmount);
uint256 postRedeemUSDCBalance = usdc.balanceOf(address(this));
require(error == 0, "Sweep from compound failed");
require(postRedeemUSDCBalance.sub(preRedeemUSDCBalance) == redeemedUSDC, "Unexpected redeem amount");
uint256 interestAccrued = redeemedUSDC.sub(cBalance);
uint256 reserveAmount = interestAccrued.div(config.getReserveDenominator());
uint256 poolAmount = interestAccrued.sub(reserveAmount);
_collectInterestAndPrincipal(address(this), poolAmount, 0);
if (reserveAmount > 0) {
sendToReserve(reserveAmount, address(cUSDC));
}
compoundBalance = 0;
}
function cUSDCToUSDC(uint256 exchangeRate, uint256 amount) internal pure returns (uint256) {
// See https://compound.finance/docs#protocol-math
// But note, the docs and reality do not agree. Docs imply that that exchange rate is
// scaled by 1e18, but tests and mainnet forking make it appear to be scaled by 1e16
// 1e16 is also what Sheraz at Certik said.
uint256 usdcDecimals = 6;
uint256 cUSDCDecimals = 8;
// We multiply in the following order, for the following reasons...
// Amount in cToken (1e8)
// Amount in USDC (but scaled by 1e16, cause that's what exchange rate decimals are)
// Downscale to cToken decimals (1e8)
// Downscale from cToken to USDC decimals (8 to 6)
return amount.mul(exchangeRate).div(10**(18 + usdcDecimals - cUSDCDecimals)).div(10**2);
}
function _collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) internal {
uint256 increment = usdcToSharePrice(interest);
sharePrice = sharePrice.add(increment);
if (interest > 0) {
emit InterestCollected(from, interest);
}
if (principal > 0) {
emit PrincipalCollected(from, principal);
totalLoansOutstanding = totalLoansOutstanding.sub(principal);
}
}
function sendToReserve(uint256 amount, address userForEvent) internal {
emit ReserveFundsCollected(userForEvent, amount);
bool success = doUSDCTransfer(address(this), config.reserveAddress(), amount);
require(success, "Reserve transfer was not successful");
}
function usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) {
return usdcToFidu(usdcAmount).mul(fiduMantissa()).div(totalShares());
}
function totalShares() internal view returns (uint256) {
return config.getFidu().totalSupply();
}
function validPool(ITranchedPool pool) internal view returns (bool) {
return config.getPoolTokens().validPool(address(pool));
}
function approvePool(ITranchedPool pool, uint256 allowance) internal {
IERC20withDec usdc = config.getUSDC();
bool success = usdc.approve(address(pool), allowance);
require(success, "Failed to approve USDC");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/SeniorPool.sol";
contract TestSeniorPool is SeniorPool {
function _getNumShares(uint256 amount) public view returns (uint256) {
return getNumShares(amount);
}
function _usdcMantissa() public pure returns (uint256) {
return usdcMantissa();
}
function _fiduMantissa() public pure returns (uint256) {
return fiduMantissa();
}
function _usdcToFidu(uint256 amount) public pure returns (uint256) {
return usdcToFidu(amount);
}
function _setSharePrice(uint256 newSharePrice) public returns (uint256) {
sharePrice = newSharePrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "../external/ERC721PresetMinterPauserAutoId.sol";
import "../interfaces/IERC20withDec.sol";
import "../interfaces/ICommunityRewards.sol";
import "../protocol/core/GoldfinchConfig.sol";
import "../protocol/core/ConfigHelper.sol";
import "../library/CommunityRewardsVesting.sol";
contract CommunityRewards is ICommunityRewards, ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20withDec;
using ConfigHelper for GoldfinchConfig;
using CommunityRewardsVesting for CommunityRewardsVesting.Rewards;
/* ========== EVENTS ========== */
event GoldfinchConfigUpdated(address indexed who, address configAddress);
/* ========== STATE VARIABLES ========== */
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
bytes32 public constant DISTRIBUTOR_ROLE = keccak256("DISTRIBUTOR_ROLE");
GoldfinchConfig public config;
/// @notice Total rewards available for granting, denominated in `rewardsToken()`
uint256 public rewardsAvailable;
/// @notice Token launch time in seconds. This is used in vesting.
uint256 public tokenLaunchTimeInSeconds;
/// @dev NFT tokenId => rewards grant
mapping(uint256 => CommunityRewardsVesting.Rewards) public grants;
// solhint-disable-next-line func-name-mixedcase
function __initialize__(
address owner,
GoldfinchConfig _config,
uint256 _tokenLaunchTimeInSeconds
) external initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained("Goldfinch V2 Community Rewards Tokens", "GFI-V2-CR");
__ERC721Pausable_init_unchained();
__AccessControl_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(OWNER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setupRole(DISTRIBUTOR_ROLE, owner);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(DISTRIBUTOR_ROLE, OWNER_ROLE);
tokenLaunchTimeInSeconds = _tokenLaunchTimeInSeconds;
config = _config;
}
/* ========== VIEWS ========== */
/// @notice The token being disbursed as rewards
function rewardsToken() public view override returns (IERC20withDec) {
return config.getGFI();
}
/// @notice Returns the rewards claimable by a given grant token, taking into
/// account vesting schedule.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function claimableRewards(uint256 tokenId) public view override returns (uint256 rewards) {
return grants[tokenId].claimable();
}
/// @notice Returns the rewards that will have vested for some grant with the given params.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function totalVestedAt(
uint256 start,
uint256 end,
uint256 granted,
uint256 cliffLength,
uint256 vestingInterval,
uint256 revokedAt,
uint256 time
) external pure override returns (uint256 rewards) {
return CommunityRewardsVesting.getTotalVestedAt(start, end, granted, cliffLength, vestingInterval, revokedAt, time);
}
/* ========== MUTATIVE, ADMIN-ONLY FUNCTIONS ========== */
/// @notice Transfer rewards from msg.sender, to be used for reward distribution
function loadRewards(uint256 rewards) external override onlyAdmin {
require(rewards > 0, "Cannot load 0 rewards");
rewardsAvailable = rewardsAvailable.add(rewards);
rewardsToken().safeTransferFrom(msg.sender, address(this), rewards);
emit RewardAdded(rewards);
}
/// @notice Revokes rewards that have not yet vested, for a grant. The unvested rewards are
/// now considered available for allocation in another grant.
/// @param tokenId The tokenId corresponding to the grant whose unvested rewards to revoke.
function revokeGrant(uint256 tokenId) external override whenNotPaused onlyAdmin {
CommunityRewardsVesting.Rewards storage grant = grants[tokenId];
require(grant.totalGranted > 0, "Grant not defined for token id");
require(grant.revokedAt == 0, "Grant has already been revoked");
uint256 totalUnvested = grant.totalUnvestedAt(block.timestamp);
require(totalUnvested > 0, "Grant has fully vested");
rewardsAvailable = rewardsAvailable.add(totalUnvested);
grant.revokedAt = block.timestamp;
emit GrantRevoked(tokenId, totalUnvested);
}
function setTokenLaunchTimeInSeconds(uint256 _tokenLaunchTimeInSeconds) external onlyAdmin {
tokenLaunchTimeInSeconds = _tokenLaunchTimeInSeconds;
}
/// @notice updates current config
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(_msgSender(), address(config));
}
/* ========== MUTATIVE, NON-ADMIN-ONLY FUNCTIONS ========== */
/// @notice Grant rewards to a recipient. The recipient address receives an
/// an NFT representing their rewards grant. They can present the NFT to `getReward()`
/// to claim their rewards. Rewards vest over a schedule.
/// @param recipient The recipient of the grant.
/// @param amount The amount of `rewardsToken()` to grant.
/// @param vestingLength The duration (in seconds) over which the grant vests.
/// @param cliffLength The duration (in seconds) from the start of the grant, before which has elapsed
/// the vested amount remains 0.
/// @param vestingInterval The interval (in seconds) at which vesting occurs. Must be a factor of `vestingLength`.
function grant(
address recipient,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
) external override nonReentrant whenNotPaused onlyDistributor returns (uint256 tokenId) {
return _grant(recipient, amount, vestingLength, cliffLength, vestingInterval);
}
function _grant(
address recipient,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
) internal returns (uint256 tokenId) {
require(amount > 0, "Cannot grant 0 amount");
require(cliffLength <= vestingLength, "Cliff length cannot exceed vesting length");
require(vestingLength.mod(vestingInterval) == 0, "Vesting interval must be a factor of vesting length");
require(amount <= rewardsAvailable, "Cannot grant amount due to insufficient funds");
rewardsAvailable = rewardsAvailable.sub(amount);
_tokenIdTracker.increment();
tokenId = _tokenIdTracker.current();
grants[tokenId] = CommunityRewardsVesting.Rewards({
totalGranted: amount,
totalClaimed: 0,
startTime: tokenLaunchTimeInSeconds,
endTime: tokenLaunchTimeInSeconds.add(vestingLength),
cliffLength: cliffLength,
vestingInterval: vestingInterval,
revokedAt: 0
});
_mint(recipient, tokenId);
emit Granted(recipient, tokenId, amount, vestingLength, cliffLength, vestingInterval);
return tokenId;
}
/// @notice Claim rewards for a given grant
/// @param tokenId A grant token ID
function getReward(uint256 tokenId) external override nonReentrant whenNotPaused {
require(ownerOf(tokenId) == msg.sender, "access denied");
uint256 reward = claimableRewards(tokenId);
if (reward > 0) {
grants[tokenId].claim(reward);
rewardsToken().safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, tokenId, reward);
}
}
/* ========== MODIFIERS ========== */
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
function isDistributor() public view returns (bool) {
return hasRole(DISTRIBUTOR_ROLE, _msgSender());
}
modifier onlyDistributor() {
require(isDistributor(), "Must have distributor role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol";
import "../interfaces/IERC20withDec.sol";
interface ICommunityRewards is IERC721 {
function rewardsToken() external view returns (IERC20withDec);
function claimableRewards(uint256 tokenId) external view returns (uint256 rewards);
function totalVestedAt(
uint256 start,
uint256 end,
uint256 granted,
uint256 cliffLength,
uint256 vestingInterval,
uint256 revokedAt,
uint256 time
) external pure returns (uint256 rewards);
function grant(
address recipient,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
) external returns (uint256 tokenId);
function loadRewards(uint256 rewards) external;
function revokeGrant(uint256 tokenId) external;
function getReward(uint256 tokenId) external;
event RewardAdded(uint256 reward);
event Granted(
address indexed user,
uint256 indexed tokenId,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
);
event GrantRevoked(uint256 indexed tokenId, uint256 totalUnvested);
event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
library CommunityRewardsVesting {
using SafeMath for uint256;
using CommunityRewardsVesting for Rewards;
/// @dev All time values in the Rewards struct (i.e. `startTime`, `endTime`,
/// `cliffLength`, `vestingInterval`, `revokedAt`) use the same units: seconds. All timestamp
/// values (i.e. `startTime`, `endTime`, `revokedAt`) are seconds since the unix epoch.
/// @dev `cliffLength` is the duration from the start of the grant, before which has elapsed
/// the vested amount remains 0.
/// @dev `vestingInterval` is the interval at which vesting occurs. For rewards to have
/// vested fully only at `endTime`, `vestingInterval` must be a factor of
/// `endTime.sub(startTime)`. If `vestingInterval` is not thusly a factor, the calculation
/// of `totalVestedAt()` would calculate rewards to have fully vested as of the time of the
/// last whole `vestingInterval`'s elapsing before `endTime`.
struct Rewards {
uint256 totalGranted;
uint256 totalClaimed;
uint256 startTime;
uint256 endTime;
uint256 cliffLength;
uint256 vestingInterval;
uint256 revokedAt;
}
function claim(Rewards storage rewards, uint256 reward) internal {
rewards.totalClaimed = rewards.totalClaimed.add(reward);
}
function claimable(Rewards storage rewards) internal view returns (uint256) {
return claimable(rewards, block.timestamp);
}
function claimable(Rewards storage rewards, uint256 time) internal view returns (uint256) {
return rewards.totalVestedAt(time).sub(rewards.totalClaimed);
}
function totalUnvestedAt(Rewards storage rewards, uint256 time) internal view returns (uint256) {
return rewards.totalGranted.sub(rewards.totalVestedAt(time));
}
function totalVestedAt(Rewards storage rewards, uint256 time) internal view returns (uint256) {
return
getTotalVestedAt(
rewards.startTime,
rewards.endTime,
rewards.totalGranted,
rewards.cliffLength,
rewards.vestingInterval,
rewards.revokedAt,
time
);
}
function getTotalVestedAt(
uint256 start,
uint256 end,
uint256 granted,
uint256 cliffLength,
uint256 vestingInterval,
uint256 revokedAt,
uint256 time
) internal pure returns (uint256) {
if (time < start.add(cliffLength)) {
return 0;
}
if (end <= start) {
return granted;
}
uint256 elapsedVestingTimestamp = revokedAt > 0 ? Math.min(revokedAt, time) : time;
uint256 elapsedVestingUnits = (elapsedVestingTimestamp.sub(start)).div(vestingInterval);
uint256 totalVestingUnits = (end.sub(start)).div(vestingInterval);
return Math.min(granted.mul(elapsedVestingUnits).div(totalVestingUnits), granted);
}
}
// SPDX-License-Identifier: GPL-3.0-only
// solhint-disable-next-line max-line-length
// Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/MerkleDistributor.sol.
pragma solidity 0.6.12;
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "../interfaces/ICommunityRewards.sol";
import "../interfaces/IMerkleDistributor.sol";
contract MerkleDistributor is IMerkleDistributor {
address public immutable override communityRewards;
bytes32 public immutable override merkleRoot;
// @dev This is a packed array of booleans.
mapping(uint256 => uint256) private acceptedBitMap;
constructor(address communityRewards_, bytes32 merkleRoot_) public {
require(communityRewards_ != address(0), "Cannot use the null address");
require(merkleRoot_ != 0, "Invalid merkle root provided");
communityRewards = communityRewards_;
merkleRoot = merkleRoot_;
}
function isGrantAccepted(uint256 index) public view override returns (bool) {
uint256 acceptedWordIndex = index / 256;
uint256 acceptedBitIndex = index % 256;
uint256 acceptedWord = acceptedBitMap[acceptedWordIndex];
uint256 mask = (1 << acceptedBitIndex);
return acceptedWord & mask == mask;
}
function _setGrantAccepted(uint256 index) private {
uint256 acceptedWordIndex = index / 256;
uint256 acceptedBitIndex = index % 256;
acceptedBitMap[acceptedWordIndex] = acceptedBitMap[acceptedWordIndex] | (1 << acceptedBitIndex);
}
function acceptGrant(
uint256 index,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval,
bytes32[] calldata merkleProof
) external override {
require(!isGrantAccepted(index), "Grant already accepted");
// Verify the merkle proof.
//
/// @dev Per the Warning in
/// https://github.com/ethereum/solidity/blob/v0.6.12/docs/abi-spec.rst#non-standard-packed-mode,
/// it is important that no more than one of the arguments to `abi.encodePacked()` here be a
/// dynamic type (see definition in
/// https://github.com/ethereum/solidity/blob/v0.6.12/docs/abi-spec.rst#formal-specification-of-the-encoding).
bytes32 node = keccak256(abi.encodePacked(index, msg.sender, amount, vestingLength, cliffLength, vestingInterval));
require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof");
// Mark it accepted and perform the granting.
_setGrantAccepted(index);
uint256 tokenId = ICommunityRewards(communityRewards).grant(
msg.sender,
amount,
vestingLength,
cliffLength,
vestingInterval
);
emit GrantAccepted(tokenId, index, msg.sender, amount, vestingLength, cliffLength, vestingInterval);
}
}
// SPDX-License-Identifier: GPL-3.0-only
// solhint-disable-next-line max-line-length
// Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/interfaces/IMerkleDistributor.sol.
pragma solidity 0.6.12;
/// @notice Enables the granting of a CommunityRewards grant, if the grant details exist in this
/// contract's Merkle root.
interface IMerkleDistributor {
/// @notice Returns the address of the CommunityRewards contract whose grants are distributed by this contract.
function communityRewards() external view returns (address);
/// @notice Returns the merkle root of the merkle tree containing grant details available to accept.
function merkleRoot() external view returns (bytes32);
/// @notice Returns true if the index has been marked accepted.
function isGrantAccepted(uint256 index) external view returns (bool);
/// @notice Causes the sender to accept the grant consisting of the given details. Reverts if
/// the inputs (which includes who the sender is) are invalid.
function acceptGrant(
uint256 index,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval,
bytes32[] calldata merkleProof
) external;
/// @notice This event is triggered whenever a call to #acceptGrant succeeds.
event GrantAccepted(
uint256 indexed tokenId,
uint256 indexed index,
address indexed account,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../core/BaseUpgradeablePausable.sol";
import "../core/ConfigHelper.sol";
import "../core/CreditLine.sol";
import "../core/GoldfinchConfig.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IBorrower.sol";
import "@opengsn/gsn/contracts/BaseRelayRecipient.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title Goldfinch's Borrower contract
* @notice These contracts represent the a convenient way for a borrower to interact with Goldfinch
* They are 100% optional. However, they let us add many sophisticated and convient features for borrowers
* while still keeping our core protocol small and secure. We therefore expect most borrowers will use them.
* This contract is the "official" borrower contract that will be maintained by Goldfinch governance. However,
* in theory, anyone can fork or create their own version, or not use any contract at all. The core functionality
* is completely agnostic to whether it is interacting with a contract or an externally owned account (EOA).
* @author Goldfinch
*/
contract Borrower is BaseUpgradeablePausable, BaseRelayRecipient, IBorrower {
using SafeMath for uint256;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
address private constant USDT_ADDRESS = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);
address private constant BUSD_ADDRESS = address(0x4Fabb145d64652a948d72533023f6E7A623C7C53);
address private constant GUSD_ADDRESS = address(0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd);
address private constant DAI_ADDRESS = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
function initialize(address owner, address _config) external override initializer {
require(owner != address(0) && _config != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = GoldfinchConfig(_config);
trustedForwarder = config.trustedForwarderAddress();
// Handle default approvals. Pool, and OneInch for maximum amounts
address oneInch = config.oneInchAddress();
IERC20withDec usdc = config.getUSDC();
usdc.approve(oneInch, uint256(-1));
bytes memory data = abi.encodeWithSignature("approve(address,uint256)", oneInch, uint256(-1));
invoke(USDT_ADDRESS, data);
invoke(BUSD_ADDRESS, data);
invoke(GUSD_ADDRESS, data);
invoke(DAI_ADDRESS, data);
}
function lockJuniorCapital(address poolAddress) external onlyAdmin {
ITranchedPool(poolAddress).lockJuniorCapital();
}
function lockPool(address poolAddress) external onlyAdmin {
ITranchedPool(poolAddress).lockPool();
}
/**
* @notice Allows a borrower to drawdown on their creditline through the CreditDesk.
* @param poolAddress The creditline from which they would like to drawdown
* @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown
* @param addressToSendTo The address where they would like the funds sent. If the zero address is passed,
* it will be defaulted to the contracts address (msg.sender). This is a convenience feature for when they would
* like the funds sent to an exchange or alternate wallet, different from the authentication address
*/
function drawdown(
address poolAddress,
uint256 amount,
address addressToSendTo
) external onlyAdmin {
ITranchedPool(poolAddress).drawdown(amount);
if (addressToSendTo == address(0) || addressToSendTo == address(this)) {
addressToSendTo = _msgSender();
}
transferERC20(config.usdcAddress(), addressToSendTo, amount);
}
function drawdownWithSwapOnOneInch(
address poolAddress,
uint256 amount,
address addressToSendTo,
address toToken,
uint256 minTargetAmount,
uint256[] calldata exchangeDistribution
) public onlyAdmin {
// Drawdown to the Borrower contract
ITranchedPool(poolAddress).drawdown(amount);
// Do the swap
swapOnOneInch(config.usdcAddress(), toToken, amount, minTargetAmount, exchangeDistribution);
// Default to sending to the owner, and don't let funds stay in this contract
if (addressToSendTo == address(0) || addressToSendTo == address(this)) {
addressToSendTo = _msgSender();
}
// Fulfill the send to
bytes memory _data = abi.encodeWithSignature("balanceOf(address)", address(this));
uint256 receivedAmount = toUint256(invoke(toToken, _data));
transferERC20(toToken, addressToSendTo, receivedAmount);
}
function transferERC20(
address token,
address to,
uint256 amount
) public onlyAdmin {
bytes memory _data = abi.encodeWithSignature("transfer(address,uint256)", to, amount);
invoke(token, _data);
}
/**
* @notice Allows a borrower to payback loans by calling the `pay` function directly on the CreditDesk
* @param poolAddress The credit line to be paid back
* @param amount The amount, in USDC atomic units, that the borrower wishes to pay
*/
function pay(address poolAddress, uint256 amount) external onlyAdmin {
IERC20withDec usdc = config.getUSDC();
bool success = usdc.transferFrom(_msgSender(), address(this), amount);
require(success, "Failed to transfer USDC");
_transferAndPay(usdc, poolAddress, amount);
}
function payMultiple(address[] calldata pools, uint256[] calldata amounts) external onlyAdmin {
require(pools.length == amounts.length, "Pools and amounts must be the same length");
uint256 totalAmount;
for (uint256 i = 0; i < amounts.length; i++) {
totalAmount = totalAmount.add(amounts[i]);
}
IERC20withDec usdc = config.getUSDC();
// Do a single transfer, which is cheaper
bool success = usdc.transferFrom(_msgSender(), address(this), totalAmount);
require(success, "Failed to transfer USDC");
for (uint256 i = 0; i < amounts.length; i++) {
_transferAndPay(usdc, pools[i], amounts[i]);
}
}
function payInFull(address poolAddress, uint256 amount) external onlyAdmin {
IERC20withDec usdc = config.getUSDC();
bool success = usdc.transferFrom(_msgSender(), address(this), amount);
require(success, "Failed to transfer USDC");
_transferAndPay(usdc, poolAddress, amount);
require(ITranchedPool(poolAddress).creditLine().balance() == 0, "Failed to fully pay off creditline");
}
function payWithSwapOnOneInch(
address poolAddress,
uint256 originAmount,
address fromToken,
uint256 minTargetAmount,
uint256[] calldata exchangeDistribution
) external onlyAdmin {
transferFrom(fromToken, _msgSender(), address(this), originAmount);
IERC20withDec usdc = config.getUSDC();
swapOnOneInch(fromToken, address(usdc), originAmount, minTargetAmount, exchangeDistribution);
uint256 usdcBalance = usdc.balanceOf(address(this));
_transferAndPay(usdc, poolAddress, usdcBalance);
}
function payMultipleWithSwapOnOneInch(
address[] calldata pools,
uint256[] calldata minAmounts,
uint256 originAmount,
address fromToken,
uint256[] calldata exchangeDistribution
) external onlyAdmin {
require(pools.length == minAmounts.length, "Pools and amounts must be the same length");
uint256 totalMinAmount = 0;
for (uint256 i = 0; i < minAmounts.length; i++) {
totalMinAmount = totalMinAmount.add(minAmounts[i]);
}
transferFrom(fromToken, _msgSender(), address(this), originAmount);
IERC20withDec usdc = config.getUSDC();
swapOnOneInch(fromToken, address(usdc), originAmount, totalMinAmount, exchangeDistribution);
for (uint256 i = 0; i < minAmounts.length; i++) {
_transferAndPay(usdc, pools[i], minAmounts[i]);
}
uint256 remainingUSDC = usdc.balanceOf(address(this));
if (remainingUSDC > 0) {
_transferAndPay(usdc, pools[0], remainingUSDC);
}
}
function _transferAndPay(
IERC20withDec usdc,
address poolAddress,
uint256 amount
) internal {
ITranchedPool pool = ITranchedPool(poolAddress);
// We don't use transferFrom since it would require a separate approval per creditline
bool success = usdc.transfer(address(pool.creditLine()), amount);
require(success, "USDC Transfer to creditline failed");
pool.assess();
}
function transferFrom(
address erc20,
address sender,
address recipient,
uint256 amount
) internal {
bytes memory _data;
// Do a low-level invoke on this transfer, since Tether fails if we use the normal IERC20 interface
_data = abi.encodeWithSignature("transferFrom(address,address,uint256)", sender, recipient, amount);
invoke(address(erc20), _data);
}
function swapOnOneInch(
address fromToken,
address toToken,
uint256 originAmount,
uint256 minTargetAmount,
uint256[] calldata exchangeDistribution
) internal {
bytes memory _data = abi.encodeWithSignature(
"swap(address,address,uint256,uint256,uint256[],uint256)",
fromToken,
toToken,
originAmount,
minTargetAmount,
exchangeDistribution,
0
);
invoke(config.oneInchAddress(), _data);
}
/**
* @notice Performs a generic transaction.
* @param _target The address for the transaction.
* @param _data The data of the transaction.
* Mostly copied from Argent:
* https://github.com/argentlabs/argent-contracts/blob/develop/contracts/wallet/BaseWallet.sol#L111
*/
function invoke(address _target, bytes memory _data) internal returns (bytes memory) {
// External contracts can be compiled with different Solidity versions
// which can cause "revert without reason" when called through,
// for example, a standard IERC20 ABI compiled on the latest version.
// This low-level call avoids that issue.
bool success;
bytes memory _res;
// solhint-disable-next-line avoid-low-level-calls
(success, _res) = _target.call(_data);
if (!success && _res.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
} else if (!success) {
revert("VM: wallet invoke reverted");
}
return _res;
}
function toUint256(bytes memory _bytes) internal pure returns (uint256 value) {
assembly {
value := mload(add(_bytes, 0x20))
}
}
// OpenZeppelin contracts come with support for GSN _msgSender() (which just defaults to msg.sender)
// Since there are two different versions of the function in the hierarchy, we need to instruct solidity to
// use the relay recipient version which can actually pull the real sender from the parameters.
// https://www.notion.so/My-contract-is-using-OpenZeppelin-How-do-I-add-GSN-support-2bee7e9d5f774a0cbb60d3a8de03e9fb
function _msgSender() internal view override(ContextUpgradeSafe, BaseRelayRecipient) returns (address payable) {
return BaseRelayRecipient._msgSender();
}
function _msgData() internal view override(ContextUpgradeSafe, BaseRelayRecipient) returns (bytes memory ret) {
return BaseRelayRecipient._msgData();
}
function versionRecipient() external view override returns (string memory) {
return "2.0.0";
}
}
// SPDX-Licence-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IBorrower {
function initialize(address owner, address _config) external;
}
// SPDX-License-Identifier:MIT
// solhint-disable no-inline-assembly
pragma solidity ^0.6.2;
import "./interfaces/IRelayRecipient.sol";
/**
* A base contract to be inherited by any contract that want to receive relayed transactions
* A subclass must use "_msgSender()" instead of "msg.sender"
*/
abstract contract BaseRelayRecipient is IRelayRecipient {
/*
* Forwarder singleton we accept calls from
*/
address public trustedForwarder;
function isTrustedForwarder(address forwarder) public override view returns(bool) {
return forwarder == trustedForwarder;
}
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal override virtual view returns (address payable ret) {
if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
assembly {
ret := shr(96,calldataload(sub(calldatasize(),20)))
}
} else {
return msg.sender;
}
}
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal override virtual view returns (bytes memory ret) {
if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// we copy the msg.data , except the last 20 bytes (and update the total length)
assembly {
let ptr := mload(0x40)
// copy only size-20 bytes
let size := sub(calldatasize(),20)
// structure RLP data as <offset> <length> <bytes>
mstore(ptr, 0x20)
mstore(add(ptr,32), size)
calldatacopy(add(ptr,64), 0, size)
return(ptr, add(size,64))
}
} else {
return msg.data;
}
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.6.2;
/**
* a contract must implement this interface in order to support relayed transaction.
* It is better to inherit the BaseRelayRecipient as its implementation.
*/
abstract contract IRelayRecipient {
/**
* return if the forwarder is trusted to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function isTrustedForwarder(address forwarder) public virtual view returns(bool);
/**
* return the sender of this call.
* if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
* of the msg.data.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal virtual view returns (address payable);
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal virtual view returns (bytes memory);
function versionRecipient() external virtual view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "./BaseUpgradeablePausable.sol";
import "../../interfaces/IBorrower.sol";
import "../../interfaces/ITranchedPool.sol";
import "./ConfigHelper.sol";
/**
* @title GoldfinchFactory
* @notice Contract that allows us to create other contracts, such as CreditLines and BorrowerContracts
* Note GoldfinchFactory is a legacy name. More properly this can be considered simply the GoldfinchFactory
* @author Goldfinch
*/
contract GoldfinchFactory is BaseUpgradeablePausable {
GoldfinchConfig public config;
/// Role to allow for pool creation
bytes32 public constant BORROWER_ROLE = keccak256("BORROWER_ROLE");
using ConfigHelper for GoldfinchConfig;
event BorrowerCreated(address indexed borrower, address indexed owner);
event PoolCreated(address indexed pool, address indexed borrower);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
event CreditLineCreated(address indexed creditLine);
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
_performUpgrade();
}
function performUpgrade() external onlyAdmin {
_performUpgrade();
}
function _performUpgrade() internal {
if (getRoleAdmin(BORROWER_ROLE) != OWNER_ROLE) {
_setRoleAdmin(BORROWER_ROLE, OWNER_ROLE);
}
}
/**
* @notice Allows anyone to create a CreditLine contract instance
* @dev There is no value to calling this function directly. It is only meant to be called
* by a TranchedPool during it's creation process.
*/
function createCreditLine() external returns (address) {
address creditLine = deployMinimal(config.creditLineImplementationAddress());
emit CreditLineCreated(creditLine);
return creditLine;
}
/**
* @notice Allows anyone to create a Borrower contract instance
* @param owner The address that will own the new Borrower instance
*/
function createBorrower(address owner) external returns (address) {
address _borrower = deployMinimal(config.borrowerImplementationAddress());
IBorrower borrower = IBorrower(_borrower);
borrower.initialize(owner, address(config));
emit BorrowerCreated(address(borrower), owner);
return address(borrower);
}
/**
* @notice Allows anyone to create a new TranchedPool for a single borrower
* @param _borrower The borrower for whom the CreditLine will be created
* @param _juniorFeePercent The percent of senior interest allocated to junior investors, expressed as
* integer percents. eg. 20% is simply 20
* @param _limit The maximum amount a borrower can drawdown from this CreditLine
* @param _interestApr The interest amount, on an annualized basis (APR, so non-compounding), expressed as an integer.
* We assume 18 digits of precision. For example, to submit 15.34%, you would pass up 153400000000000000,
* and 5.34% would be 53400000000000000
* @param _paymentPeriodInDays How many days in each payment period.
* ie. the frequency with which they need to make payments.
* @param _termInDays Number of days in the credit term. It is used to set the `termEndTime` upon first drawdown.
* ie. The credit line should be fully paid off {_termIndays} days after the first drawdown.
* @param _lateFeeApr The additional interest you will pay if you are late. For example, if this is 3%, and your
* normal rate is 15%, then you will pay 18% while you are late. Also expressed as an 18 decimal precision integer
*
* Requirements:
* You are the admin
*/
function createPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) external onlyAdminOrBorrower returns (address pool) {
address tranchedPoolImplAddress = config.tranchedPoolAddress();
pool = deployMinimal(tranchedPoolImplAddress);
ITranchedPool(pool).initialize(
address(config),
_borrower,
_juniorFeePercent,
_limit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays,
_fundableAt,
_allowedUIDTypes
);
emit PoolCreated(pool, _borrower);
config.getPoolTokens().onPoolCreated(pool);
return pool;
}
function createMigratedPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) external onlyCreditDesk returns (address pool) {
address tranchedPoolImplAddress = config.migratedTranchedPoolAddress();
pool = deployMinimal(tranchedPoolImplAddress);
ITranchedPool(pool).initialize(
address(config),
_borrower,
_juniorFeePercent,
_limit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays,
_fundableAt,
_allowedUIDTypes
);
emit PoolCreated(pool, _borrower);
config.getPoolTokens().onPoolCreated(pool);
return pool;
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
// Stolen from:
// https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/ProxyFactory.sol
function deployMinimal(address _logic) internal returns (address proxy) {
bytes20 targetBytes = bytes20(_logic);
// solhint-disable-next-line no-inline-assembly
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
proxy := create(0, clone, 0x37)
}
return proxy;
}
function isBorrower() public view returns (bool) {
return hasRole(BORROWER_ROLE, _msgSender());
}
modifier onlyAdminOrBorrower() {
require(isAdmin() || isBorrower(), "Must have admin or borrower role to perform this action");
_;
}
modifier onlyCreditDesk() {
require(msg.sender == config.creditDeskAddress(), "Only the CreditDesk can call this");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
import "../library/SafeERC20Transfer.sol";
import "../protocol/core/ConfigHelper.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../interfaces/IPoolTokens.sol";
import "../interfaces/ITranchedPool.sol";
import "../interfaces/IBackerRewards.sol";
// Basically, Every time a interest payment comes back
// we keep a running total of dollars (totalInterestReceived) until it reaches the maxInterestDollarsEligible limit
// Every dollar of interest received from 0->maxInterestDollarsEligible
// has a allocated amount of rewards based on a sqrt function.
// When a interest payment comes in for a given Pool or the pool balance increases
// we recalculate the pool's accRewardsPerPrincipalDollar
// equation ref `_calculateNewGrossGFIRewardsForInterestAmount()`:
// (sqrtNewTotalInterest - sqrtOrigTotalInterest) / sqrtMaxInterestDollarsEligible * (totalRewards / totalGFISupply)
// When a PoolToken is minted, we set the mint price to the pool's current accRewardsPerPrincipalDollar
// Every time a PoolToken withdraws rewards, we determine the allocated rewards,
// increase that PoolToken's rewardsClaimed, and transfer the owner the gfi
contract BackerRewards is IBackerRewards, BaseUpgradeablePausable, SafeERC20Transfer {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
using SafeMath for uint256;
struct BackerRewardsInfo {
uint256 accRewardsPerPrincipalDollar; // accumulator gfi per interest dollar
}
struct BackerRewardsTokenInfo {
uint256 rewardsClaimed; // gfi claimed
uint256 accRewardsPerPrincipalDollarAtMint; // Pool's accRewardsPerPrincipalDollar at PoolToken mint()
}
uint256 public totalRewards; // total amount of GFI rewards available, times 1e18
uint256 public maxInterestDollarsEligible; // interest $ eligible for gfi rewards, times 1e18
uint256 public totalInterestReceived; // counter of total interest repayments, times 1e6
uint256 public totalRewardPercentOfTotalGFI; // totalRewards/totalGFISupply, times 1e18
mapping(uint256 => BackerRewardsTokenInfo) public tokens; // poolTokenId -> BackerRewardsTokenInfo
mapping(address => BackerRewardsInfo) public pools; // pool.address -> BackerRewardsInfo
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
}
/**
* @notice Calculates the accRewardsPerPrincipalDollar for a given pool,
when a interest payment is received by the protocol
* @param _interestPaymentAmount The amount of total dollars the interest payment, expects 10^6 value
*/
function allocateRewards(uint256 _interestPaymentAmount) external override onlyPool {
// note: do not use a require statment because that will TranchedPool kill execution
if (_interestPaymentAmount > 0) {
_allocateRewards(_interestPaymentAmount);
}
}
/**
* @notice Set the total gfi rewards and the % of total GFI
* @param _totalRewards The amount of GFI rewards available, expects 10^18 value
*/
function setTotalRewards(uint256 _totalRewards) public onlyAdmin {
totalRewards = _totalRewards;
uint256 totalGFISupply = config.getGFI().totalSupply();
totalRewardPercentOfTotalGFI = _totalRewards.mul(mantissa()).div(totalGFISupply).mul(100);
emit BackerRewardsSetTotalRewards(_msgSender(), _totalRewards, totalRewardPercentOfTotalGFI);
}
/**
* @notice Set the total interest received to date.
This should only be called once on contract deploy.
* @param _totalInterestReceived The amount of interest the protocol has received to date, expects 10^6 value
*/
function setTotalInterestReceived(uint256 _totalInterestReceived) public onlyAdmin {
totalInterestReceived = _totalInterestReceived;
emit BackerRewardsSetTotalInterestReceived(_msgSender(), _totalInterestReceived);
}
/**
* @notice Set the max dollars across the entire protocol that are eligible for GFI rewards
* @param _maxInterestDollarsEligible The amount of interest dollars eligible for GFI rewards, expects 10^18 value
*/
function setMaxInterestDollarsEligible(uint256 _maxInterestDollarsEligible) public onlyAdmin {
maxInterestDollarsEligible = _maxInterestDollarsEligible;
emit BackerRewardsSetMaxInterestDollarsEligible(_msgSender(), _maxInterestDollarsEligible);
}
/**
* @notice When a pool token is minted for multiple drawdowns,
set accRewardsPerPrincipalDollarAtMint to the current accRewardsPerPrincipalDollar price
* @param tokenId Pool token id
*/
function setPoolTokenAccRewardsPerPrincipalDollarAtMint(address poolAddress, uint256 tokenId) external override {
require(_msgSender() == config.poolTokensAddress(), "Invalid sender!");
require(config.getPoolTokens().validPool(poolAddress), "Invalid pool!");
if (tokens[tokenId].accRewardsPerPrincipalDollarAtMint != 0) {
return;
}
IPoolTokens poolTokens = config.getPoolTokens();
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
require(poolAddress == tokenInfo.pool, "PoolAddress must equal PoolToken pool address");
tokens[tokenId].accRewardsPerPrincipalDollarAtMint = pools[tokenInfo.pool].accRewardsPerPrincipalDollar;
}
/**
* @notice Calculate the gross available gfi rewards for a PoolToken
* @param tokenId Pool token id
* @return The amount of GFI claimable
*/
function poolTokenClaimableRewards(uint256 tokenId) public view returns (uint256) {
IPoolTokens poolTokens = config.getPoolTokens();
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
// Note: If a TranchedPool is oversubscribed, reward allocation's scale down proportionately.
uint256 diffOfAccRewardsPerPrincipalDollar = pools[tokenInfo.pool].accRewardsPerPrincipalDollar.sub(
tokens[tokenId].accRewardsPerPrincipalDollarAtMint
);
uint256 rewardsClaimed = tokens[tokenId].rewardsClaimed.mul(mantissa());
/*
equation for token claimable rewards:
token.principalAmount
* (pool.accRewardsPerPrincipalDollar - token.accRewardsPerPrincipalDollarAtMint)
- token.rewardsClaimed
*/
return
usdcToAtomic(tokenInfo.principalAmount).mul(diffOfAccRewardsPerPrincipalDollar).sub(rewardsClaimed).div(
mantissa()
);
}
/**
* @notice PoolToken request to withdraw multiple PoolTokens allocated rewards
* @param tokenIds Array of pool token id
*/
function withdrawMultiple(uint256[] calldata tokenIds) public {
require(tokenIds.length > 0, "TokensIds length must not be 0");
for (uint256 i = 0; i < tokenIds.length; i++) {
withdraw(tokenIds[i]);
}
}
/**
* @notice PoolToken request to withdraw all allocated rewards
* @param tokenId Pool token id
*/
function withdraw(uint256 tokenId) public {
uint256 totalClaimableRewards = poolTokenClaimableRewards(tokenId);
uint256 poolTokenRewardsClaimed = tokens[tokenId].rewardsClaimed;
IPoolTokens poolTokens = config.getPoolTokens();
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
address poolAddr = tokenInfo.pool;
require(config.getPoolTokens().validPool(poolAddr), "Invalid pool!");
require(msg.sender == poolTokens.ownerOf(tokenId), "Must be owner of PoolToken");
BaseUpgradeablePausable pool = BaseUpgradeablePausable(poolAddr);
require(!pool.paused(), "Pool withdraw paused");
ITranchedPool tranchedPool = ITranchedPool(poolAddr);
require(!tranchedPool.creditLine().isLate(), "Pool is late on payments");
tokens[tokenId].rewardsClaimed = poolTokenRewardsClaimed.add(totalClaimableRewards);
safeERC20Transfer(config.getGFI(), poolTokens.ownerOf(tokenId), totalClaimableRewards);
emit BackerRewardsClaimed(_msgSender(), tokenId, totalClaimableRewards);
}
/* Internal functions */
function _allocateRewards(uint256 _interestPaymentAmount) internal {
uint256 _totalInterestReceived = totalInterestReceived;
if (usdcToAtomic(_totalInterestReceived) >= maxInterestDollarsEligible) {
return;
}
address _poolAddress = _msgSender();
// Gross GFI Rewards earned for incoming interest dollars
uint256 newGrossRewards = _calculateNewGrossGFIRewardsForInterestAmount(_interestPaymentAmount);
ITranchedPool pool = ITranchedPool(_poolAddress);
BackerRewardsInfo storage _poolInfo = pools[_poolAddress];
uint256 totalJuniorDeposits = pool.totalJuniorDeposits();
if (totalJuniorDeposits == 0) {
return;
}
// example: (6708203932437400000000 * 10^18) / (100000*10^18)
_poolInfo.accRewardsPerPrincipalDollar = _poolInfo.accRewardsPerPrincipalDollar.add(
newGrossRewards.mul(mantissa()).div(usdcToAtomic(totalJuniorDeposits))
);
totalInterestReceived = _totalInterestReceived.add(_interestPaymentAmount);
}
/**
* @notice Calculate the rewards earned for a given interest payment
* @param _interestPaymentAmount interest payment amount times 1e6
*/
function _calculateNewGrossGFIRewardsForInterestAmount(uint256 _interestPaymentAmount)
internal
view
returns (uint256)
{
uint256 totalGFISupply = config.getGFI().totalSupply();
// incoming interest payment, times * 1e18 divided by 1e6
uint256 interestPaymentAmount = usdcToAtomic(_interestPaymentAmount);
// all-time interest payments prior to the incoming amount, times 1e18
uint256 _previousTotalInterestReceived = usdcToAtomic(totalInterestReceived);
uint256 sqrtOrigTotalInterest = Babylonian.sqrt(_previousTotalInterestReceived);
// sum of new interest payment + previous total interest payments, times 1e18
uint256 newTotalInterest = usdcToAtomic(
atomicToUSDC(_previousTotalInterestReceived).add(atomicToUSDC(interestPaymentAmount))
);
// interest payment passed the maxInterestDollarsEligible cap, should only partially be rewarded
if (newTotalInterest > maxInterestDollarsEligible) {
newTotalInterest = maxInterestDollarsEligible;
}
/*
equation:
(sqrtNewTotalInterest-sqrtOrigTotalInterest)
* totalRewardPercentOfTotalGFI
/ sqrtMaxInterestDollarsEligible
/ 100
* totalGFISupply
/ 10^18
example scenario:
- new payment = 5000*10^18
- original interest received = 0*10^18
- total reward percent = 3 * 10^18
- max interest dollars = 1 * 10^27 ($1 billion)
- totalGfiSupply = 100_000_000 * 10^18
example math:
(70710678118 - 0)
* 3000000000000000000
/ 31622776601683
/ 100
* 100000000000000000000000000
/ 10^18
= 6708203932437400000000 (6,708.2039 GFI)
*/
uint256 sqrtDiff = Babylonian.sqrt(newTotalInterest).sub(sqrtOrigTotalInterest);
uint256 sqrtMaxInterestDollarsEligible = Babylonian.sqrt(maxInterestDollarsEligible);
require(sqrtMaxInterestDollarsEligible > 0, "maxInterestDollarsEligible must not be zero");
uint256 newGrossRewards = sqrtDiff
.mul(totalRewardPercentOfTotalGFI)
.div(sqrtMaxInterestDollarsEligible)
.div(100)
.mul(totalGFISupply)
.div(mantissa());
// Extra safety check to make sure the logic is capped at a ceiling of potential rewards
// Calculating the gfi/$ for first dollar of interest to the protocol, and multiplying by new interest amount
uint256 absoluteMaxGfiCheckPerDollar = Babylonian
.sqrt((uint256)(1).mul(mantissa()))
.mul(totalRewardPercentOfTotalGFI)
.div(sqrtMaxInterestDollarsEligible)
.div(100)
.mul(totalGFISupply)
.div(mantissa());
require(
newGrossRewards < absoluteMaxGfiCheckPerDollar.mul(newTotalInterest),
"newGrossRewards cannot be greater then the max gfi per dollar"
);
return newGrossRewards;
}
function mantissa() internal pure returns (uint256) {
return uint256(10)**uint256(18);
}
function usdcMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(6);
}
function usdcToAtomic(uint256 amount) internal pure returns (uint256) {
return amount.mul(mantissa()).div(usdcMantissa());
}
function atomicToUSDC(uint256 amount) internal pure returns (uint256) {
return amount.div(mantissa().div(usdcMantissa()));
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(_msgSender(), address(config));
}
/* ======== MODIFIERS ======== */
modifier onlyPool() {
require(config.getPoolTokens().validPool(_msgSender()), "Invalid pool!");
_;
}
/* ======== EVENTS ======== */
event GoldfinchConfigUpdated(address indexed who, address configAddress);
event BackerRewardsClaimed(address indexed owner, uint256 indexed tokenId, uint256 amount);
event BackerRewardsSetTotalRewards(address indexed owner, uint256 totalRewards, uint256 totalRewardPercentOfTotalGFI);
event BackerRewardsSetTotalInterestReceived(address indexed owner, uint256 totalInterestReceived);
event BackerRewardsSetMaxInterestDollarsEligible(address indexed owner, uint256 maxInterestDollarsEligible);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../rewards/BackerRewards.sol";
contract TestBackerRewards is BackerRewards {
address payable public sender;
// solhint-disable-next-line modifiers/ensure-modifiers
function _setSender(address payable _sender) public {
sender = _sender;
}
function _msgSender() internal view override returns (address payable) {
if (sender != address(0)) {
return sender;
} else {
return super._msgSender();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "../../external/ERC721PresetMinterPauserAutoId.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/IFidu.sol";
import "../core/BaseUpgradeablePausable.sol";
import "../core/GoldfinchConfig.sol";
import "../core/ConfigHelper.sol";
import "../../library/SafeERC20Transfer.sol";
contract TransferRestrictedVault is
ERC721PresetMinterPauserAutoIdUpgradeSafe,
ReentrancyGuardUpgradeSafe,
SafeERC20Transfer
{
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
using SafeMath for uint256;
struct PoolTokenPosition {
uint256 tokenId;
uint256 lockedUntil;
}
struct FiduPosition {
uint256 amount;
uint256 lockedUntil;
}
// tokenId => poolTokenPosition
mapping(uint256 => PoolTokenPosition) public poolTokenPositions;
// tokenId => fiduPosition
mapping(uint256 => FiduPosition) public fiduPositions;
/*
We are using our own initializer function so that OZ doesn't automatically
set owner as msg.sender. Also, it lets us set our config contract
*/
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) external initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__Context_init_unchained();
__AccessControl_init_unchained();
__ReentrancyGuard_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained("Goldfinch V2 Accredited Investor Tokens", "GFI-V2-AI");
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
config = _config;
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
function depositJunior(ITranchedPool tranchedPool, uint256 amount) public nonReentrant {
require(config.getGo().go(msg.sender), "This address has not been go-listed");
safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount);
approveSpender(address(tranchedPool), amount);
uint256 poolTokenId = tranchedPool.deposit(uint256(ITranchedPool.Tranches.Junior), amount);
uint256 transferRestrictionPeriodInSeconds = SECONDS_PER_DAY.mul(config.getTransferRestrictionPeriodInDays());
_tokenIdTracker.increment();
uint256 tokenId = _tokenIdTracker.current();
poolTokenPositions[tokenId] = PoolTokenPosition({
tokenId: poolTokenId,
lockedUntil: block.timestamp.add(transferRestrictionPeriodInSeconds)
});
_mint(msg.sender, tokenId);
}
function depositJuniorWithPermit(
ITranchedPool tranchedPool,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s);
depositJunior(tranchedPool, amount);
}
function depositSenior(uint256 amount) public nonReentrant {
safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount);
ISeniorPool seniorPool = config.getSeniorPool();
approveSpender(address(seniorPool), amount);
uint256 depositShares = seniorPool.deposit(amount);
uint256 transferRestrictionPeriodInSeconds = SECONDS_PER_DAY.mul(config.getTransferRestrictionPeriodInDays());
_tokenIdTracker.increment();
uint256 tokenId = _tokenIdTracker.current();
fiduPositions[tokenId] = FiduPosition({
amount: depositShares,
lockedUntil: block.timestamp.add(transferRestrictionPeriodInSeconds)
});
_mint(msg.sender, tokenId);
}
function depositSeniorWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s);
depositSenior(amount);
}
function withdrawSenior(uint256 tokenId, uint256 usdcAmount) public nonReentrant onlyTokenOwner(tokenId) {
IFidu fidu = config.getFidu();
ISeniorPool seniorPool = config.getSeniorPool();
uint256 fiduBalanceBefore = fidu.balanceOf(address(this));
uint256 receivedAmount = seniorPool.withdraw(usdcAmount);
uint256 fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this)));
FiduPosition storage fiduPosition = fiduPositions[tokenId];
uint256 fiduPositionAmount = fiduPosition.amount;
require(fiduPositionAmount >= fiduUsed, "Not enough Fidu for withdrawal");
fiduPosition.amount = fiduPositionAmount.sub(fiduUsed);
safeERC20Transfer(config.getUSDC(), msg.sender, receivedAmount);
}
function withdrawSeniorInFidu(uint256 tokenId, uint256 shares) public nonReentrant onlyTokenOwner(tokenId) {
FiduPosition storage fiduPosition = fiduPositions[tokenId];
uint256 fiduPositionAmount = fiduPosition.amount;
require(fiduPositionAmount >= shares, "Not enough Fidu for withdrawal");
fiduPosition.amount = fiduPositionAmount.sub(shares);
uint256 usdcAmount = config.getSeniorPool().withdrawInFidu(shares);
safeERC20Transfer(config.getUSDC(), msg.sender, usdcAmount);
}
function withdrawJunior(uint256 tokenId, uint256 amount)
public
nonReentrant
onlyTokenOwner(tokenId)
returns (uint256 interestWithdrawn, uint256 principalWithdrawn)
{
PoolTokenPosition storage position = poolTokenPositions[tokenId];
require(position.lockedUntil > 0, "Position is empty");
IPoolTokens poolTokens = config.getPoolTokens();
uint256 poolTokenId = position.tokenId;
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(poolTokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
(interestWithdrawn, principalWithdrawn) = pool.withdraw(poolTokenId, amount);
uint256 totalWithdrawn = interestWithdrawn.add(principalWithdrawn);
safeERC20Transfer(config.getUSDC(), msg.sender, totalWithdrawn);
return (interestWithdrawn, principalWithdrawn);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId // solhint-disable-line no-unused-vars
) internal virtual override(ERC721PresetMinterPauserAutoIdUpgradeSafe) {
// AccreditedInvestor tokens can never be transferred. The underlying positions,
// however, can be transferred after the timelock expires.
require(from == address(0) || to == address(0), "TransferRestrictedVault tokens cannot be transferred");
}
/**
* @dev This method assumes that positions are mutually exclusive i.e. that the token
* represents a position in either PoolTokens or Fidu, but not both.
*/
function transferPosition(uint256 tokenId, address to) public nonReentrant {
require(ownerOf(tokenId) == msg.sender, "Cannot transfer position of token you don't own");
FiduPosition storage fiduPosition = fiduPositions[tokenId];
if (fiduPosition.lockedUntil > 0) {
require(
block.timestamp >= fiduPosition.lockedUntil,
"Underlying position cannot be transferred until lockedUntil"
);
transferFiduPosition(fiduPosition, to);
delete fiduPositions[tokenId];
}
PoolTokenPosition storage poolTokenPosition = poolTokenPositions[tokenId];
if (poolTokenPosition.lockedUntil > 0) {
require(
block.timestamp >= poolTokenPosition.lockedUntil,
"Underlying position cannot be transferred until lockedUntil"
);
transferPoolTokenPosition(poolTokenPosition, to);
delete poolTokenPositions[tokenId];
}
_burn(tokenId);
}
function transferPoolTokenPosition(PoolTokenPosition storage position, address to) internal {
IPoolTokens poolTokens = config.getPoolTokens();
poolTokens.safeTransferFrom(address(this), to, position.tokenId);
}
function transferFiduPosition(FiduPosition storage position, address to) internal {
IFidu fidu = config.getFidu();
safeERC20Transfer(fidu, to, position.amount);
}
function approveSpender(address spender, uint256 allowance) internal {
IERC20withDec usdc = config.getUSDC();
safeERC20Approve(usdc, spender, allowance);
}
modifier onlyTokenOwner(uint256 tokenId) {
require(ownerOf(tokenId) == msg.sender, "Only the token owner is allowed to call this function");
_;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
// contract IOneSplitConsts {
// // flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ...
// uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01;
// uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated
// uint256 internal constant FLAG_DISABLE_BANCOR = 0x04;
// uint256 internal constant FLAG_DISABLE_OASIS = 0x08;
// uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10;
// uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20;
// uint256 internal constant FLAG_DISABLE_CHAI = 0x40;
// uint256 internal constant FLAG_DISABLE_AAVE = 0x80;
// uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100;
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default
// uint256 internal constant FLAG_DISABLE_BDAI = 0x400;
// uint256 internal constant FLAG_DISABLE_IEARN = 0x800;
// uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000;
// uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000;
// uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000;
// uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000;
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default
// uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000;
// uint256 internal constant FLAG_DISABLE_WETH = 0x80000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
// uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH
// uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
// uint256 internal constant FLAG_DISABLE_IDLE = 0x800000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000;
// uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000;
// uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000;
// uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000;
// uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000;
// uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000;
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default
// uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000;
// uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000;
// uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000;
// uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000;
// uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000;
// uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000;
// uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000;
// uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000;
// uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000;
// uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000;
// uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000;
// uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000;
// uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default
// uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default
// uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000;
// uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000;
// uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000;
// uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000;
// uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000;
// uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_ALL = 0x8000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_ETH = 0x10000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_DAI = 0x20000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_USDC = 0x40000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_POOL_TOKEN = 0x80000000000000000;
// }
interface IOneSplit {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) external view returns (uint256 returnAmount, uint256[] memory distribution);
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
external
view
returns (
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) external payable returns (uint256 returnAmount);
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../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 {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
}
function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
import "../../Initializable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20PausableUpgradeSafe is Initializable, ERC20UpgradeSafe, PausableUpgradeSafe {
function __ERC20Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./ERC20.sol";
import "../../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 ERC20BurnableUpgradeSafe is Initializable, ContextUpgradeSafe, ERC20UpgradeSafe {
function __ERC20Burnable_init() internal initializer {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal initializer {
}
/**
* @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;
}
pragma solidity ^0.6.0;
import "../access/AccessControl.sol";
import "../GSN/Context.sol";
import "../token/ERC20/ERC20.sol";
import "../token/ERC20/ERC20Burnable.sol";
import "../token/ERC20/ERC20Pausable.sol";
import "../Initializable.sol";
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to aother accounts
*/
contract ERC20PresetMinterPauserUpgradeSafe is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, ERC20BurnableUpgradeSafe, ERC20PausableUpgradeSafe {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
function initialize(string memory name, string memory symbol) public {
__ERC20PresetMinterPauser_init(name, symbol);
}
function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
__ERC20PresetMinterPauser_init_unchained(name, symbol);
}
function __ERC20PresetMinterPauser_init_unchained(string memory name, string memory symbol) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20UpgradeSafe, ERC20PausableUpgradeSafe) {
super._beforeTokenTransfer(from, to, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/presets/ERC20PresetMinterPauser.sol";
import "./ConfigHelper.sol";
/**
* @title Fidu
* @notice Fidu (symbol: FIDU) is Goldfinch's liquidity token, representing shares
* in the Pool. When you deposit, we mint a corresponding amount of Fidu, and when you withdraw, we
* burn Fidu. The share price of the Pool implicitly represents the "exchange rate" between Fidu
* and USDC (or whatever currencies the Pool may allow withdraws in during the future)
* @author Goldfinch
*/
contract Fidu is ERC20PresetMinterPauserUpgradeSafe {
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
// $1 threshold to handle potential rounding errors, from differing decimals on Fidu and USDC;
uint256 public constant ASSET_LIABILITY_MATCH_THRESHOLD = 1e6;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
event GoldfinchConfigUpdated(address indexed who, address configAddress);
/*
We are using our own initializer function so we can set the owner by passing it in.
I would override the regular "initializer" function, but I can't because it's not marked
as "virtual" in the parent contract
*/
// solhint-disable-next-line func-name-mixedcase
function __initialize__(
address owner,
string calldata name,
string calldata symbol,
GoldfinchConfig _config
) external initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
config = _config;
_setupRole(MINTER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(MINTER_ROLE, OWNER_ROLE);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintTo(address to, uint256 amount) public {
require(canMint(amount), "Cannot mint: it would create an asset/liability mismatch");
// This super call restricts to only the minter in its implementation, so we don't need to do it here.
super.mint(to, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have the MINTER_ROLE
*/
function burnFrom(address from, uint256 amount) public override {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: Must have minter role to burn");
require(canBurn(amount), "Cannot burn: it would create an asset/liability mismatch");
_burn(from, amount);
}
// Internal functions
// canMint assumes that the USDC that backs the new shares has already been sent to the Pool
function canMint(uint256 newAmount) internal view returns (bool) {
ISeniorPool seniorPool = config.getSeniorPool();
uint256 liabilities = totalSupply().add(newAmount).mul(seniorPool.sharePrice()).div(fiduMantissa());
uint256 liabilitiesInDollars = fiduToUSDC(liabilities);
uint256 _assets = seniorPool.assets();
if (_assets >= liabilitiesInDollars) {
return true;
} else {
return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD;
}
}
// canBurn assumes that the USDC that backed these shares has already been moved out the Pool
function canBurn(uint256 amountToBurn) internal view returns (bool) {
ISeniorPool seniorPool = config.getSeniorPool();
uint256 liabilities = totalSupply().sub(amountToBurn).mul(seniorPool.sharePrice()).div(fiduMantissa());
uint256 liabilitiesInDollars = fiduToUSDC(liabilities);
uint256 _assets = seniorPool.assets();
if (_assets >= liabilitiesInDollars) {
return true;
} else {
return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD;
}
}
function fiduToUSDC(uint256 amount) internal pure returns (uint256) {
return amount.div(fiduMantissa().div(usdcMantissa()));
}
function fiduMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(18);
}
function usdcMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(6);
}
function updateGoldfinchConfig() external {
require(hasRole(OWNER_ROLE, _msgSender()), "ERC20PresetMinterPauser: Must have minter role to change config");
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "./LeverageRatioStrategy.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ITranchedPool.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
contract FixedLeverageRatioStrategy is LeverageRatioStrategy {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
event GoldfinchConfigUpdated(address indexed who, address configAddress);
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
function getLeverageRatio(ITranchedPool pool) public view override returns (uint256) {
return config.getLeverageRatio();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ITranchedPool.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
abstract contract LeverageRatioStrategy is BaseUpgradeablePausable, ISeniorPoolStrategy {
using SafeMath for uint256;
uint256 internal constant LEVERAGE_RATIO_DECIMALS = 1e18;
/**
* @notice Determines how much money to invest in the senior tranche based on what is committed to the junior
* tranche, what is committed to the senior tranche, and a leverage ratio to the junior tranche. Because
* it takes into account what is already committed to the senior tranche, the value returned by this
* function can be used "idempotently" to achieve the investment target amount without exceeding that target.
* @param seniorPool The senior pool to invest from
* @param pool The tranched pool to invest into (as the senior)
* @return The amount of money to invest into the tranched pool's senior tranche, from the senior pool
*/
function invest(ISeniorPool seniorPool, ITranchedPool pool) public view override returns (uint256) {
ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior));
ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));
// If junior capital is not yet invested, or pool already locked, then don't invest anything.
if (juniorTranche.lockedUntil == 0 || seniorTranche.lockedUntil > 0) {
return 0;
}
return _invest(pool, juniorTranche, seniorTranche);
}
/**
* @notice A companion of `invest()`: determines how much would be returned by `invest()`, as the
* value to invest into the senior tranche, if the junior tranche were locked and the senior tranche
* were not locked.
* @param seniorPool The senior pool to invest from
* @param pool The tranched pool to invest into (as the senior)
* @return The amount of money to invest into the tranched pool's senior tranche, from the senior pool
*/
function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view override returns (uint256) {
ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior));
ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));
return _invest(pool, juniorTranche, seniorTranche);
}
function _invest(
ITranchedPool pool,
ITranchedPool.TrancheInfo memory juniorTranche,
ITranchedPool.TrancheInfo memory seniorTranche
) internal view returns (uint256) {
uint256 juniorCapital = juniorTranche.principalDeposited;
uint256 existingSeniorCapital = seniorTranche.principalDeposited;
uint256 seniorTarget = juniorCapital.mul(getLeverageRatio(pool)).div(LEVERAGE_RATIO_DECIMALS);
if (existingSeniorCapital >= seniorTarget) {
return 0;
}
return seniorTarget.sub(existingSeniorCapital);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "./LeverageRatioStrategy.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ITranchedPool.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
contract DynamicLeverageRatioStrategy is LeverageRatioStrategy {
bytes32 public constant LEVERAGE_RATIO_SETTER_ROLE = keccak256("LEVERAGE_RATIO_SETTER_ROLE");
struct LeverageRatioInfo {
uint256 leverageRatio;
uint256 juniorTrancheLockedUntil;
}
// tranchedPoolAddress => leverageRatioInfo
mapping(address => LeverageRatioInfo) public ratios;
event LeverageRatioUpdated(
address indexed pool,
uint256 leverageRatio,
uint256 juniorTrancheLockedUntil,
bytes32 version
);
function initialize(address owner) public initializer {
require(owner != address(0), "Owner address cannot be empty");
__BaseUpgradeablePausable__init(owner);
_setupRole(LEVERAGE_RATIO_SETTER_ROLE, owner);
_setRoleAdmin(LEVERAGE_RATIO_SETTER_ROLE, OWNER_ROLE);
}
function getLeverageRatio(ITranchedPool pool) public view override returns (uint256) {
LeverageRatioInfo memory ratioInfo = ratios[address(pool)];
ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior));
ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));
require(ratioInfo.juniorTrancheLockedUntil > 0, "Leverage ratio has not been set yet.");
if (seniorTranche.lockedUntil > 0) {
// The senior tranche is locked. Coherence check: we expect locking the senior tranche to have
// updated `juniorTranche.lockedUntil` (compared to its value when `setLeverageRatio()` was last
// called successfully).
require(
ratioInfo.juniorTrancheLockedUntil < juniorTranche.lockedUntil,
"Expected junior tranche `lockedUntil` to have been updated."
);
} else {
require(
ratioInfo.juniorTrancheLockedUntil == juniorTranche.lockedUntil,
"Leverage ratio is obsolete. Wait for its recalculation."
);
}
return ratioInfo.leverageRatio;
}
/**
* @notice Updates the leverage ratio for the specified tranched pool. The combination of the
* `juniorTranchedLockedUntil` param and the `version` param in the event emitted by this
* function are intended to enable an outside observer to verify the computation of the leverage
* ratio set by calls of this function.
* @param pool The tranched pool whose leverage ratio to update.
* @param leverageRatio The leverage ratio value to set for the tranched pool.
* @param juniorTrancheLockedUntil The `lockedUntil` timestamp, of the tranched pool's
* junior tranche, to which this calculation of `leverageRatio` corresponds, i.e. the
* value of the `lockedUntil` timestamp of the JuniorCapitalLocked event which the caller
* is calling this function in response to having observed. By providing this timestamp
* (plus an assumption that we can trust the caller to report this value accurately),
* the caller enables this function to enforce that a leverage ratio that is obsolete in
* the sense of having been calculated for an obsolete `lockedUntil` timestamp cannot be set.
* @param version An arbitrary identifier included in the LeverageRatioUpdated event emitted
* by this function, enabling the caller to describe how it calculated `leverageRatio`. Using
* the bytes32 type accommodates using git commit hashes (both the current SHA1 hashes, which
* require 20 bytes; and the future SHA256 hashes, which require 32 bytes) for this value.
*/
function setLeverageRatio(
ITranchedPool pool,
uint256 leverageRatio,
uint256 juniorTrancheLockedUntil,
bytes32 version
) public onlySetterRole {
ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior));
ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));
// NOTE: We allow a `leverageRatio` of 0.
require(
leverageRatio <= 10 * LEVERAGE_RATIO_DECIMALS,
"Leverage ratio must not exceed 10 (adjusted for decimals)."
);
require(juniorTranche.lockedUntil > 0, "Cannot set leverage ratio if junior tranche is not locked.");
require(seniorTranche.lockedUntil == 0, "Cannot set leverage ratio if senior tranche is locked.");
require(juniorTrancheLockedUntil == juniorTranche.lockedUntil, "Invalid `juniorTrancheLockedUntil` timestamp.");
ratios[address(pool)] = LeverageRatioInfo({
leverageRatio: leverageRatio,
juniorTrancheLockedUntil: juniorTrancheLockedUntil
});
emit LeverageRatioUpdated(address(pool), leverageRatio, juniorTrancheLockedUntil, version);
}
modifier onlySetterRole() {
require(
hasRole(LEVERAGE_RATIO_SETTER_ROLE, _msgSender()),
"Must have leverage-ratio setter role to perform this action"
);
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.5 <0.8.0;
import "../token/ERC20/ERC20.sol";
import "./IERC20Permit.sol";
import "../cryptography/ECDSA.sol";
import "../utils/Counters.sol";
import "./EIP712.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping (address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) internal EIP712(name, "1") {
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_nonces[owner].current(),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_nonces[owner].increment();
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
}
// 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 Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) internal {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = _getChainId();
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
if (_getChainId() == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
_getChainId(),
address(this)
)
);
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath 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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol";
/**
* @title GFI
* @notice GFI is Goldfinch's governance token.
* @author Goldfinch
*/
contract GFI is Context, AccessControl, ERC20Burnable, ERC20Pausable {
using SafeMath for uint256;
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/// The maximum number of tokens that can be minted
uint256 public cap;
event CapUpdated(address indexed who, uint256 cap);
constructor(
address owner,
string memory name,
string memory symbol,
uint256 initialCap
) public ERC20(name, symbol) {
cap = initialCap;
_setupRole(MINTER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(MINTER_ROLE, OWNER_ROLE);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
/**
* @notice create and send tokens to a specified address
* @dev this function will fail if the caller attempts to mint over the current cap
*/
function mint(address account, uint256 amount) public onlyMinter whenNotPaused {
require(mintingAmountIsWithinCap(amount), "Cannot mint more than cap");
_mint(account, amount);
}
/**
* @notice sets the maximum number of tokens that can be minted
* @dev the cap must be greater than the current total supply
*/
function setCap(uint256 _cap) external onlyOwner {
require(_cap >= totalSupply(), "Cannot decrease the cap below existing supply");
cap = _cap;
emit CapUpdated(_msgSender(), cap);
}
function mintingAmountIsWithinCap(uint256 amount) internal returns (bool) {
return totalSupply().add(amount) <= cap;
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() external onlyPauser {
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() external onlyPauser {
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
modifier onlyOwner() {
require(hasRole(OWNER_ROLE, _msgSender()), "Must be owner");
_;
}
modifier onlyMinter() {
require(hasRole(MINTER_ROLE, _msgSender()), "Must be minter");
_;
}
modifier onlyPauser() {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must be pauser");
_;
}
}
// 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;
/**
* @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.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
// Taken from https://github.com/opengsn/forwarder/blob/master/contracts/Forwarder.sol and adapted to work locally
// Main change is removing interface inheritance and adding a some debugging niceities
contract TestForwarder {
using ECDSA for bytes32;
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
}
string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data";
string public constant EIP712_DOMAIN_TYPE =
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"; // solhint-disable-line max-line-length
mapping(bytes32 => bool) public typeHashes;
mapping(bytes32 => bool) public domains;
// Nonces of senders, used to prevent replay attacks
mapping(address => uint256) private nonces;
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
function getNonce(address from) public view returns (uint256) {
return nonces[from];
}
constructor() public {
string memory requestType = string(abi.encodePacked("ForwardRequest(", GENERIC_PARAMS, ")"));
registerRequestTypeInternal(requestType);
}
function verify(
ForwardRequest memory req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig
) external view {
_verifyNonce(req);
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
}
function execute(
ForwardRequest memory req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig
) external payable returns (bool success, bytes memory ret) {
_verifyNonce(req);
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
_updateNonce(req);
// solhint-disable-next-line avoid-low-level-calls
(success, ret) = req.to.call{gas: req.gas, value: req.value}(abi.encodePacked(req.data, req.from));
// Added by Goldfinch for debugging
if (!success) {
require(success, string(ret));
}
if (address(this).balance > 0) {
//can't fail: req.from signed (off-chain) the request, so it must be an EOA...
payable(req.from).transfer(address(this).balance);
}
return (success, ret);
}
function _verifyNonce(ForwardRequest memory req) internal view {
require(nonces[req.from] == req.nonce, "nonce mismatch");
}
function _updateNonce(ForwardRequest memory req) internal {
nonces[req.from]++;
}
function registerRequestType(string calldata typeName, string calldata typeSuffix) external {
for (uint256 i = 0; i < bytes(typeName).length; i++) {
bytes1 c = bytes(typeName)[i];
require(c != "(" && c != ")", "invalid typename");
}
string memory requestType = string(abi.encodePacked(typeName, "(", GENERIC_PARAMS, ",", typeSuffix));
registerRequestTypeInternal(requestType);
}
function registerDomainSeparator(string calldata name, string calldata version) external {
uint256 chainId;
/* solhint-disable-next-line no-inline-assembly */
assembly {
chainId := chainid()
}
bytes memory domainValue = abi.encode(
keccak256(bytes(EIP712_DOMAIN_TYPE)),
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
address(this)
);
bytes32 domainHash = keccak256(domainValue);
domains[domainHash] = true;
emit DomainRegistered(domainHash, domainValue);
}
function registerRequestTypeInternal(string memory requestType) internal {
bytes32 requestTypehash = keccak256(bytes(requestType));
typeHashes[requestTypehash] = true;
emit RequestTypeRegistered(requestTypehash, requestType);
}
event DomainRegistered(bytes32 indexed domainSeparator, bytes domainValue);
event RequestTypeRegistered(bytes32 indexed typeHash, string typeStr);
function _verifySig(
ForwardRequest memory req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes memory suffixData,
bytes memory sig
) internal view {
require(domains[domainSeparator], "unregistered domain separator");
require(typeHashes[requestTypeHash], "unregistered request typehash");
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, keccak256(_getEncoded(req, requestTypeHash, suffixData)))
);
require(digest.recover(sig) == req.from, "signature mismatch");
}
function _getEncoded(
ForwardRequest memory req,
bytes32 requestTypeHash,
bytes memory suffixData
) public pure returns (bytes memory) {
return
abi.encodePacked(
requestTypeHash,
abi.encode(req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)),
suffixData
);
}
}
// contracts/GLDToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/drafts/ERC20Permit.sol";
contract TestERC20 is ERC20("USD Coin", "USDC"), ERC20Permit("USD Coin") {
constructor(uint256 initialSupply, uint8 decimals) public {
_setupDecimals(decimals);
_mint(msg.sender, initialSupply);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../external/ERC721PresetMinterPauserAutoId.sol";
import "./GoldfinchConfig.sol";
import "./ConfigHelper.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IPoolTokens.sol";
/**
* @title PoolTokens
* @notice PoolTokens is an ERC721 compliant contract, which can represent
* junior tranche or senior tranche shares of any of the borrower pools.
* @author Goldfinch
*/
contract PoolTokens is IPoolTokens, ERC721PresetMinterPauserAutoIdUpgradeSafe {
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
struct PoolInfo {
uint256 totalMinted;
uint256 totalPrincipalRedeemed;
bool created;
}
// tokenId => tokenInfo
mapping(uint256 => TokenInfo) public tokens;
// poolAddress => poolInfo
mapping(address => PoolInfo) public pools;
event TokenMinted(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 amount,
uint256 tranche
);
event TokenRedeemed(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed,
uint256 tranche
);
event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
/*
We are using our own initializer function so that OZ doesn't automatically
set owner as msg.sender. Also, it lets us set our config contract
*/
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) external initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC165_init_unchained();
// This is setting name and symbol of the NFT's
__ERC721_init_unchained("Goldfinch V2 Pool Tokens", "GFI-V2-PT");
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
config = _config;
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
/**
* @notice Called by pool to create a debt position in a particular tranche and amount
* @param params Struct containing the tranche and the amount
* @param to The address that should own the position
* @return tokenId The token ID (auto-incrementing integer across all pools)
*/
function mint(MintParams calldata params, address to)
external
virtual
override
onlyPool
whenNotPaused
returns (uint256 tokenId)
{
address poolAddress = _msgSender();
tokenId = createToken(params, poolAddress);
_mint(to, tokenId);
config.getBackerRewards().setPoolTokenAccRewardsPerPrincipalDollarAtMint(_msgSender(), tokenId);
emit TokenMinted(to, poolAddress, tokenId, params.principalAmount, params.tranche);
return tokenId;
}
/**
* @notice Updates a token to reflect the principal and interest amounts that have been redeemed.
* @param tokenId The token id to update (must be owned by the pool calling this function)
* @param principalRedeemed The incremental amount of principal redeemed (cannot be more than principal deposited)
* @param interestRedeemed The incremental amount of interest redeemed
*/
function redeem(
uint256 tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed
) external virtual override onlyPool whenNotPaused {
TokenInfo storage token = tokens[tokenId];
address poolAddr = token.pool;
require(token.pool != address(0), "Invalid tokenId");
require(_msgSender() == poolAddr, "Only the token's pool can redeem");
PoolInfo storage pool = pools[poolAddr];
pool.totalPrincipalRedeemed = pool.totalPrincipalRedeemed.add(principalRedeemed);
require(pool.totalPrincipalRedeemed <= pool.totalMinted, "Cannot redeem more than we minted");
token.principalRedeemed = token.principalRedeemed.add(principalRedeemed);
require(
token.principalRedeemed <= token.principalAmount,
"Cannot redeem more than principal-deposited amount for token"
);
token.interestRedeemed = token.interestRedeemed.add(interestRedeemed);
emit TokenRedeemed(ownerOf(tokenId), poolAddr, tokenId, principalRedeemed, interestRedeemed, token.tranche);
}
/**
* @dev Burns a specific ERC721 token, and removes the data from our mappings
* @param tokenId uint256 id of the ERC721 token to be burned.
*/
function burn(uint256 tokenId) external virtual override whenNotPaused {
TokenInfo memory token = _getTokenInfo(tokenId);
bool canBurn = _isApprovedOrOwner(_msgSender(), tokenId);
bool fromTokenPool = _validPool(_msgSender()) && token.pool == _msgSender();
address owner = ownerOf(tokenId);
require(canBurn || fromTokenPool, "ERC721Burnable: caller cannot burn this token");
require(token.principalRedeemed == token.principalAmount, "Can only burn fully redeemed tokens");
destroyAndBurn(tokenId);
emit TokenBurned(owner, token.pool, tokenId);
}
function getTokenInfo(uint256 tokenId) external view virtual override returns (TokenInfo memory) {
return _getTokenInfo(tokenId);
}
/**
* @notice Called by the GoldfinchFactory to register the pool as a valid pool. Only valid pools can mint/redeem
* tokens
* @param newPool The address of the newly created pool
*/
function onPoolCreated(address newPool) external override onlyGoldfinchFactory {
pools[newPool].created = true;
}
/**
* @notice Returns a boolean representing whether the spender is the owner or the approved spender of the token
* @param spender The address to check
* @param tokenId The token id to check for
* @return True if approved to redeem/transfer/burn the token, false if not
*/
function isApprovedOrOwner(address spender, uint256 tokenId) external view override returns (bool) {
return _isApprovedOrOwner(spender, tokenId);
}
function validPool(address sender) public view virtual override returns (bool) {
return _validPool(sender);
}
function createToken(MintParams calldata params, address poolAddress) internal returns (uint256 tokenId) {
PoolInfo storage pool = pools[poolAddress];
_tokenIdTracker.increment();
tokenId = _tokenIdTracker.current();
tokens[tokenId] = TokenInfo({
pool: poolAddress,
tranche: params.tranche,
principalAmount: params.principalAmount,
principalRedeemed: 0,
interestRedeemed: 0
});
pool.totalMinted = pool.totalMinted.add(params.principalAmount);
return tokenId;
}
function destroyAndBurn(uint256 tokenId) internal {
delete tokens[tokenId];
_burn(tokenId);
}
function _validPool(address poolAddress) internal view virtual returns (bool) {
return pools[poolAddress].created;
}
function _getTokenInfo(uint256 tokenId) internal view returns (TokenInfo memory) {
return tokens[tokenId];
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyGoldfinchFactory() {
require(_msgSender() == config.goldfinchFactoryAddress(), "Only Goldfinch factory is allowed");
_;
}
modifier onlyPool() {
require(_validPool(_msgSender()), "Invalid pool!");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/PoolTokens.sol";
contract TestPoolTokens is PoolTokens {
bool public disablePoolValidation;
address payable public sender;
// solhint-disable-next-line modifiers/ensure-modifiers
function _disablePoolValidation(bool shouldDisable) public {
disablePoolValidation = shouldDisable;
}
// solhint-disable-next-line modifiers/ensure-modifiers
function _setSender(address payable _sender) public {
sender = _sender;
}
function _validPool(address _sender) internal view override returns (bool) {
if (disablePoolValidation) {
return true;
} else {
return super._validPool(_sender);
}
}
function _msgSender() internal view override returns (address payable) {
if (sender != address(0)) {
return sender;
} else {
return super._msgSender();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IV2CreditLine.sol";
import "./IV1CreditLine.sol";
import "./ITranchedPool.sol";
abstract contract IMigratedTranchedPool is ITranchedPool {
function migrateCreditLineToV2(
IV1CreditLine clToMigrate,
uint256 termEndTime,
uint256 nextDueTime,
uint256 interestAccruedAsOf,
uint256 lastFullPaymentTime,
uint256 totalInterestPaid
) external virtual returns (IV2CreditLine);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IV1CreditLine {
address public borrower;
address public underwriter;
uint256 public limit;
uint256 public interestApr;
uint256 public paymentPeriodInDays;
uint256 public termInDays;
uint256 public lateFeeApr;
uint256 public balance;
uint256 public interestOwed;
uint256 public principalOwed;
uint256 public termEndBlock;
uint256 public nextDueBlock;
uint256 public interestAccruedAsOfBlock;
uint256 public writedownAmount;
uint256 public lastFullPaymentBlock;
function setLimit(uint256 newAmount) external virtual;
function setBalance(uint256 newBalance) external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./TranchedPool.sol";
import "../../interfaces/IV1CreditLine.sol";
import "../../interfaces/IMigratedTranchedPool.sol";
contract MigratedTranchedPool is TranchedPool, IMigratedTranchedPool {
bool public migrated;
function migrateCreditLineToV2(
IV1CreditLine clToMigrate,
uint256 termEndTime,
uint256 nextDueTime,
uint256 interestAccruedAsOf,
uint256 lastFullPaymentTime,
uint256 totalInterestPaid
) external override returns (IV2CreditLine) {
require(msg.sender == config.creditDeskAddress(), "Only credit desk can call this");
require(!migrated, "Already migrated");
// Set accounting state vars.
IV2CreditLine newCl = creditLine;
newCl.setBalance(clToMigrate.balance());
newCl.setInterestOwed(clToMigrate.interestOwed());
newCl.setPrincipalOwed(clToMigrate.principalOwed());
newCl.setTermEndTime(termEndTime);
newCl.setNextDueTime(nextDueTime);
newCl.setInterestAccruedAsOf(interestAccruedAsOf);
newCl.setLastFullPaymentTime(lastFullPaymentTime);
newCl.setTotalInterestAccrued(totalInterestPaid.add(clToMigrate.interestOwed()));
migrateDeposits(clToMigrate, totalInterestPaid);
migrated = true;
return newCl;
}
function migrateDeposits(IV1CreditLine clToMigrate, uint256 totalInterestPaid) internal {
// Mint junior tokens to the SeniorPool, equal to current cl balance;
require(!locked(), "Pool has been locked");
// Hardcode to always get the JuniorTranche, since the migration case is when
// the senior pool took the entire investment. Which we're expressing as the junior tranche
uint256 tranche = uint256(ITranchedPool.Tranches.Junior);
TrancheInfo storage trancheInfo = getTrancheInfo(tranche);
require(trancheInfo.lockedUntil == 0, "Tranche has been locked");
trancheInfo.principalDeposited = clToMigrate.limit();
IPoolTokens.MintParams memory params = IPoolTokens.MintParams({
tranche: tranche,
principalAmount: trancheInfo.principalDeposited
});
IPoolTokens poolTokens = config.getPoolTokens();
uint256 tokenId = poolTokens.mint(params, config.seniorPoolAddress());
uint256 balancePaid = creditLine.limit().sub(creditLine.balance());
// Account for the implicit redemptions already made by the Legacy Pool
_lockJuniorCapital(poolSlices.length - 1);
_lockPool();
PoolSlice storage currentSlice = poolSlices[poolSlices.length - 1];
currentSlice.juniorTranche.lockedUntil = block.timestamp - 1;
poolTokens.redeem(tokenId, balancePaid, totalInterestPaid);
// Simulate the drawdown
currentSlice.juniorTranche.principalSharePrice = 0;
currentSlice.seniorTranche.principalSharePrice = 0;
// Set junior's sharePrice correctly
currentSlice.juniorTranche.applyByAmount(totalInterestPaid, balancePaid, totalInterestPaid, balancePaid);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "./Accountant.sol";
import "./CreditLine.sol";
import "./GoldfinchFactory.sol";
import "../../interfaces/IV1CreditLine.sol";
import "../../interfaces/IMigratedTranchedPool.sol";
/**
* @title Goldfinch's CreditDesk contract
* @notice Main entry point for borrowers and underwriters.
* Handles key logic for creating CreditLine's, borrowing money, repayment, etc.
* @author Goldfinch
*/
contract CreditDesk is BaseUpgradeablePausable, ICreditDesk {
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
struct Underwriter {
uint256 governanceLimit;
address[] creditLines;
}
struct Borrower {
address[] creditLines;
}
event PaymentApplied(
address indexed payer,
address indexed creditLine,
uint256 interestAmount,
uint256 principalAmount,
uint256 remainingAmount
);
event PaymentCollected(address indexed payer, address indexed creditLine, uint256 paymentAmount);
event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount);
event CreditLineCreated(address indexed borrower, address indexed creditLine);
event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit);
mapping(address => Underwriter) public underwriters;
mapping(address => Borrower) private borrowers;
mapping(address => address) private creditLines;
/**
* @notice Run only once, on initialization
* @param owner The address of who should have the "OWNER_ROLE" of this contract
* @param _config The address of the GoldfinchConfig contract
*/
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
}
/**
* @notice Sets a particular underwriter's limit of how much credit the DAO will allow them to "create"
* @param underwriterAddress The address of the underwriter for whom the limit shall change
* @param limit What the new limit will be set to
* Requirements:
*
* - the caller must have the `OWNER_ROLE`.
*/
function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit)
external
override
onlyAdmin
whenNotPaused
{
require(withinMaxUnderwriterLimit(limit), "This limit is greater than the max allowed by the protocol");
underwriters[underwriterAddress].governanceLimit = limit;
emit GovernanceUpdatedUnderwriterLimit(underwriterAddress, limit);
}
/**
* @notice Allows a borrower to drawdown on their creditline.
* `amount` USDC is sent to the borrower, and the credit line accounting is updated.
* @param creditLineAddress The creditline from which they would like to drawdown
* @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown
*
* Requirements:
*
* - the caller must be the borrower on the creditLine
*/
function drawdown(address creditLineAddress, uint256 amount)
external
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
CreditLine cl = CreditLine(creditLineAddress);
Borrower storage borrower = borrowers[msg.sender];
require(borrower.creditLines.length > 0, "No credit lines exist for this borrower");
require(amount > 0, "Must drawdown more than zero");
require(cl.borrower() == msg.sender, "You are not the borrower of this credit line");
require(withinTransactionLimit(amount), "Amount is over the per-transaction limit");
uint256 unappliedBalance = getUSDCBalance(creditLineAddress);
require(
withinCreditLimit(amount, unappliedBalance, cl),
"The borrower does not have enough credit limit for this drawdown"
);
uint256 balance = cl.balance();
if (balance == 0) {
cl.setInterestAccruedAsOf(currentTime());
cl.setLastFullPaymentTime(currentTime());
}
IPool pool = config.getPool();
// If there is any balance on the creditline that has not been applied yet, then use that first before
// drawing down from the pool. This is to support cases where the borrower partially pays back the
// principal before the due date, but then decides to drawdown again
uint256 amountToTransferFromCL;
if (unappliedBalance > 0) {
if (amount > unappliedBalance) {
amountToTransferFromCL = unappliedBalance;
amount = amount.sub(unappliedBalance);
} else {
amountToTransferFromCL = amount;
amount = 0;
}
bool success = pool.transferFrom(creditLineAddress, msg.sender, amountToTransferFromCL);
require(success, "Failed to drawdown");
}
(uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, currentTime());
balance = balance.add(amount);
updateCreditLineAccounting(cl, balance, interestOwed, principalOwed);
// Must put this after we update the credit line accounting, so we're using the latest
// interestOwed
require(!isLate(cl, currentTime()), "Cannot drawdown when payments are past due");
emit DrawdownMade(msg.sender, address(cl), amount.add(amountToTransferFromCL));
if (amount > 0) {
bool success = pool.drawdown(msg.sender, amount);
require(success, "Failed to drawdown");
}
}
/**
* @notice Allows a borrower to repay their loan. Payment is *collected* immediately (by sending it to
* the individual CreditLine), but it is not *applied* unless it is after the nextDueTime, or until we assess
* the credit line (ie. payment period end).
* Any amounts over the minimum payment will be applied to outstanding principal (reducing the effective
* interest rate). If there is still any left over, it will remain in the USDC Balance
* of the CreditLine, which is held distinct from the Pool amounts, and can not be withdrawn by LP's.
* @param creditLineAddress The credit line to be paid back
* @param amount The amount, in USDC atomic units, that a borrower wishes to pay
*/
function pay(address creditLineAddress, uint256 amount)
external
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
require(amount > 0, "Must pay more than zero");
CreditLine cl = CreditLine(creditLineAddress);
collectPayment(cl, amount);
assessCreditLine(creditLineAddress);
}
/**
* @notice Assesses a particular creditLine. This will apply payments, which will update accounting and
* distribute gains or losses back to the pool accordingly. This function is idempotent, and anyone
* is allowed to call it.
* @param creditLineAddress The creditline that should be assessed.
*/
function assessCreditLine(address creditLineAddress)
public
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
CreditLine cl = CreditLine(creditLineAddress);
// Do not assess until a full period has elapsed or past due
require(cl.balance() > 0, "Must have balance to assess credit line");
// Don't assess credit lines early!
if (currentTime() < cl.nextDueTime() && !isLate(cl, currentTime())) {
return;
}
uint256 timeToAssess = calculateNextDueTime(cl);
cl.setNextDueTime(timeToAssess);
// We always want to assess for the most recently *past* nextDueTime.
// So if the recalculation above sets the nextDueTime into the future,
// then ensure we pass in the one just before this.
if (timeToAssess > currentTime()) {
uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY);
timeToAssess = timeToAssess.sub(secondsPerPeriod);
}
_applyPayment(cl, getUSDCBalance(address(cl)), timeToAssess);
}
function applyPayment(address creditLineAddress, uint256 amount)
external
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
CreditLine cl = CreditLine(creditLineAddress);
require(cl.borrower() == msg.sender, "You do not belong to this credit line");
_applyPayment(cl, amount, currentTime());
}
function migrateV1CreditLine(
address _clToMigrate,
address borrower,
uint256 termEndTime,
uint256 nextDueTime,
uint256 interestAccruedAsOf,
uint256 lastFullPaymentTime,
uint256 totalInterestPaid
) public onlyAdmin returns (address, address) {
IV1CreditLine clToMigrate = IV1CreditLine(_clToMigrate);
uint256 originalBalance = clToMigrate.balance();
require(clToMigrate.limit() > 0, "Can't migrate empty credit line");
require(originalBalance > 0, "Can't migrate credit line that's currently paid off");
// Ensure it is a v1 creditline by calling a function that only exists on v1
require(clToMigrate.nextDueBlock() > 0, "Invalid creditline");
if (borrower == address(0)) {
borrower = clToMigrate.borrower();
}
// We're migrating from 1e8 decimal precision of interest rates to 1e18
// So multiply the legacy rates by 1e10 to normalize them.
uint256 interestMigrationFactor = 1e10;
uint256[] memory allowedUIDTypes;
address pool = getGoldfinchFactory().createMigratedPool(
borrower,
20, // junior fee percent
clToMigrate.limit(),
clToMigrate.interestApr().mul(interestMigrationFactor),
clToMigrate.paymentPeriodInDays(),
clToMigrate.termInDays(),
clToMigrate.lateFeeApr(),
0,
0,
allowedUIDTypes
);
IV2CreditLine newCl = IMigratedTranchedPool(pool).migrateCreditLineToV2(
clToMigrate,
termEndTime,
nextDueTime,
interestAccruedAsOf,
lastFullPaymentTime,
totalInterestPaid
);
// Close out the original credit line
clToMigrate.setLimit(0);
clToMigrate.setBalance(0);
// Some sanity checks on the migration
require(newCl.balance() == originalBalance, "Balance did not migrate properly");
require(newCl.interestAccruedAsOf() == interestAccruedAsOf, "Interest accrued as of did not migrate properly");
return (address(newCl), pool);
}
/**
* @notice Simple getter for the creditlines of a given underwriter
* @param underwriterAddress The underwriter address you would like to see the credit lines of.
*/
function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) {
return underwriters[underwriterAddress].creditLines;
}
/**
* @notice Simple getter for the creditlines of a given borrower
* @param borrowerAddress The borrower address you would like to see the credit lines of.
*/
function getBorrowerCreditLines(address borrowerAddress) public view returns (address[] memory) {
return borrowers[borrowerAddress].creditLines;
}
/**
* @notice This function is only meant to be used by frontends. It returns the total
* payment due for a given creditLine as of the provided timestamp. Returns 0 if no
* payment is due (e.g. asOf is before the nextDueTime)
* @param creditLineAddress The creditLine to calculate the payment for
* @param asOf The timestamp to use for the payment calculation, if it is set to 0, uses the current time
*/
function getNextPaymentAmount(address creditLineAddress, uint256 asOf)
external
view
override
onlyValidCreditLine(creditLineAddress)
returns (uint256)
{
if (asOf == 0) {
asOf = currentTime();
}
CreditLine cl = CreditLine(creditLineAddress);
if (asOf < cl.nextDueTime() && !isLate(cl, currentTime())) {
return 0;
}
(uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(
cl,
asOf,
config.getLatenessGracePeriodInDays()
);
return cl.interestOwed().add(interestAccrued).add(cl.principalOwed().add(principalAccrued));
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
}
/*
* Internal Functions
*/
/**
* @notice Collects `amount` of payment for a given credit line. This sends money from the payer to the credit line.
* Note that payment is not *applied* when calling this function. Only collected (ie. held) for later application.
* @param cl The CreditLine the payment will be collected for.
* @param amount The amount, in USDC atomic units, to be collected
*/
function collectPayment(CreditLine cl, uint256 amount) internal {
require(withinTransactionLimit(amount), "Amount is over the per-transaction limit");
emit PaymentCollected(msg.sender, address(cl), amount);
bool success = config.getPool().transferFrom(msg.sender, address(cl), amount);
require(success, "Failed to collect payment");
}
/**
* @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool.
* It also updates all the accounting variables. Note that interest is always paid back first, then principal.
* Any extra after paying the minimum will go towards existing principal (reducing the
* effective interest rate). Any extra after the full loan has been paid off will remain in the
* USDC Balance of the creditLine, where it will be automatically used for the next drawdown.
* @param cl The CreditLine the payment will be collected for.
* @param amount The amount, in USDC atomic units, to be applied
* @param timestamp The timestamp on which accrual calculations should be based. This allows us
* to be precise when we assess a Credit Line
*/
function _applyPayment(
CreditLine cl,
uint256 amount,
uint256 timestamp
) internal {
(uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = handlePayment(
cl,
amount,
timestamp
);
IPool pool = config.getPool();
if (interestPayment > 0 || principalPayment > 0) {
emit PaymentApplied(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining);
pool.collectInterestAndPrincipal(address(cl), interestPayment, principalPayment);
}
}
function handlePayment(
CreditLine cl,
uint256 paymentAmount,
uint256 timestamp
)
internal
returns (
uint256,
uint256,
uint256
)
{
(uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, timestamp);
Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(
paymentAmount,
cl.balance(),
interestOwed,
principalOwed
);
uint256 newBalance = cl.balance().sub(pa.principalPayment);
// Apply any additional payment towards the balance
newBalance = newBalance.sub(pa.additionalBalancePayment);
uint256 totalPrincipalPayment = cl.balance().sub(newBalance);
uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment);
updateCreditLineAccounting(
cl,
newBalance,
interestOwed.sub(pa.interestPayment),
principalOwed.sub(pa.principalPayment)
);
assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount);
return (paymentRemaining, pa.interestPayment, totalPrincipalPayment);
}
function isLate(CreditLine cl, uint256 timestamp) internal view returns (bool) {
uint256 secondsElapsedSinceFullPayment = timestamp.sub(cl.lastFullPaymentTime());
return secondsElapsedSinceFullPayment > cl.paymentPeriodInDays().mul(SECONDS_PER_DAY);
}
function getGoldfinchFactory() internal view returns (GoldfinchFactory) {
return GoldfinchFactory(config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory)));
}
function updateAndGetInterestAndPrincipalOwedAsOf(CreditLine cl, uint256 timestamp)
internal
returns (uint256, uint256)
{
(uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(
cl,
timestamp,
config.getLatenessGracePeriodInDays()
);
if (interestAccrued > 0) {
// If we've accrued any interest, update interestAccruedAsOf to the time that we've
// calculated interest for. If we've not accrued any interest, then we keep the old value so the next
// time the entire period is taken into account.
cl.setInterestAccruedAsOf(timestamp);
}
return (cl.interestOwed().add(interestAccrued), cl.principalOwed().add(principalAccrued));
}
function withinCreditLimit(
uint256 amount,
uint256 unappliedBalance,
CreditLine cl
) internal view returns (bool) {
return cl.balance().add(amount).sub(unappliedBalance) <= cl.limit();
}
function withinTransactionLimit(uint256 amount) internal view returns (bool) {
return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit));
}
function calculateNewTermEndTime(CreditLine cl, uint256 balance) internal view returns (uint256) {
// If there's no balance, there's no loan, so there's no term end time
if (balance == 0) {
return 0;
}
// Don't allow any weird bugs where we add to your current end time. This
// function should only be used on new credit lines, when we are setting them up
if (cl.termEndTime() != 0) {
return cl.termEndTime();
}
return currentTime().add(SECONDS_PER_DAY.mul(cl.termInDays()));
}
function calculateNextDueTime(CreditLine cl) internal view returns (uint256) {
uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY);
uint256 balance = cl.balance();
uint256 nextDueTime = cl.nextDueTime();
uint256 curTimestamp = currentTime();
// You must have just done your first drawdown
if (nextDueTime == 0 && balance > 0) {
return curTimestamp.add(secondsPerPeriod);
}
// Active loan that has entered a new period, so return the *next* nextDueTime.
// But never return something after the termEndTime
if (balance > 0 && curTimestamp >= nextDueTime) {
uint256 secondsToAdvance = (curTimestamp.sub(nextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod);
nextDueTime = nextDueTime.add(secondsToAdvance);
return Math.min(nextDueTime, cl.termEndTime());
}
// Your paid off, or have not taken out a loan yet, so no next due time.
if (balance == 0 && nextDueTime != 0) {
return 0;
}
// Active loan in current period, where we've already set the nextDueTime correctly, so should not change.
if (balance > 0 && curTimestamp < nextDueTime) {
return nextDueTime;
}
revert("Error: could not calculate next due time.");
}
function currentTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function underwriterCanCreateThisCreditLine(uint256 newAmount, Underwriter storage underwriter)
internal
view
returns (bool)
{
uint256 underwriterLimit = underwriter.governanceLimit;
require(underwriterLimit != 0, "underwriter does not have governance limit");
uint256 creditCurrentlyExtended = getCreditCurrentlyExtended(underwriter);
uint256 totalToBeExtended = creditCurrentlyExtended.add(newAmount);
return totalToBeExtended <= underwriterLimit;
}
function withinMaxUnderwriterLimit(uint256 amount) internal view returns (bool) {
return amount <= config.getNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit));
}
function getCreditCurrentlyExtended(Underwriter storage underwriter) internal view returns (uint256) {
uint256 creditExtended;
uint256 length = underwriter.creditLines.length;
for (uint256 i = 0; i < length; i++) {
CreditLine cl = CreditLine(underwriter.creditLines[i]);
creditExtended = creditExtended.add(cl.limit());
}
return creditExtended;
}
function updateCreditLineAccounting(
CreditLine cl,
uint256 balance,
uint256 interestOwed,
uint256 principalOwed
) internal nonReentrant {
// subtract cl from total loans outstanding
totalLoansOutstanding = totalLoansOutstanding.sub(cl.balance());
cl.setBalance(balance);
cl.setInterestOwed(interestOwed);
cl.setPrincipalOwed(principalOwed);
// This resets lastFullPaymentTime. These conditions assure that they have
// indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown)
uint256 nextDueTime = cl.nextDueTime();
if (interestOwed == 0 && nextDueTime != 0) {
// If interest was fully paid off, then set the last full payment as the previous due time
uint256 mostRecentLastDueTime;
if (currentTime() < nextDueTime) {
uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY);
mostRecentLastDueTime = nextDueTime.sub(secondsPerPeriod);
} else {
mostRecentLastDueTime = nextDueTime;
}
cl.setLastFullPaymentTime(mostRecentLastDueTime);
}
// Add new amount back to total loans outstanding
totalLoansOutstanding = totalLoansOutstanding.add(balance);
cl.setTermEndTime(calculateNewTermEndTime(cl, balance)); // pass in balance as a gas optimization
cl.setNextDueTime(calculateNextDueTime(cl));
}
function getUSDCBalance(address _address) internal view returns (uint256) {
return config.getUSDC().balanceOf(_address);
}
modifier onlyValidCreditLine(address clAddress) {
require(creditLines[clAddress] != address(0), "Unknown credit line");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/CreditDesk.sol";
contract TestCreditDesk is CreditDesk {
// solhint-disable-next-line modifiers/ensure-modifiers
function _setTotalLoansOutstanding(uint256 amount) public {
totalLoansOutstanding = amount;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../core/BaseUpgradeablePausable.sol";
import "../core/ConfigHelper.sol";
import "../core/CreditLine.sol";
import "../core/GoldfinchConfig.sol";
import "../../interfaces/IMigrate.sol";
/**
* @title V2 Migrator Contract
* @notice This is a one-time use contract solely for the purpose of migrating from our V1
* to our V2 architecture. It will be temporarily granted authority from the Goldfinch governance,
* and then revokes it's own authority and transfers it back to governance.
* @author Goldfinch
*/
contract V2Migrator is BaseUpgradeablePausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE");
using SafeMath for uint256;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
mapping(address => address) public borrowerContracts;
event CreditLineMigrated(address indexed owner, address indexed clToMigrate, address newCl, address tranchedPool);
function initialize(address owner, address _config) external initializer {
require(owner != address(0) && _config != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = GoldfinchConfig(_config);
}
function migratePhase1(GoldfinchConfig newConfig) external onlyAdmin {
pauseEverything();
migrateToNewConfig(newConfig);
migrateToSeniorPool(newConfig);
}
function migrateCreditLines(
GoldfinchConfig newConfig,
address[][] calldata creditLinesToMigrate,
uint256[][] calldata migrationData
) external onlyAdmin {
IMigrate creditDesk = IMigrate(newConfig.creditDeskAddress());
IGoldfinchFactory factory = newConfig.getGoldfinchFactory();
for (uint256 i = 0; i < creditLinesToMigrate.length; i++) {
address[] calldata clData = creditLinesToMigrate[i];
uint256[] calldata data = migrationData[i];
address clAddress = clData[0];
address owner = clData[1];
address borrowerContract = borrowerContracts[owner];
if (borrowerContract == address(0)) {
borrowerContract = factory.createBorrower(owner);
borrowerContracts[owner] = borrowerContract;
}
(address newCl, address pool) = creditDesk.migrateV1CreditLine(
clAddress,
borrowerContract,
data[0],
data[1],
data[2],
data[3],
data[4]
);
emit CreditLineMigrated(owner, clAddress, newCl, pool);
}
}
function bulkAddToGoList(GoldfinchConfig newConfig, address[] calldata members) external onlyAdmin {
newConfig.bulkAddToGoList(members);
}
function pauseEverything() internal {
IMigrate(config.creditDeskAddress()).pause();
IMigrate(config.poolAddress()).pause();
IMigrate(config.fiduAddress()).pause();
}
function migrateToNewConfig(GoldfinchConfig newConfig) internal {
uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig);
config.setAddress(key, address(newConfig));
IMigrate(config.creditDeskAddress()).updateGoldfinchConfig();
IMigrate(config.poolAddress()).updateGoldfinchConfig();
IMigrate(config.fiduAddress()).updateGoldfinchConfig();
IMigrate(config.goldfinchFactoryAddress()).updateGoldfinchConfig();
key = uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds);
newConfig.setNumber(key, 24 * 60 * 60);
key = uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays);
newConfig.setNumber(key, 365);
key = uint256(ConfigOptions.Numbers.LeverageRatio);
// 1e18 is the LEVERAGE_RATIO_DECIMALS
newConfig.setNumber(key, 3 * 1e18);
}
function upgradeImplementations(GoldfinchConfig _config, address[] calldata newDeployments) public {
address newPoolAddress = newDeployments[0];
address newCreditDeskAddress = newDeployments[1];
address newFiduAddress = newDeployments[2];
address newGoldfinchFactoryAddress = newDeployments[3];
bytes memory data;
IMigrate pool = IMigrate(_config.poolAddress());
IMigrate creditDesk = IMigrate(_config.creditDeskAddress());
IMigrate fidu = IMigrate(_config.fiduAddress());
IMigrate goldfinchFactory = IMigrate(_config.goldfinchFactoryAddress());
// Upgrade implementations
pool.changeImplementation(newPoolAddress, data);
creditDesk.changeImplementation(newCreditDeskAddress, data);
fidu.changeImplementation(newFiduAddress, data);
goldfinchFactory.changeImplementation(newGoldfinchFactoryAddress, data);
}
function migrateToSeniorPool(GoldfinchConfig newConfig) internal {
IMigrate(config.fiduAddress()).grantRole(MINTER_ROLE, newConfig.seniorPoolAddress());
IMigrate(config.poolAddress()).unpause();
IMigrate(newConfig.poolAddress()).migrateToSeniorPool();
}
function closeOutMigration(GoldfinchConfig newConfig) external onlyAdmin {
IMigrate fidu = IMigrate(newConfig.fiduAddress());
IMigrate creditDesk = IMigrate(newConfig.creditDeskAddress());
IMigrate oldPool = IMigrate(newConfig.poolAddress());
IMigrate goldfinchFactory = IMigrate(newConfig.goldfinchFactoryAddress());
fidu.unpause();
fidu.renounceRole(MINTER_ROLE, address(this));
fidu.renounceRole(OWNER_ROLE, address(this));
fidu.renounceRole(PAUSER_ROLE, address(this));
creditDesk.renounceRole(OWNER_ROLE, address(this));
creditDesk.renounceRole(PAUSER_ROLE, address(this));
oldPool.renounceRole(OWNER_ROLE, address(this));
oldPool.renounceRole(PAUSER_ROLE, address(this));
goldfinchFactory.renounceRole(OWNER_ROLE, address(this));
goldfinchFactory.renounceRole(PAUSER_ROLE, address(this));
config.renounceRole(PAUSER_ROLE, address(this));
config.renounceRole(OWNER_ROLE, address(this));
newConfig.renounceRole(OWNER_ROLE, address(this));
newConfig.renounceRole(PAUSER_ROLE, address(this));
newConfig.renounceRole(GO_LISTER_ROLE, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IMigrate {
function pause() public virtual;
function unpause() public virtual;
function updateGoldfinchConfig() external virtual;
function grantRole(bytes32 role, address assignee) external virtual;
function renounceRole(bytes32 role, address self) external virtual;
// Proxy methods
function transferOwnership(address newOwner) external virtual;
function changeImplementation(address newImplementation, bytes calldata data) external virtual;
function owner() external view virtual returns (address);
// CreditDesk
function migrateV1CreditLine(
address _clToMigrate,
address borrower,
uint256 termEndTime,
uint256 nextDueTime,
uint256 interestAccruedAsOf,
uint256 lastFullPaymentTime,
uint256 totalInterestPaid
) public virtual returns (address, address);
// Pool
function migrateToSeniorPool() external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/Pool.sol";
contract TestPool is Pool {
function _getNumShares(uint256 amount) public view returns (uint256) {
return getNumShares(amount);
}
function _usdcMantissa() public pure returns (uint256) {
return usdcMantissa();
}
function _fiduMantissa() public pure returns (uint256) {
return fiduMantissa();
}
function _usdcToFidu(uint256 amount) public pure returns (uint256) {
return usdcToFidu(amount);
}
function _setSharePrice(uint256 newSharePrice) public returns (uint256) {
sharePrice = newSharePrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/Pool.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
contract FakeV2CreditLine is BaseUpgradeablePausable {
// Credit line terms
address public borrower;
address public underwriter;
uint256 public limit;
uint256 public interestApr;
uint256 public paymentPeriodInDays;
uint256 public termInDays;
uint256 public lateFeeApr;
// Accounting variables
uint256 public balance;
uint256 public interestOwed;
uint256 public principalOwed;
uint256 public termEndTime;
uint256 public nextDueTime;
uint256 public interestAccruedAsOf;
uint256 public writedownAmount;
uint256 public lastFullPaymentTime;
function initialize(
address owner,
address _borrower,
address _underwriter,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr
) public initializer {
__BaseUpgradeablePausable__init(owner);
borrower = _borrower;
underwriter = _underwriter;
limit = _limit;
interestApr = _interestApr;
paymentPeriodInDays = _paymentPeriodInDays;
termInDays = _termInDays;
lateFeeApr = _lateFeeApr;
interestAccruedAsOf = block.timestamp;
}
function anotherNewFunction() external pure returns (uint256) {
return 42;
}
function authorizePool(address) external view onlyAdmin {
// no-op
return;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "../../interfaces/IGo.sol";
import "../../interfaces/IUniqueIdentity0612.sol";
contract Go is IGo, BaseUpgradeablePausable {
address public override uniqueIdentity;
using SafeMath for uint256;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
GoldfinchConfig public legacyGoList;
uint256[11] public allIdTypes;
event GoldfinchConfigUpdated(address indexed who, address configAddress);
function initialize(
address owner,
GoldfinchConfig _config,
address _uniqueIdentity
) public initializer {
require(
owner != address(0) && address(_config) != address(0) && _uniqueIdentity != address(0),
"Owner and config and UniqueIdentity addresses cannot be empty"
);
__BaseUpgradeablePausable__init(owner);
_performUpgrade();
config = _config;
uniqueIdentity = _uniqueIdentity;
}
function updateGoldfinchConfig() external override onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
function performUpgrade() external onlyAdmin {
return _performUpgrade();
}
function _performUpgrade() internal {
allIdTypes[0] = ID_TYPE_0;
allIdTypes[1] = ID_TYPE_1;
allIdTypes[2] = ID_TYPE_2;
allIdTypes[3] = ID_TYPE_3;
allIdTypes[4] = ID_TYPE_4;
allIdTypes[5] = ID_TYPE_5;
allIdTypes[6] = ID_TYPE_6;
allIdTypes[7] = ID_TYPE_7;
allIdTypes[8] = ID_TYPE_8;
allIdTypes[9] = ID_TYPE_9;
allIdTypes[10] = ID_TYPE_10;
}
/**
* @notice sets the config that will be used as the source of truth for the go
* list instead of the config currently associated. To use the associated config for to list, set the override
* to the null address.
*/
function setLegacyGoList(GoldfinchConfig _legacyGoList) external onlyAdmin {
legacyGoList = _legacyGoList;
}
/**
* @notice Returns whether the provided account is go-listed for use of the Goldfinch protocol
* for any of the UID token types.
* This status is defined as: whether `balanceOf(account, id)` on the UniqueIdentity
* contract is non-zero (where `id` is a supported token id on UniqueIdentity), falling back to the
* account's status on the legacy go-list maintained on GoldfinchConfig.
* @param account The account whose go status to obtain
* @return The account's go status
*/
function go(address account) public view override returns (bool) {
require(account != address(0), "Zero address is not go-listed");
if (_getLegacyGoList().goList(account) || IUniqueIdentity0612(uniqueIdentity).balanceOf(account, ID_TYPE_0) > 0) {
return true;
}
// start loop at index 1 because we checked index 0 above
for (uint256 i = 1; i < allIdTypes.length; ++i) {
uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, allIdTypes[i]);
if (idTypeBalance > 0) {
return true;
}
}
return false;
}
/**
* @notice Returns whether the provided account is go-listed for use of the Goldfinch protocol
* for defined UID token types
* @param account The account whose go status to obtain
* @param onlyIdTypes Array of id types to check balances
* @return The account's go status
*/
function goOnlyIdTypes(address account, uint256[] memory onlyIdTypes) public view override returns (bool) {
require(account != address(0), "Zero address is not go-listed");
GoldfinchConfig goListSource = _getLegacyGoList();
for (uint256 i = 0; i < onlyIdTypes.length; ++i) {
if (onlyIdTypes[i] == ID_TYPE_0 && goListSource.goList(account)) {
return true;
}
uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, onlyIdTypes[i]);
if (idTypeBalance > 0) {
return true;
}
}
return false;
}
/**
* @notice Returns whether the provided account is go-listed for use of the SeniorPool on the Goldfinch protocol.
* @param account The account whose go status to obtain
* @return The account's go status
*/
function goSeniorPool(address account) public view override returns (bool) {
require(account != address(0), "Zero address is not go-listed");
if (account == config.stakingRewardsAddress() || _getLegacyGoList().goList(account)) {
return true;
}
uint256[2] memory seniorPoolIdTypes = [ID_TYPE_0, ID_TYPE_1];
for (uint256 i = 0; i < seniorPoolIdTypes.length; ++i) {
uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, seniorPoolIdTypes[i]);
if (idTypeBalance > 0) {
return true;
}
}
return false;
}
function _getLegacyGoList() internal view returns (GoldfinchConfig) {
return address(legacyGoList) == address(0) ? config : legacyGoList;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/// @dev This interface provides a subset of the functionality of the IUniqueIdentity
/// interface -- namely, the subset of functionality needed by Goldfinch protocol contracts
/// compiled with Solidity version 0.6.12.
interface IUniqueIdentity0612 {
function balanceOf(address account, uint256 id) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/GoldfinchConfig.sol";
contract TestTheConfig {
address public poolAddress = 0xBAc2781706D0aA32Fb5928c9a5191A13959Dc4AE;
address public clImplAddress = 0xc783df8a850f42e7F7e57013759C285caa701eB6;
address public goldfinchFactoryAddress = 0x0afFE1972479c386A2Ab21a27a7f835361B6C0e9;
address public fiduAddress = 0xf3c9B38c155410456b5A98fD8bBf5E35B87F6d96;
address public creditDeskAddress = 0xeAD9C93b79Ae7C1591b1FB5323BD777E86e150d4;
address public treasuryReserveAddress = 0xECd9C93B79AE7C1591b1fB5323BD777e86E150d5;
address public trustedForwarderAddress = 0x956868751Cc565507B3B58E53a6f9f41B56bed74;
address public cUSDCAddress = 0x5B281A6DdA0B271e91ae35DE655Ad301C976edb1;
address public goldfinchConfigAddress = address(8);
function testTheEnums(address configAddress) public {
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TransactionLimit), 1);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit), 2);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit), 3);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.ReserveDenominator), 4);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator), 5);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays), 6);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays), 7);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds), 8);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays), 9);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LeverageRatio), 10);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Fidu), fiduAddress);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Pool), poolAddress);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CreditDesk), creditDeskAddress);
GoldfinchConfig(configAddress).setAddress(
uint256(ConfigOptions.Addresses.GoldfinchFactory),
goldfinchFactoryAddress
);
GoldfinchConfig(configAddress).setAddress(
uint256(ConfigOptions.Addresses.TrustedForwarder),
trustedForwarderAddress
);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CUSDCContract), cUSDCAddress);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig), goldfinchConfigAddress);
GoldfinchConfig(configAddress).setTreasuryReserve(treasuryReserveAddress);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/GoldfinchConfig.sol";
contract TestGoldfinchConfig is GoldfinchConfig {
function setAddressForTest(uint256 addressKey, address newAddress) public {
addresses[addressKey] = newAddress;
}
}
|
Enables the transfer of GFI rewards (referred to as a "grant"), if the grant details exist in this contract's Merkle root.
|
interface IMerkleDirectDistributor {
function gfi() external view returns (address);
function merkleRoot() external view returns (bytes32);
function isGrantAccepted(uint256 index) external view returns (bool);
function acceptGrant(
uint256 index,
uint256 amount,
bytes32[] calldata merkleProof
) external;
event GrantAccepted(uint256 indexed index, address indexed account, uint256 amount);
pragma solidity 0.6.12;
}
| 6,235,182 |
./full_match/80001/0x2aC04fc70D237f181BE0b33A53bB6Bb23CDa76E6/sources/project_/contracts/MysticGalacticMission1.sol
|
Mints new NFTs from the reserved supply for the caller. Can only be called by the reserve minter account and when the contract is not paused. bottles The number of NFTs to be minted from the reserved supply./
|
function mintNFTReserved(uint256 bottles) public onlyReserveMinter whenNotPaused {
sm.mintFromReservedSupply(msg.sender, bottles);
}
| 9,432,021 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.6.4 <0.8.0;
pragma experimental ABIEncoderV2;
///
/// @dev EIP-1153 License Transaction Encoder Library
/// @author Tyler R. Drury <[email protected]> (www.twitter.com/StudiosVigil) - copyright 29/8/2021, All Rights Reserved
///
library abiEncoderEIP1753
{
//
//getter stubs
//
string internal constant STUB_HAS_VALID_LICENSE = 'hasValidLicense(address)';
string internal constant STUB_HAS_AUTHORITY = 'hasAuthority(address)';
//
//mutable stubs
//
string internal constant STUB_GRANT_AUTHORITY = 'grantAuthority(address)';
string internal constant STUB_REVOKE_AUTHORITY = 'revokeAuthority(address)';
//
string internal constant STUB_ISSUE = 'issue(address,uint,uint)';
string internal constant STUB_REVOKE = 'revoke(address)';
//
// = 'purchase(uint,uint)';
// = 'renewTime(address,uint)';
// = 'renewDuration(address,uint)';
//
//current circulating supply(licnese which have been issued)
//function circulatingSupply(
//)internal pure returns(
//bytes memory
//);
//totalSupply - issued
//function remainingSupply(
//)internal view returns(
//uint256
//);
//does client currently hold a valid license
function hasValidLicense(
address client
)internal pure returns(
bytes memory
){
return abi.encodeWithSignature(
STUB_HAS_VALID_LICENSE,
client
);
}
//amount of seconds from now client has until their license is expired
//function durationRemaining(
//address client
//)internal pure returns(
//bytes memory
//){
//return abi.encodeWithSignature(
//STUB_DURATION_REMAINING,
//client
//);
//}
/// does client have authority to issue/revoke licenses
function hasAuthority(
address client
)internal pure returns(
bytes memory
){
return abi.encodeWithSignature(
STUB_HAS_AUTHORITY,
client
);
}
///
///mutable interface
///
///owner grants account elevated privellages (such as issuing and revoking licenses)
///issuing authorities can NOT themselves grant or revoke authority,
///that should be an owner/admin privellage ONLY
function grantAuthority(
address account
)internal pure returns(
bytes memory
){
return abi.encodeWithSignature(
STUB_GRANT_AUTHORITY,
account
);
}
//revoke account's elevated privellages as an issuing authority
function revokeAuthority(
address account
)internal pure returns(
bytes memory
){
return abi.encodeWithSignature(
STUB_REVOKE_AUTHORITY,
account
);
}
///an issuing authority issues client a license which is valid between the timestamp from,
///until the timestamp to from can be retroactive (in the past) but to MUST always be in the future
function issue(
address client,
uint from,
uint to
)internal pure returns(
bytes memory
){
return abi.encodeWithSignature(
STUB_ISSUE,
client,
from,
to
);
}
///issuing authority revokes client's license
///reverts if client does not have a license or if caller is not an issuing authority
function revoke(
address client
)internal pure returns(
bytes memory
){
return abi.encodeWithSignature(
STUB_REVOKE,
client
);
}
/**
///notice interfaces can not have payable functions for some reason
///
///caller purchases a license, if one is available, otherwise reverts
function purchase(
uint validFrom,
uint validTo
)internal pure returns(
bytes memory
);
///renew an active license, extending to timestamp time
function renewTime(
address client,
uint time
)internal pure returns(
bytes memory
);
///renew an active license, extending by duration seconds
function renewDuration(
address client,
uint duration
)internal pure returns(
bytes memory
)
{
return abi.encodeWithSignature(
STUB_REVOKE_ALLOWANCE,
spender
);
}
*/
}
|
does client have authority to issue/revoke licenses
|
function hasAuthority(
address client
)internal pure returns(
bytes memory
){
return abi.encodeWithSignature(
STUB_HAS_AUTHORITY,
client
);
}
| 974,476 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.9; // code below expects that integer overflows will revert
import "./Vendor/openzeppelin-contracts-3dadd40034961d5ca75fa209a4188b01d7129501/token/ERC721/IERC721.sol";
import "./Vendor/openzeppelin-contracts-3dadd40034961d5ca75fa209a4188b01d7129501/access/Ownable.sol";
import "./Utilities/Withdrawable.sol";
/// @title Area marketplace contract, 🌐 the earth on the blockchain, 📌 geolocation NFTs
/// @notice This decentralized marketplace matches bids and offers for one underlying ERC-721 contract. With much
/// respect to CryptoPunks. Your offers & bids on this marketplace will close only if matched on this
/// marketplace. If you trade anywhere else, consider to revoke your offers & bids here.
/// @author William Entriken
contract NFTMarketplace is Ownable, Withdrawable {
struct TokenMarket {
address offeror; // The token owner that is selling
uint256 minimumOffer; // The amount (in Wei) that is the minimum to accept; or zero to indicate no offer
address invitedBidder; // The exclusive invited buyer for this offer; or the zero address if not exclusive
address bidder; // The party that committed Ether to bid
uint256 lockedBid; // The amount (in Wei) that the bidder has committed
}
/// @notice The underlying asset contract
IERC721 immutable public tokenContract;
/// @notice The transaction fee (in basis points) as a portion of the sale price
uint256 public feePortion;
/// @notice The best bids and offers for any token
mapping(uint256 => TokenMarket) public tokenMarkets;
/// @notice A token is offered for sale by owner; or such an offer is revoked
/// @param tokenId which token
/// @param offeror the token owner that is selling
/// @param minimumOffer the amount (in Wei) that is the minimum to accept; or zero to indicate no offer
/// @param invitedBidder the exclusive invited buyer for this offer; or the zero address if not exclusive
event OfferUpdated(uint256 indexed tokenId, address offeror, uint256 minimumOffer, address invitedBidder);
/// @notice A new highest bid is committed for a token; or such a bid is revoked
/// @param tokenId which token
/// @param bidder the party that committed Ether to bid
/// @param lockedBid the amount (in Wei) that the bidder has committed
event BidUpdated(uint256 indexed tokenId, address bidder, uint256 lockedBid);
/// @notice A token is traded on the marketplace (this implies any offer for the token is revoked)
/// @param tokenId which token
/// @param value the sale price
/// @param offeror the party that previously owned the token
/// @param bidder the party that now owns the token
event Traded(uint256 indexed tokenId, uint256 value, address indexed offeror, address indexed bidder);
/// @param initialFeePortion the transaction fee (in basis points) as a portion of the sale price
/// @param immutableNftTokenContract the underlying NFT asset
constructor(uint256 initialFeePortion, IERC721 immutableNftTokenContract) {
feePortion = initialFeePortion;
tokenContract = immutableNftTokenContract;
}
/// @notice An offeror may revoke their offer
/// @dev It is possible that a token will change owners without this contract being notified (e.g. an ERC-721
/// "gift" transaction). In this case the old owner who made an offer needs, and gets, a way to revoke that.
/// There is no reason why the new owner of a token would need to revoke the prior owner's ineffectual
/// offer. But we provide this option anyway because we recognize the token market to be the prerogative of
/// that token's owner.
/// @param tokenId which token
function revokeOffer(uint256 tokenId) external {
require(
(msg.sender == tokenMarkets[tokenId].offeror) ||
(msg.sender == tokenContract.ownerOf(tokenId)),
"Only the offeror or token owner may revoke an offer"
);
_setOffer(tokenId, address(0), 0, address(0));
}
/// @notice Any token owner may offer it for sale
/// @dev If a bid comes which is higher than the offer then the sale price will be this higher amount.
/// @param tokenId which token
/// @param minimumOffer the amount (in Wei) that is the minimum to accept
/// @param invitedBidder the exclusive invited buyer for this offer; or the zero address if not exclusive
function offer(uint256 tokenId, uint256 minimumOffer, address invitedBidder) external {
require(msg.sender == tokenContract.ownerOf(tokenId), "Only the token owner can offer");
require(minimumOffer > 0, "Ask for more");
address bidder = tokenMarkets[tokenId].bidder;
uint256 lockedBid = tokenMarkets[tokenId].lockedBid;
bool isInvited = invitedBidder == address(0) || invitedBidder == bidder;
// Can we match this offer to an existing bid?
if (lockedBid >= minimumOffer && isInvited) {
_doTrade(tokenId, lockedBid, msg.sender, bidder);
_setBid(tokenId, address(0), 0);
} else {
_setOffer(tokenId, msg.sender, minimumOffer, invitedBidder);
}
}
/// @notice An bidder may revoke their bid
/// @param tokenId which token
function revokeBid(uint256 tokenId) external {
require(msg.sender == tokenMarkets[tokenId].bidder, "Only the bidder may revoke their bid");
_increasePendingWithdrawal(msg.sender, tokenMarkets[tokenId].lockedBid);
_setBid(tokenId, address(0), 0);
}
/// @notice Anyone may commit more than the existing bid for a token.
/// @dev When reading the below, note there are three important contexts to consider:
/// 1. There is no existing bidder
/// 2. The message caller is the highest bidder
/// 3. Somebody else is the highest bidder
/// when you submit this transaction and when it settles.
/// @param tokenId which token
function bid(uint256 tokenId) external payable {
uint256 existingLockedBid = tokenMarkets[tokenId].lockedBid;
require(msg.value > existingLockedBid, "Bid too low");
address existingBidder = tokenMarkets[tokenId].bidder;
uint256 minimumOffer = tokenMarkets[tokenId].minimumOffer;
address invitedBidder = tokenMarkets[tokenId].invitedBidder;
address offeror = tokenMarkets[tokenId].offeror;
bool isInvited = invitedBidder == address(0) || invitedBidder == msg.sender;
// Can we match this bid to an existing offer?
if (minimumOffer > 0 &&
msg.value >= minimumOffer &&
isInvited &&
offeror == tokenContract.ownerOf(tokenId)) {
_doTrade(tokenId, msg.value, offeror, msg.sender);
if (existingBidder == msg.sender) {
// This is context 2
_increasePendingWithdrawal(msg.sender, existingLockedBid);
_setBid(tokenId, address(0), 0);
}
} else {
// Wind up old bid, if any
if (existingLockedBid > 0) {
// This is context 2 or 3
_increasePendingWithdrawal(existingBidder, existingLockedBid);
}
// Enter new bid
_setBid(tokenId, msg.sender, msg.value);
}
}
/// @notice Anyone may add more value to their existing bid
/// @param tokenId which token
function bidIncrease(uint256 tokenId) external payable {
require(msg.value > 0, "Must send value to increase bid");
require(msg.sender == tokenMarkets[tokenId].bidder, "You are not current bidder");
uint256 newBidAmount = tokenMarkets[tokenId].lockedBid + msg.value;
uint256 minimumOffer = tokenMarkets[tokenId].minimumOffer;
address invitedBidder = tokenMarkets[tokenId].invitedBidder;
address offeror = tokenMarkets[tokenId].offeror;
bool isInvited = invitedBidder == address(0) || invitedBidder == msg.sender;
// Can we match this bid to an existing offer?
if (minimumOffer > 0 &&
newBidAmount >= minimumOffer &&
isInvited &&
offeror == tokenContract.ownerOf(tokenId)) {
_doTrade(tokenId, newBidAmount, offeror, msg.sender);
_setBid(tokenId, address(0), 0);
} else {
tokenMarkets[tokenId].lockedBid = newBidAmount;
_setBid(tokenId, msg.sender, newBidAmount);
}
}
/// @notice The owner can set the fee portion
/// @param newFeePortion the transaction fee (in basis points) as a portion of the sale price
function setFeePortion(uint256 newFeePortion) external onlyOwner {
require(newFeePortion <= 1000, "Exceeded maximum fee portion of 10%");
feePortion = newFeePortion;
}
/// @dev Collect fee for owner & offeror and transfer underlying asset. The Traded event emits before the
/// ERC721.Transfer event so that somebody observing the events and seeing the latter will recognize the
/// context of the former. The bid is NOT cleaned up generally in this function because a circumstance exists
/// where an existing bid persists after a trade. See "context 3" above.
function _doTrade(uint256 tokenId, uint256 value, address offeror, address bidder) private {
// Divvy up proceeds
uint256 feeAmount = value * feePortion / 10000; // reverts on overflow
_increasePendingWithdrawal(Ownable.owner(), feeAmount);
_increasePendingWithdrawal(offeror, value - feeAmount);
emit Traded(tokenId, value, offeror, bidder);
tokenMarkets[tokenId].offeror = address(0);
tokenMarkets[tokenId].minimumOffer = 0;
tokenMarkets[tokenId].invitedBidder = address(0);
tokenContract.transferFrom(offeror, bidder, tokenId);
}
/// @dev Set and emit new offer
function _setOffer(uint256 tokenId, address offeror, uint256 minimumOffer, address invitedBidder) private {
tokenMarkets[tokenId].offeror = offeror;
tokenMarkets[tokenId].minimumOffer = minimumOffer;
tokenMarkets[tokenId].invitedBidder = invitedBidder;
emit OfferUpdated(tokenId, offeror, minimumOffer, invitedBidder);
}
/// @dev Set and emit new bid
function _setBid(uint256 tokenId, address bidder, uint256 lockedBid) private {
tokenMarkets[tokenId].bidder = bidder;
tokenMarkets[tokenId].lockedBid = lockedBid;
emit BidUpdated(tokenId, bidder, lockedBid);
}
}
|
The owner can set the fee portion newFeePortion the transaction fee (in basis points) as a portion of the sale price
|
function setFeePortion(uint256 newFeePortion) external onlyOwner {
require(newFeePortion <= 1000, "Exceeded maximum fee portion of 10%");
feePortion = newFeePortion;
}
| 5,460,796 |
./full_match/1/0x7e1e077b289c0153b5ceAD9F264d66215341c9Ab/sources/contracts/plugins/assets/compoundv3/WrappedERC20.sol
|
See {IERC20-transfer}. Requirements: - `to` cannot be the zero address. - the caller must have a balance of at least `amount`./
|
function transfer(address to, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, to, amount);
return true;
}
| 3,138,300 |
./full_match/5/0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45/sources/contracts/V3SwapRouter.sol
|
@inheritdoc IV3SwapRouter
|
function exactOutput(ExactOutputParams calldata params) external payable override returns (uint256 amountIn) {
exactOutputInternal(
params.amountOut,
params.recipient,
0,
);
amountIn = amountInCached;
require(amountIn <= params.amountInMaximum, 'Too much requested');
amountInCached = DEFAULT_AMOUNT_IN_CACHED;
}
| 1,926,418 |
pragma solidity ^0.4.23;
//import "./Receiver_Interface.sol";
contract ContractReceiver {
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint _value, bytes _data) public pure {
TKN memory tkn;
tkn.sender = _from;
tkn.value = _value;
tkn.data = _data;
uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
tkn.sig = bytes4(u);
/* tkn variable is analogue of msg variable of Ether transaction
* tkn.sender is person who initiated this token transaction (analogue of msg.sender)
* tkn.value the number of tokens that were sent (analogue of msg.value)
* tkn.data is data of token transaction (analogue of msg.data)
* tkn.sig is 4 bytes signature of function
* if data of token transaction is a function execution
*/
}
}
//import "./ERC223_Interface.sol";
contract ERC223 {
uint public totalSupply;
function balanceOf(address who) public view returns (uint);
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function decimals() public view returns (uint8 _decimals);
function totalSupply() public view returns (uint256 _supply);
function transfer(address to, uint value) public returns (bool ok);
function transfer(address to, uint value, bytes data) public returns (bool ok);
function transfer(address to, uint value, bytes data, string custom_fallback) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
}
/**
* ERC223 token by Dexaran
*
* https://github.com/Dexaran/ERC223-token-standard
*/
/* https://github.com/LykkeCity/EthereumApiDotNetCore/blob/master/src/ContractBuilder/contracts/token/SafeMath.sol */
contract SafeMath {
uint256 constant public MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
function safeAdd(uint256 x, uint256 y) pure internal returns (uint256 z) {
if (x > MAX_UINT256 - y) revert();
return x + y;
}
function safeSub(uint256 x, uint256 y) pure internal returns (uint256 z) {
if (x < y) revert();
return x - y;
}
function safeMul(uint256 x, uint256 y) pure internal returns (uint256 z) {
if (y == 0) return 0;
if (x > MAX_UINT256 / y) revert();
return x * y;
}
}
contract PiperToken is ERC223, SafeMath {
mapping(address => uint) balances;
string public name = "Peid Piper Token";
string public symbol = "PIP";
uint8 public decimals = 18;
uint256 public totalSupply = 0;
uint256 exchange = 1000000;
uint256 endICO = 0;
address admin;
constructor() public {
balances[msg.sender]=1000000000000000000000000;
admin = msg.sender;
endICO=block.timestamp+(60*60*24*31); // 31 days
}
// Function to access name of token .
function name() public view returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() public view returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
function () public payable{
if(block.timestamp>endICO)revert("ICO OVER");
balances[msg.sender]=safeAdd(balances[msg.sender],safeMul(msg.value,exchange));
totalSupply=safeAdd(totalSupply,safeMul(msg.value,exchange)); // increase the supply
admin.transfer(address(this).balance);
}
function getEndICO() public constant returns (uint256){
return endICO;
}
function getCurrentTime() public constant returns (uint256){
return block.timestamp;
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) {
if(isContract(_to)) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value) public returns (bool success) {
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
}
|
Function to access total supply of tokens .
|
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
| 6,513,054 |
./full_match/4/0x5EAee32F7C74b3868ECb286112D72D549981317a/sources/contracts/OrangeadNFT.sol
|
return an URI for a given _tokenId _tokenId The ID of the desired NFT/
|
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealTime == 0) {
return unrevealedURI;
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(
abi.encodePacked(baseURI, _tokenId.toString(), ".json")
)
: "";
}
}
| 12,351,286 |
pragma solidity 0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
interface TokenInterface {
function totalSupply() external constant returns (uint);
function balanceOf(address tokenOwner) external constant returns (uint balance);
function allowance(address tokenOwner, address spender) external constant returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
function burn(uint256 _value) external;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Burn(address indexed burner, uint256 value);
}
contract PVCCrowdsale is Ownable{
using SafeMath for uint256;
// The token being sold
TokenInterface public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// how many token units a buyer gets per wei
uint256 public ratePerWei = 1000;
// amount of raised money in wei
uint256 public weiRaised;
uint256 public TOKENS_SOLD;
uint256 maxTokensToSale;
uint256 TokensForTeamVesting;
uint256 TokensForAdvisorVesting;
uint256 bonusInPreSalePhase1;
uint256 bonusInPreSalePhase2;
uint256 bonusInPublicSalePhase1;
uint256 bonusInPublicSalePhase2;
uint256 bonusInPublicSalePhase3;
bool isCrowdsalePaused = false;
uint256 totalDurationInDays = 75 days;
mapping(address=>bool) isAddressWhiteListed;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function PVCCrowdsale(uint256 _startTime, address _wallet, address _tokenAddress) public
{
require(_wallet != 0x0);
//TODO: Uncomment the following before deployment on main network
require(_startTime >=now);
startTime = _startTime;
//TODO: Comment the following when deploying on main network
//startTime = now;
endTime = startTime + totalDurationInDays;
require(endTime >= startTime);
owner = _wallet;
maxTokensToSale = 32500000 * 10 ** 18;
bonusInPreSalePhase1 = 30;
bonusInPreSalePhase2 = 25;
bonusInPublicSalePhase1 = 20;
bonusInPreSalePhase2 = 10;
bonusInPublicSalePhase3 = 5;
TokensForTeamVesting = 7000000 * 10 ** 18;
TokensForAdvisorVesting = 3000000 * 10 ** 18;
token = TokenInterface(_tokenAddress);
}
// fallback function can be used to buy tokens
function () public payable {
buyTokens(msg.sender);
}
function determineBonus(uint tokens) internal view returns (uint256 bonus)
{
uint256 timeElapsed = now - startTime;
uint256 timeElapsedInDays = timeElapsed.div(1 days);
//Closed pre-sale phase 1 (8 days)
if (timeElapsedInDays <8)
{
bonus = tokens.mul(bonusInPreSalePhase1);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSale);
}
//Closed pre-sale phase 2 (8 days)
else if (timeElapsedInDays >=8 && timeElapsedInDays <16)
{
bonus = tokens.mul(bonusInPreSalePhase2);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSale);
}
//Public sale phase 1 (30 days)
else if (timeElapsedInDays >=16 && timeElapsedInDays <46)
{
bonus = tokens.mul(bonusInPublicSalePhase1);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSale);
}
//Public sale phase 2 (11 days)
else if (timeElapsedInDays >=46 && timeElapsedInDays <57)
{
bonus = tokens.mul(bonusInPublicSalePhase2);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSale);
}
//Public sale phase 3 (6 days)
else if (timeElapsedInDays >=57 && timeElapsedInDays <63)
{
bonus = tokens.mul(bonusInPublicSalePhase3);
bonus = bonus.div(100);
require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSale);
}
//Public sale phase 4 (11 days)
else
{
bonus = 0;
}
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(isCrowdsalePaused == false);
require(isAddressWhiteListed[beneficiary] == true);
require(validPurchase());
require(TOKENS_SOLD<maxTokensToSale);
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(ratePerWei);
uint256 bonus = determineBonus(tokens);
tokens = tokens.add(bonus);
// update state
weiRaised = weiRaised.add(weiAmount);
token.transfer(beneficiary,tokens);
emit TokenPurchase(owner, beneficiary, weiAmount, tokens);
TOKENS_SOLD = TOKENS_SOLD.add(tokens);
forwardFunds();
}
// send ether to the fund collection wallet
function forwardFunds() internal {
owner.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endTime;
}
/**
* function to change the end timestamp of the ico
* can only be called by owner wallet
**/
function changeEndDate(uint256 endTimeUnixTimestamp) public onlyOwner{
endTime = endTimeUnixTimestamp;
}
/**
* function to change the start timestamp of the ico
* can only be called by owner wallet
**/
function changeStartDate(uint256 startTimeUnixTimestamp) public onlyOwner{
startTime = startTimeUnixTimestamp;
}
/**
* function to change the rate of tokens
* can only be called by owner wallet
**/
function setPriceRate(uint256 newPrice) public onlyOwner {
ratePerWei = newPrice;
}
/**
* function to pause the crowdsale
* can only be called from owner wallet
**/
function pauseCrowdsale() public onlyOwner {
isCrowdsalePaused = true;
}
/**
* function to resume the crowdsale if it is paused
* can only be called from owner wallet
**/
function resumeCrowdsale() public onlyOwner {
isCrowdsalePaused = false;
}
/**
* function through which owner can remove an address from whitelisting
**/
function addAddressToWhitelist(address _whitelist) public onlyOwner
{
isAddressWhiteListed[_whitelist]= true;
}
/**
* function through which owner can whitelist an address
**/
function removeAddressToWhitelist(address _whitelist) public onlyOwner
{
isAddressWhiteListed[_whitelist]= false;
}
/**
* function through which owner can take back the tokens from the contract
**/
function takeTokensBack() public onlyOwner
{
uint remainingTokensInTheContract = token.balanceOf(address(this));
token.transfer(owner,remainingTokensInTheContract);
}
/**
* once the ICO has ended, owner can send all the unsold tokens to treasury address
**/
function sendUnsoldTokensToTreasury(address treasury) public onlyOwner
{
require(hasEnded());
uint remainingTokensInTheContract = token.balanceOf(address(this));
token.transfer(treasury,remainingTokensInTheContract);
}
}
|
function through which owner can remove an address from whitelisting/
|
function addAddressToWhitelist(address _whitelist) public onlyOwner
{
isAddressWhiteListed[_whitelist]= true;
}
| 2,261,336 |
./full_match/4337/0xd71E61dde321dCDe58886479A47f1142bBF0C6d6/sources/contracts/paymaster/OpenfortPaymasterV2.sol
|
The new owner accepts the ownership transfer. If the new owner had some native tokens deposited to the Paymaster, they will now be part of the owner's deposit./
|
function acceptOwnership() public override {
totalDepositorBalances -= depositorBalances[pendingOwner()];
depositorBalances[pendingOwner()] = 0;
super.acceptOwnership();
}
| 13,221,862 |
/// @title Marketplace: A marketplace for listing and buying products
/// @author John McCrae
/// @notice This contract inherits EmergencyStop, a contract that implements the circuit breaker design pattern
/// @dev This contract requires solidity compiler version 0.5 or higher.
pragma solidity ^0.5.0;
/// @dev This contract imports EmergencyStop.sol
import "./EmergencyStop.sol";
/// @dev Marketplace: A contract for listing and buying products
contract Marketplace is EmergencyStop {
/// @param ownerMarketplace A public payable address data type
address payable public ownerMarketplace;
/// @param productIDGen A public uint data type to keep track of product ID numbers.
uint public productIDGen;
/// @param managerIDGen A public uint data type to keep track of manager ID numbers
uint public managerIDGen;
/// @param productName A string data type to keep track of store product names
/// @param totalUnits A uint data type to keep track of total store product units
/// @param unitPrice A uint data type to keep track of store product unit prices
/// @param forSale A uint data type to keep track of whether store product is for sale
/// @param buyersAcc A uint data type to keep track of total product units held within the buyers account
struct Product {
string productName;
uint totalUnits;
uint unitPrice;
bool forSale;
mapping (address => uint) buyersAcc;
}
/// @param managerID A uint data type to keep track of store manager ID numbers
/// @param managerName A string data type to keep track of store manager names
/// @param managerAuth A boolean data type to keep track of store manager authorisation
struct Managers {
uint managerID;
string managerName;
bool managerAuth;
}
/// @param storeProd A mapping data type with key as uint (store product ID) and value as struct Products (store product data)
mapping (uint => Product) public storeProd;
/// @param storeMan A mapping data type with key as address (store manager address) and value as struct Managers (store manager data)
mapping (address => Managers) public storeMan;
/// @dev _xxxProductID A uint data type to keep track of store product ID numbers
/// @dev _xxxProductName A string data type to keep track of store product names
/// @dev _xxxTotalUnits A uint data type to keep track of total store product units
/// @dev _xxxUnitPrice A uint data type to keep track of store product unit prices
/// @dev _xxxforSale A uint data type to keep track of whether store product is for sale
/// @dev _xxxbuyersAcc A uint data type to keep track of total product units held within the buyers account
/// @dev _readStoreFunds A uint data type to output value of store funds
/// @dev _contractBalance A uint data type to output value of store funds withdrawl
event LogStoreProductsRead(uint _readProductID, string _readProductName, uint _readTotalUnits, uint _readUnitPrice, bool _forSale, uint _buyersAcc);
event LogStoreProductBuy(uint _buyProductID, string _buyProductName, uint _buyTotalUnits, uint _buyUnitPrice);
event LogStoreProductAdded(uint _newProductID, string _newProductName, uint _newTotalUnits, uint _newUnitPrice, bool _forSale, uint _buyersAcc);
event LogStoreProductRemoved(uint _oldProductID, string _oldProductName, uint _oldTotalUnits, uint _oldUnitPrice, bool _forSale, uint _buyersAcc);
event LogStoreProductPriceChanged(uint _changeProductID, string _changeProductName, uint _changeTotalUnits, uint _changeUnitPrice, bool _forSale);
event LogStoreManAdded(uint _newManagerID, string _newManagerName, bool _newManagerAuth, address _newManagerAddress);
event LogStoreManRemoved(uint _oldManagerID, string _oldManagerName, bool _oldManagerAuth, address _oldManagerAddress);
event LogReadStoreFunds(uint _readStoreFunds);
event LogStoreFundsWithdrawn(uint _amountWithdrawn);
/// @dev verifyOwnerMarketplace A modifier requiring the message sender address is equal to the ownerMarketplace address
modifier verifyOwnerMarketplace () {
require (msg.sender == ownerMarketplace, "Access denied. Access restricted to contract owner.");
_;
}
/// @dev verifyManagerMarketplace A modifier requiring the message sender has been authorised as a store manager
modifier verifyManagerMarketplace () {
require (storeMan[msg.sender].managerAuth == true, "Access denied. Access restricted to store managers.");
_;
}
/// @dev verifyProductForSale A modifier requiring the requested store product to be currently registered as for sale.
modifier verifyProductForSale (uint _productID) {
require (storeProd[_productID].forSale == true, "Request declined. Store product is not for sale.");
_;
}
/// @dev verifyManagerAuth A modifier requiring the requested store manager to be currently registered as authorised.
modifier verifyManagerAuth (address _manAddress) {
require (storeMan[_manAddress].managerAuth == true, "Request declined. Store manager is not authorised.");
_;
}
/// @dev verifyWithinPriceCap A modifier requiring product prices to be below a cap of 1,000 Wei. This mitigates risk of money loss
modifier verifyWithinPriceCap (uint _newUnitPrice) {
require (_newUnitPrice <= 1000, "Request declined. Price cap of 1,000 Wei enforced.");
_;
}
/// @dev verifyWithinUnitsCap A modifier requiring total units to be below a cap of 1,000,000. This mitigates risk of integer overflow
modifier verifyWithinUnitsCap (uint _newTotalUnits) {
require (_newTotalUnits <= 1000000, "Request declined. Total units cap of 1,000,000 enforced.");
_;
}
/// @dev verifyUnitsEnough A modifier requiring product units to be in stock prior to purchase
modifier verifyUnitsEnough (uint _productID) {
require (storeProd[_productID].totalUnits >= 1, "Payment declined. Unit out of stock.");
_;
}
/// @dev verifyPaidEnough A modifier requiring buyer payment value to be no less than unit price
modifier verifyPaidEnough (uint _orderPrice) {
require (msg.value >= _orderPrice, "Payment declined. Insufficient funds received.");
_;
}
/// @dev sendPaymentChange A modifier that refunds buyers in the event they send too much ether
modifier sendPaymentChange (uint _orderPrice) {
_;
uint paymentChange = msg.value - _orderPrice;
msg.sender.transfer(paymentChange);
}
/// @dev Declare constructor. Set ownerMarketplace to be the contract creator
constructor () public {
ownerMarketplace = msg.sender;
}
/// @dev readStoreProducts() A function to read store product data
/// @param readProductID A uint data type to read data associated with store product ID
/// @return _xxxProductID, _xxxProductName, _xxxTotalUnits, _xxxUnitPrice, _xxxforSale, _xxxbuyersAcc
function readStoreProducts(uint readProductID)
public
verifyEmergencyStopValue
returns(uint _readProductID, string memory _readProductName, uint _readTotalUnits, uint _readUnitPrice, bool _forSale, uint _buyersAcc)
{
emit LogStoreProductsRead(readProductID, storeProd[readProductID].productName, storeProd[readProductID].totalUnits, storeProd[readProductID].unitPrice, storeProd[readProductID].forSale, storeProd[readProductID].buyersAcc[msg.sender]);
return(readProductID, storeProd[readProductID].productName, storeProd[readProductID].totalUnits, storeProd[readProductID].unitPrice, storeProd[readProductID].forSale, storeProd[readProductID].buyersAcc[msg.sender]);
}
/// @dev buyStoreProduct() A function to buy a store product
/// @param buyProductID A uint data type to buy store product associated with store product ID
/// @return _xxxProductID, _xxxProductName, _xxxTotalUnits, _xxxUnitPrice
function buyStoreProduct(uint buyProductID)
public
payable
verifyEmergencyStopValue
verifyProductForSale (buyProductID)
verifyUnitsEnough (buyProductID)
verifyPaidEnough (storeProd[buyProductID].unitPrice)
sendPaymentChange (storeProd[buyProductID].unitPrice)
returns(uint _buyProductID, string memory _buyProductName, uint _buyTotalUnits, uint _buyUnitPrice)
{
storeProd[buyProductID].totalUnits -= 1;
storeProd[buyProductID].buyersAcc[msg.sender] += 1;
emit LogStoreProductBuy(buyProductID, storeProd[buyProductID].productName, storeProd[buyProductID].totalUnits, storeProd[buyProductID].unitPrice);
return(buyProductID, storeProd[buyProductID].productName, storeProd[buyProductID].totalUnits, storeProd[buyProductID].unitPrice);
}
/// @dev addStoreProduct() A function to add a new store product ***Restricted to store manager (authorised by store owner)***
/// @param newProductName A string data type to add new store product name
/// @param newTotalUnits A uint data type to add new total store product units
/// @param newUnitPrice A uint data type to add new store product unit price
/// @return _xxxProductID, _xxxProductName, _xxxTotalUnits, _xxxUnitPrice, _xxxforSale, _xxxbuyersAcc
function addStoreProduct(string memory newProductName, uint newTotalUnits, uint newUnitPrice)
public
verifyEmergencyStopValue
verifyManagerMarketplace
verifyWithinPriceCap (newUnitPrice)
verifyWithinUnitsCap (newTotalUnits)
returns(uint _productIDGen, string memory _newProductName, uint _newTotalUnits, uint _newUnitPrice, bool _forSale, uint _buyersAcc)
{
storeProd[productIDGen].productName = newProductName;
storeProd[productIDGen].totalUnits = newTotalUnits;
storeProd[productIDGen].unitPrice = newUnitPrice;
storeProd[productIDGen].forSale = true;
productIDGen += 1;
emit LogStoreProductAdded(productIDGen - 1, storeProd[productIDGen - 1].productName, storeProd[productIDGen - 1].totalUnits, storeProd[productIDGen - 1].unitPrice, storeProd[productIDGen - 1].forSale, storeProd[productIDGen - 1].buyersAcc[msg.sender]);
return (productIDGen - 1, storeProd[productIDGen - 1].productName, storeProd[productIDGen - 1].totalUnits, storeProd[productIDGen - 1].unitPrice, storeProd[productIDGen - 1].forSale, storeProd[productIDGen - 1].buyersAcc[msg.sender]);
}
/// @dev removeStoreProduct() A function to remove an old store product ***Restricted to store manager (authorised by store owner)***
/// @param oldProductID A uint data type to remove store product associated with store product ID
/// @return _xxxProductID, _xxxProductName, _xxxTotalUnits, _xxxUnitPrice, _xxxforSale, _xxxbuyersAcc
function removeStoreProduct(uint oldProductID)
public
verifyEmergencyStopValue
verifyManagerMarketplace
verifyProductForSale (oldProductID)
returns(uint _oldProductID, string memory _oldProductName, uint _oldTotalUnits, uint _oldUnitPrice, bool _forSale, uint _buyersAcc)
{
storeProd[oldProductID].forSale = false;
emit LogStoreProductRemoved(oldProductID, storeProd[oldProductID].productName, storeProd[oldProductID].totalUnits, storeProd[oldProductID].unitPrice, storeProd[oldProductID].forSale, storeProd[oldProductID].buyersAcc[msg.sender]);
return (oldProductID, storeProd[oldProductID].productName, storeProd[oldProductID].totalUnits, storeProd[oldProductID].unitPrice, storeProd[oldProductID].forSale, storeProd[oldProductID].buyersAcc[msg.sender]);
}
/// @dev changeStoreProductPrice() A function to change the price of a store product ***Restricted to store manager (authorised by store owner)***
/// @param changeProductID A uint data type to identify the store product to change
/// @param changeUnitPrice A uint data type to state the new price of the store product
/// @return _xxxProductID, _xxxProductName, _xxxTotalUnits, _xxxUnitPrice, _xxxforSale
function changeStoreProductPrice(uint changeProductID, uint changeUnitPrice)
public
verifyEmergencyStopValue
verifyManagerMarketplace
verifyProductForSale (changeProductID)
verifyWithinPriceCap (changeUnitPrice)
returns(uint _changeProductID, string memory _changeProductName, uint _changeTotalUnits, uint _changeUnitPrice, bool _forSale)
{
emit LogStoreProductPriceChanged(changeProductID, storeProd[changeProductID].productName, storeProd[changeProductID].totalUnits, changeUnitPrice, storeProd[changeProductID].forSale);
storeProd[changeProductID].unitPrice = changeUnitPrice;
return (changeProductID, storeProd[changeProductID].productName, storeProd[changeProductID].totalUnits, storeProd[changeProductID].unitPrice, storeProd[changeProductID].forSale);
}
/// @dev addStoreManager() A function to add a new store manager ***Restricted to store owner (contract owner)***
/// @param newManagerName A string data type to add a new store manager name
/// @param newManagerAddress An address data type to add new store manager address
/// @return _xxxManagerID, _xxxManagerName, _xxxManagerAuth, _xxxManagerAddress
function addStoreManager(string memory newManagerName, address newManagerAddress)
public
verifyEmergencyStopValue
verifyOwnerMarketplace
returns(uint _manIDGen, string memory _manName, bool _manAuth, address _manAddress)
{
storeMan[newManagerAddress].managerID = managerIDGen;
storeMan[newManagerAddress].managerName = newManagerName;
storeMan[newManagerAddress].managerAuth = true;
managerIDGen += 1;
emit LogStoreManAdded(storeMan[newManagerAddress].managerID, storeMan[newManagerAddress].managerName, storeMan[newManagerAddress].managerAuth, newManagerAddress);
return (storeMan[newManagerAddress].managerID, storeMan[newManagerAddress].managerName, storeMan[newManagerAddress].managerAuth, newManagerAddress);
}
/// @dev removeStoreManager() A function to remove an old store manager ***Restricted to store owner (contract owner)***
/// @param oldManagerAddress An address data type to identify the store manager to remove
/// @return _xxxManagerID, _xxxManagerName, _xxxManagerAuth, _xxxManagerAddress
function removeStoreManager(address oldManagerAddress)
public
verifyEmergencyStopValue
verifyOwnerMarketplace
verifyManagerAuth (oldManagerAddress)
returns(uint _manIDGen, string memory _manName, bool _manAuth, address _manAddress)
{
storeMan[oldManagerAddress].managerAuth = false;
emit LogStoreManRemoved(storeMan[oldManagerAddress].managerID, storeMan[oldManagerAddress].managerName, storeMan[oldManagerAddress].managerAuth, oldManagerAddress);
return (storeMan[oldManagerAddress].managerID, storeMan[oldManagerAddress].managerName, storeMan[oldManagerAddress].managerAuth, oldManagerAddress);
}
/// @dev readStoreFunds() A function to read store funds. ***Restricted to store owner (contract owner)***
/// @return _storeFunds
function readStoreFunds()
public
verifyOwnerMarketplace
returns(uint _readStoreFunds)
{
uint storeFundsAmount = address(this).balance;
emit LogReadStoreFunds(storeFundsAmount);
return (storeFundsAmount);
}
/// @dev withdrawStoreFunds() A function to withdraw store funds. ***Restricted to store owner (contract owner)***
/// @return _amountWithdrawn
function withdrawStoreFunds()
public
verifyOwnerMarketplace
returns(uint _amountWithdrawn)
{
uint amountWithdrawn = address(this).balance;
emit LogStoreFundsWithdrawn(amountWithdrawn);
ownerMarketplace.transfer(amountWithdrawn);
return (amountWithdrawn);
}
}
|
withdrawStoreFunds() A function to withdraw store funds. Restricted to store owner (contract owner) return _amountWithdrawn
|
function withdrawStoreFunds()
public
verifyOwnerMarketplace
returns(uint _amountWithdrawn)
{
uint amountWithdrawn = address(this).balance;
emit LogStoreFundsWithdrawn(amountWithdrawn);
ownerMarketplace.transfer(amountWithdrawn);
return (amountWithdrawn);
}
| 12,957,481 |
pragma solidity ^0.4.23;
/**
* @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
*/
contract ERC721 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
function implementsERC721() public pure returns (bool);
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;
}
/**
* @title Interface of auction contract
*/
interface CurioAuction {
function isCurioAuction() external returns (bool);
function withdrawBalance() external;
function setAuctionPriceLimit(uint256 _newAuctionPriceLimit) external;
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external;
}
/**
* @title Curio
* @dev Curio core contract implements ERC721 token.
*/
contract Curio is ERC721 {
event Create(
address indexed owner,
uint256 indexed tokenId,
string name
);
event ContractUpgrade(address newContract);
struct Token {
string name;
}
// Name and symbol of ERC721 token
string public constant NAME = "Curio";
string public constant SYMBOL = "CUR";
// Array of token's data
Token[] tokens;
// A mapping from token IDs to the address that owns them
mapping (uint256 => address) public tokenIndexToOwner;
// A mapping from owner address to count of tokens that address owns
mapping (address => uint256) ownershipTokenCount;
// A mapping from token IDs to an address that has been approved
mapping (uint256 => address) public tokenIndexToApproved;
address public ownerAddress;
address public adminAddress;
bool public paused = false;
// The address of new contract when this contract was upgraded
address public newContractAddress;
// The address of CurioAuction contract that handles sales of tokens
CurioAuction public auction;
// Restriction on release of tokens
uint256 public constant TOTAL_SUPPLY_LIMIT = 900;
// Count of released tokens
uint256 public releaseCreatedCount;
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == ownerAddress);
_;
}
/**
* @dev Throws if called by any account other than the admin.
*/
modifier onlyAdmin() {
require(msg.sender == adminAddress);
_;
}
/**
* @dev Throws if called by any account other than the owner or admin.
*/
modifier onlyOwnerOrAdmin() {
require(
msg.sender == adminAddress ||
msg.sender == ownerAddress
);
_;
}
/**
* @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 Constructor function
*/
constructor() public {
// Contract paused after start
paused = true;
// Set owner and admin addresses
ownerAddress = msg.sender;
adminAddress = msg.sender;
}
// -----------------------------------------
// External interface
// -----------------------------------------
/**
* @dev Check implementing ERC721 standard (needed in auction contract).
*/
function implementsERC721() public pure returns (bool) {
return true;
}
/**
* @dev Default payable function rejects all Ether from being sent here, unless it's from auction contract.
*/
function() external payable {
require(msg.sender == address(auction));
}
/**
* @dev Transfer all Ether from this contract to owner.
*/
function withdrawBalance() external onlyOwner {
ownerAddress.transfer(address(this).balance);
}
/**
* @dev Returns the total number of tokens currently in existence.
*/
function totalSupply() public view returns (uint) {
return tokens.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 (uint256 count) {
return ownershipTokenCount[_owner];
}
/**
* @dev Returns the address currently assigned ownership of a given token.
* @param _tokenId The ID of the token
*/
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = tokenIndexToOwner[_tokenId];
require(owner != address(0));
}
/**
* @dev Returns information about token.
* @param _id The ID of the token
*/
function getToken(uint256 _id) external view returns (string name) {
Token storage token = tokens[_id];
name = token.name;
}
/**
* @dev Set new owner address. Only available to the current owner.
* @param _newOwner The address of the new owner
*/
function setOwner(address _newOwner) onlyOwner external {
require(_newOwner != address(0));
ownerAddress = _newOwner;
}
/**
* @dev Set new admin address. Only available to owner.
* @param _newAdmin The address of the new admin
*/
function setAdmin(address _newAdmin) onlyOwner external {
require(_newAdmin != address(0));
adminAddress = _newAdmin;
}
/**
* @dev Set new auction price limit.
* @param _newAuctionPriceLimit Start and end price limit
*/
function setAuctionPriceLimit(uint256 _newAuctionPriceLimit) onlyOwnerOrAdmin external {
auction.setAuctionPriceLimit(_newAuctionPriceLimit);
}
/**
* @dev Set the address of upgraded contract.
* @param _newContract Address of new contract
*/
function setNewAddress(address _newContract) onlyOwner whenPaused external {
newContractAddress = _newContract;
emit ContractUpgrade(_newContract);
}
/**
* @dev Pause the contract. Called by owner or admin to pause the contract.
*/
function pause() onlyOwnerOrAdmin whenNotPaused external {
paused = true;
}
/**
* @dev Unpause the contract. Can only be called by owner, since
* one reason we may pause the contract is when admin account is
* compromised. Requires auction contract addresses
* to be set before contract can be unpaused. Also, we can't have
* newContractAddress set either, because then the contract was upgraded.
*/
function unpause() onlyOwner whenPaused public {
require(auction != address(0));
require(newContractAddress == address(0));
paused = false;
}
/**
* @dev Transfer 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,
uint256 _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.
// The contract should never own any tokens (except very briefly
// after a release token is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contract to prevent accidental
// misuse. Auction contracts should only take ownership of tokens
// through the allow + transferFrom flow.
require(_to != address(auction));
// Check token ownership
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/**
* @dev Grant another address the right to transfer a specific token via
* transferFrom(). This is the preferred flow for transfering NFTs to contracts.
* @param _to The address to be granted transfer approval. Pass address(0) to
* clear all approvals
* @param _tokenId The ID of the token that can be transferred if this call succeeds
*/
function approve(
address _to,
uint256 _tokenId
)
whenNotPaused
external
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
/**
* @dev Transfers a token owned by another address, for which the calling address
* has previously been granted transfer approval by the owner.
* @param _from The address that owns the token to be transferred
* @param _to The address that should take ownership of the token. Can be any address,
* including the caller
* @param _tokenId The ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _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.
// The contract should never own any tokens (except very briefly
// after a release token is created and before it goes on auction).
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);
}
/**
* @dev Returns a list of all tokens assigned to an address.
* @param _owner The owner whose tokens we are interested in
* @notice This method MUST NEVER be called by smart contract code. First, it's fairly
* expensive (it walks the entire token array looking for tokens belonging to owner),
* but it also returns a dynamic array, which is only supported for web3 calls, and
* not contract-to-contract calls.
*/
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalTokens = totalSupply();
uint256 resultIndex = 0;
uint256 tokenId;
for (tokenId = 0; tokenId <= totalTokens; tokenId++) {
if (tokenIndexToOwner[tokenId] == _owner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
/**
* @dev Set the reference to the auction contract.
* @param _address Address of auction contract
*/
function setAuctionAddress(address _address) onlyOwner external {
CurioAuction candidateContract = CurioAuction(_address);
require(candidateContract.isCurioAuction());
// Set the new contract address
auction = candidateContract;
}
/**
* @dev Put a token up for auction.
* @param _tokenId ID of token to auction, sender must be owner
* @param _startingPrice Price of item (in wei) at beginning of auction
* @param _endingPrice Price of item (in wei) at end of auction
* @param _duration Length of auction (in seconds)
*/
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
whenNotPaused
external
{
// Auction contract checks input sizes
// If token is already on any auction, this will throw because it will be owned by the auction contract
require(_owns(msg.sender, _tokenId));
// Set auction contract as approved for token
_approve(_tokenId, auction);
// Sale auction throws if inputs are invalid
auction.createAuction(
_tokenId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/**
* @dev Transfers the balance of the auction contract to this contract by owner or admin.
*/
function withdrawAuctionBalance() onlyOwnerOrAdmin external {
auction.withdrawBalance();
}
/**
* @dev Creates a new release token with the given name and creates an auction for it.
* @param _name Name ot the token
* @param _startingPrice Price of item (in wei) at beginning of auction
* @param _endingPrice Price of item (in wei) at end of auction
* @param _duration Length of auction (in seconds)
*/
function createReleaseTokenAuction(
string _name,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
onlyAdmin
external
{
// Check release tokens limit
require(releaseCreatedCount < TOTAL_SUPPLY_LIMIT);
// Create token and tranfer ownership to this contract
uint256 tokenId = _createToken(_name, address(this));
// Set auction address as approved for release token
_approve(tokenId, auction);
// Call createAuction in auction contract
auction.createAuction(
tokenId,
_startingPrice,
_endingPrice,
_duration,
address(this)
);
releaseCreatedCount++;
}
/**
* @dev Creates free token and transfer it to recipient.
* @param _name Name of the token
* @param _to The address of the recipient, can be a user or contract
*/
function createFreeToken(
string _name,
address _to
)
onlyAdmin
external
{
require(_to != address(0));
require(_to != address(this));
require(_to != address(auction));
// Check release tokens limit
require(releaseCreatedCount < TOTAL_SUPPLY_LIMIT);
// Create token and transfer to owner
_createToken(_name, _to);
releaseCreatedCount++;
}
// -----------------------------------------
// Internal interface
// -----------------------------------------
/**
* @dev Create a new token and stores it.
* @param _name Token name
* @param _owner The initial owner of this token, must be non-zero
*/
function _createToken(
string _name,
address _owner
)
internal
returns (uint)
{
Token memory _token = Token({
name: _name
});
uint256 newTokenId = tokens.push(_token) - 1;
// Check overflow newTokenId
require(newTokenId == uint256(uint32(newTokenId)));
emit Create(_owner, newTokenId, _name);
// This will assign ownership
_transfer(0, _owner, newTokenId);
return newTokenId;
}
/**
* @dev Check claimant address as token owner.
* @param _claimant The address we are validating against
* @param _tokenId Token id, only valid when > 0
*/
function _owns(
address _claimant,
uint256 _tokenId
)
internal
view
returns (bool)
{
return tokenIndexToOwner[_tokenId] == _claimant;
}
/**
* @dev Check if a given address currently has transferApproval for a particular token.
* @param _claimant The address we are confirming token is approved for
* @param _tokenId Token id, only valid when > 0
*/
function _approvedFor(
address _claimant,
uint256 _tokenId
)
internal
view
returns (bool)
{
return tokenIndexToApproved[_tokenId] == _claimant;
}
/**
* @dev Marks an address as being approved for transferFrom().
* Setting _approved to address(0) clears all transfer approval.
* NOTE: _approve() does NOT send the Approval event. This is intentional because
* _approve() and transferFrom() are used together for putting tokens on auction, and
* there is no value in spamming the log with Approval events in that case.
*/
function _approve(
uint256 _tokenId,
address _approved
)
internal
{
tokenIndexToApproved[_tokenId] = _approved;
}
/**
* @dev Assigns ownership of a specific token to an address.
*/
function _transfer(
address _from,
address _to,
uint256 _tokenId
)
internal
{
ownershipTokenCount[_to]++;
// Transfer ownership
tokenIndexToOwner[_tokenId] = _to;
// When creating new token _from is 0x0, but we can't account that address
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// Clear any previously approved ownership exchange
delete tokenIndexToApproved[_tokenId];
}
emit Transfer(_from, _to, _tokenId);
}
}
|
Check claimant address as token owner. _claimant The address we are validating against _tokenId Token id, only valid when > 0/
|
function _owns(
address _claimant,
uint256 _tokenId
)
internal
view
returns (bool)
{
return tokenIndexToOwner[_tokenId] == _claimant;
}
| 5,995,115 |
./full_match/3/0x4388C22BE6667CCE325d0ab6C7869db25d12a6AA/sources/browser/Election.sol
|
require that they haven't voted before require a valid candidate record that voter has voted update candidate vote Count trigger voted event
|
function vote (uint _candidateId) public {
require(!voters[msg.sender]);
require(_candidateId > 0 && _candidateId <= candidatesCount);
voters[msg.sender] = true;
candidates[_candidateId].voteCount ++;
emit votedEvent(_candidateId);
}
| 8,110,917 |
pragma solidity ^0.4.4;
contract Meetup {
/**
* NOTES
*
* "organizer" is the person creating meetup.
*/
/**
* Meetup Events
*/
event _MeetupCreated(uint indexed id);
event _MeetupUpdated(uint indexed id);
struct MeetupPost {
uint id;
address organizer;
string ipfsHash;
}
/**
* meetups map
*
* structure
* meetups[organizer][id] => ipfs hash
*
* example
* meetups[0x123...abc][1] => Qm123...abc
*/
mapping (uint => MeetupPost) meetups;
/**
* Latest sequential meetup ID
*/
uint public seqId = 0;
/**
* Contract owner
*/
address owner;
/**
* Constructor
*/
function Meetup() {
owner = msg.sender;
}
/**
* Change contract owner
*/
function changeOwner(address newOwner) external {
if (msg.sender == owner) {
owner = newOwner;
}
}
/**
* Create a new meetup post
*/
function createMeetup(
string ipfsHash
) external {
address organizer = msg.sender;
seqId = seqId + 1;
meetups[seqId] = MeetupPost(seqId, organizer, ipfsHash);
_MeetupCreated(seqId);
}
/**
* Edit ipfs hash of a post
*/
function editMeetup(
uint id,
string ipfsHash
) external {
address organizer = msg.sender;
MeetupPost storage meetup = meetups[id];
require(meetup.organizer == organizer);
meetups[id].ipfsHash = ipfsHash;
_MeetupUpdated(id);
}
/**
* Retrieve a meetup post by ID
*/
function getMeetup(uint id) external constant returns (uint, address, string) {
MeetupPost storage meetup = meetups[id];
return (meetup.id, meetup.organizer, meetup.ipfsHash);
}
}
|
Create a new meetup post/
|
function createMeetup(
string ipfsHash
) external {
address organizer = msg.sender;
seqId = seqId + 1;
meetups[seqId] = MeetupPost(seqId, organizer, ipfsHash);
_MeetupCreated(seqId);
}
| 1,759,461 |
./partial_match/1/0x020082A7a9c2510e1921116001152DEE4da81985/sources/src/v0.8/ccip/PriceRegistry.sol
|
Add and remove tokens from feeTokens set. feeTokensToAdd The addresses of the tokens which are now considered fee tokens and can be used to calculate fees. feeTokensToRemove The addresses of the tokens which are no longer considered feeTokens.
|
function _applyFeeTokensUpdates(address[] memory feeTokensToAdd, address[] memory feeTokensToRemove) private {
for (uint256 i = 0; i < feeTokensToAdd.length; ++i) {
if (s_feeTokens.add(feeTokensToAdd[i])) {
emit FeeTokenAdded(feeTokensToAdd[i]);
}
}
for (uint256 i = 0; i < feeTokensToRemove.length; ++i) {
if (s_feeTokens.remove(feeTokensToRemove[i])) {
emit FeeTokenRemoved(feeTokensToRemove[i]);
}
}
}
| 3,968,935 |
./partial_match/3/0x2C02cD8a2645D97977E7ffE74Ed21a943ba465E0/sources/option.sol
|
get expiry date from round r/
|
function getRoundExpiryDate(uint r) external override view returns(uint) {
return rounds[r].expiryDate;
}
| 5,241,104 |
pragma solidity ^0.4.11;
import "./Owned.sol";
contract CurrencyHedge is Owned {
struct Hedge {
address beneficiary;
uint hedgeStart; // Seconds in Unix Epoch (since Jan 1, 1970)
uint hedgeEnd; // Seconds in Unix Epoch
bytes3 homeCurr; // Denoted with three letters (e.g. USD, EUR)
bytes3 hedgeCurr;
// Rates will be evaluated up to 5 decimal points, and so must be
// multiplied by 10^5 to be stored as an integer value.
uint64 refRate;
bytes32 instID; // Institution identifier
bytes32 acctID; // ID of account associated with institution
bool active; // Hedge contract state (active or expired?)
}
struct Transaction {
// This struct will eventually need a way to check that the purchase made
// by the client is actually covered by the hedge (e.g. client made the
// purchase in Thailand for a Thai hedge and not in, say, New Zealand)
uint timeStamp; // Seconds in Unix Epoch
uint64 txValue; // Transaction value in home currency
uint64 rateDiff; // Difference between spot exchange rate at time of transaction and hedge's reference rate
}
// Create a global list of all hedges
// NOTE: This implies that hedgeTx will also be public, which it probably shouldn't be
Hedge[] public allHedges;
// Solidity cannot return structs, and can only return arrays of addresses, bools, or uints
mapping (address => uint256[]) private hedgeIndices;
// Reverse mapping of indices to addresses for easy verification
mapping (uint256 => address) private hedgeBeneficiaries;
// Mapping of Hedge indices to arrays of Transactions. This must be used because Solidity does weird
// things when a struct array is nested inside another struct
// Refer to https://ethereum.stackexchange.com/questions/3525/how-to-initialize-empty-struct-array-in-new-struct
mapping (uint256 => Transaction[]) private allTx;
// CurrencyHedge: Contract creator.
function CurrencyHedge() {
owner = msg.sender;
}
// addHedge: Add a new hedge to the book
function addHedge(address _beneficiary, uint _hedgeStart, uint _hedgeEnd, bytes3 _homeCurr,
bytes3 _hedgeCurr, uint64 _refRate, bytes32 _instID, bytes32 _acctID) public onlyOwner {
require(_hedgeEnd - _hedgeStart >= 604800); // Enforce minimum hedge period of 7 days = 604,800 seconds
// Create a new hedge and populate the information.
Hedge memory newHedge = Hedge(_beneficiary, _hedgeStart, _hedgeEnd, _homeCurr, _hedgeCurr, _refRate, _instID, _acctID, false);
// Add the hedge to the global list, and associate the index of the hedge with the beneficiary
allHedges.push(newHedge);
uint newIndex = allHedges.length - 1;
hedgeIndices[_beneficiary].push(newIndex);
hedgeBeneficiaries[newIndex] = _beneficiary;
}
// getHedgeIndices: Retrieve a list of indices of the allHedges array associated with a particular beneficiary's
// Refer to https://ethereum.stackexchange.com/questions/3589/how-can-i-return-an-array-of-struct-from-a-function
function getHedgeIndices(address _beneficiary) public onlyOwner returns (uint256[]) {
return hedgeIndices[_beneficiary];
}
// getNumberOfTx: Retrieve the number of transactions currently associated with a given hedge
function getNumberOfTx(uint _index) public onlyOwner returns (uint) {
return allTx[_index].length;
}
// activateHedge: Activate a hedge and allow transactions to be recorded to it
function activateHedge(address _beneficiary, uint256 _index) public onlyOwner {
require(hedgeBeneficiaries[_index] == _beneficiary); // Check that the specified index and beneficiary are associated
require(!allHedges[_index].active); // Check that the hedge is currently inactive
// This should be verified outside of the contract. 'now' is an alias for
// block.timestamp, not current time
require(allHedges[_index].hedgeEnd < now); // Don't reactivate a dead hedge
require(allHedges[_index].hedgeStart >= now); // Don't prematurely activate a hedge
allHedges[_index].active = true;
}
// deactivateHedge: Deactivate a hedge and prevent any new data from being added
function deactivateHedge(address _beneficiary, uint256 _index) public onlyOwner {
require(hedgeBeneficiaries[_index] == _beneficiary); // Check that the specified index and beneficiary are associated
require(allHedges[_index].active); // Check that the hedge is currently active
// This should be verified outside of the contract. 'now' is an alias for
// block.timestamp, not current time
require(allHedges[_index].hedgeEnd >= now); // Don't prematurely deactivate a hedge
allHedges[_index].active = false;
}
// recordTransaction: Add a transaction record to a particular hedge
function recordTransaction(address _beneficiary, uint256 _index, uint64 _timeStamp, uint64 _txValue,
uint64 _spotRate) public onlyOwner {
require(hedgeBeneficiaries[_index] == _beneficiary); // Check that the specified index and beneficiary are associated
require(allHedges[_index].active); // Check that the hedge is currently inactive
// This should be verified outside of the contract. 'now' is an alias for
// block.timestamp, not current time
require(allHedges[_index].hedgeEnd <= now);
Transaction memory newTx = Transaction(_timeStamp, _txValue, _spotRate - allHedges[_index].refRate);
allTx[_index].push(newTx);
}
// endContract: Close out the hedge and pay whatever is needed to the beneficiary
function endContract(address _beneficiary, uint256 _index) public payable onlyOwner {
require(hedgeBeneficiaries[_index] == _beneficiary); // Check that the specified index and beneficiary are associated
require(!allHedges[_index].active); // Check that the hedge is currently inactive
require(allTx[_index].length > 0); // Check that the list of transactions is greater than zero
// Calculate the value of the payout to the beneficiary
uint totalPayout = 0;
for (uint256 i = 0; i < allTx[_index].length; i++) {
if (allTx[_index][i].rateDiff > 0)
totalPayout += allTx[_index][i].txValue * allTx[_index][i].rateDiff;
}
// Deactivate the hedge
deactivateHedge(_beneficiary, _index);
_beneficiary.transfer(totalPayout);
}
}
|
activateHedge: Activate a hedge and allow transactions to be recorded to it This should be verified outside of the contract. 'now' is an alias for block.timestamp, not current time
|
function activateHedge(address _beneficiary, uint256 _index) public onlyOwner {
allHedges[_index].active = true;
}
| 15,780,871 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// tested components for smartcontracts
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// Creation of the ERC721 contract
contract RuralCity is Context, AccessControlEnumerable, ERC721Enumerable, ERC721URIStorage, Ownable{
using Counters for Counters.Counter;
Counters.Counter public _tokenIdTracker;
string private _baseTokenURI;
uint private _price;
uint private _max;
address _wallet;
bool _openMint;
bool _openWhitelistMint;
mapping(address => bool) private whitelist;
// Different parameters for the contract and what the admin or user could potentially have access too
constructor(string memory name, string memory symbol, string memory baseTokenURI, uint mintPrice, uint max, address wallet, address admin) ERC721(name, symbol) {
_baseTokenURI = baseTokenURI;
_price = mintPrice;
_max = max;
_wallet = wallet;
_openMint = false;
_openWhitelistMint = false;
_setupRole(DEFAULT_ADMIN_ROLE, wallet);
_setupRole(DEFAULT_ADMIN_ROLE, admin);
}
// Metadata server
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
// Metadata server
function setBaseURI(string memory baseURI) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Rural&City: must have admin role to change base URI");
_baseTokenURI = baseURI;
}
function setTokenURI(uint256 tokenId, string memory _tokenURI) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Rural&City: must have admin role to change token URI");
_setTokenURI(tokenId, _tokenURI);
}
// Admin sets price of the NFT
function setPrice(uint mintPrice) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Rural&City: must have admin role to change price");
_price = mintPrice;
}
// Admin sets a bool statement to open or close the mint function on the contract
function setMint(bool openMint, bool openWhitelistMint) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Rural&City: must have admin role to open/close mint");
_openMint = openMint;
_openWhitelistMint = openWhitelistMint;
}
function price() public view returns (uint) {
return _price;
}
// Every mint increases the edition and ID of the ERC721 created
function mint(address[] memory toSend ) public payable onlyOwner{
require(toSend.length <= 2, "Rural&City: max of 2 Rural&City: per mint");
require(_openMint == true, "Rural&City: minting is closed");
require(msg.value == _price*toSend.length, "Rural&City: must send correct price");
require(_tokenIdTracker.current() + toSend.length <= _max, "Rural&City: not enough Rural&City left to be mint amount");
for(uint i = 0; i < toSend.length; i++) {
_mint(toSend[i], _tokenIdTracker.current());
_tokenIdTracker.increment();
}
payable(_wallet).transfer(msg.value);
}
//Addresses allowed to mint early
function mintWhitelist() public payable {
require(_openWhitelistMint == true, "Rural&City: minting is closed");
require(whitelist[msg.sender] == true, "Rural&City: user must be whitelisted to mint");
require(msg.value == _price, "Rural&City: must send correct price");
require(_tokenIdTracker.current() < _max, "Rural&City: all Rural&City photos have been minted");
whitelist[msg.sender] = false;
_mint(msg.sender, _tokenIdTracker.current());
_tokenIdTracker.increment();
payable(_wallet).transfer(msg.value);
}
// Setting if whitelist address will be open or not
function whitelistUser(address user) public {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Rural&City: must have admin role to whitelist address");
whitelist[user] = true;
}
function whitelistStatus(address user) public view returns(bool) {
return whitelist[user];
}
// Delete of ERC721
function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) {
return ERC721URIStorage._burn(tokenId);
}
function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) {
return ERC721URIStorage.tokenURI(tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
}
|
Addresses allowed to mint early
|
function mintWhitelist() public payable {
require(_openWhitelistMint == true, "Rural&City: minting is closed");
require(whitelist[msg.sender] == true, "Rural&City: user must be whitelisted to mint");
require(msg.value == _price, "Rural&City: must send correct price");
require(_tokenIdTracker.current() < _max, "Rural&City: all Rural&City photos have been minted");
whitelist[msg.sender] = false;
_mint(msg.sender, _tokenIdTracker.current());
_tokenIdTracker.increment();
payable(_wallet).transfer(msg.value);
}
| 14,067,666 |
pragma solidity ^0.4.19;
import './Ownable.sol';
import './ERC884ForUser.sol';
contract IshuUser is ERC884ForUser, Ownable {
bytes32 constant private ZERO_BYTES = bytes32(0);
address constant private ZERO_ADDRESS = address(0);
mapping(address => bytes32) private verified;
modifier isVerifiedAddress(address addr) {
require(verified[addr] != ZERO_BYTES);
_;
}
/**
* Add a verified address, along with an associated verification hash to the contract.
* @param addr The address of the person represented by the supplied hash.
* @param hash A cryptographic hash of the address holder's verified information.
*/
function addVerified(address addr, bytes32 hash)
public onlyOwner {
require(addr != ZERO_ADDRESS);
require(hash != ZERO_BYTES);
require(verified[addr] == ZERO_BYTES);
verified[addr] = hash;
emit VerifiedAddressAdded(addr, hash, msg.sender);
}
/**
* Remove a verified address, and the associated verification hash
* @param addr The verified address to be removed.
*/
function removeVerified(address addr)
public onlyOwner {
if (verified[addr] != ZERO_BYTES) {
verified[addr] = ZERO_BYTES;
}
emit VerifiedAddressRemoved(addr, msg.sender);
}
/**
* Update the hash for a verified address known to the contract.
* @param addr The verified address of the person represented by the supplied hash.
* @param hash A new cryptographic hash of the address holder's updated verified information.
*/
function updateVerified(address addr, bytes32 hash)
public onlyOwner isVerifiedAddress(addr) {
require(hash != ZERO_BYTES);
bytes32 oldHash = verified[addr];
if (oldHash != hash) {
verified[addr] = hash;
}
emit VerifiedAddressUpdated(addr, oldHash, hash, msg.sender);
}
/**
* Tests that the supplied address is known to the contract.
* @param addr The address to test.
* @return true if the address is known to the contract.
*/
function isVerified(address addr, bytes32 hash)
public view returns (bool) {
require(verified[addr] != ZERO_BYTES);
return verified[addr] == hash;
}
}
|
Update the hash for a verified address known to the contract. addr The verified address of the person represented by the supplied hash. hash A new cryptographic hash of the address holder's updated verified information./
|
function updateVerified(address addr, bytes32 hash)
public onlyOwner isVerifiedAddress(addr) {
require(hash != ZERO_BYTES);
bytes32 oldHash = verified[addr];
if (oldHash != hash) {
verified[addr] = hash;
}
emit VerifiedAddressUpdated(addr, oldHash, hash, msg.sender);
}
| 6,439,408 |
./partial_match/4/0x9e4Da12D3cC45896fd1E548E2cAbE69d44EecA5D/sources/animalMain.sol
|
TO DO使用亂數來產生DNA, 星級, 動物種類動手玩創意,可以限制每次建立動物需要花費多少ETH
|
function createAnimal() public payable {
bytes32 dna;
uint star;
uint roletype;
dna = random();
uint ram = uint(random())%100;
if ( ram < 40 ) star = 1;
else if ( ram < 65 ) star = 2;
else if ( ram < 85 ) star = 3;
else if ( ram < 95 ) star = 4;
else star = 5;
require( msg.value == 2 wei);
uint id = animals.push(animal(dna, uint8(star), uint8(roletype))) - 1;
animalToOwner[id] = msg.sender;
ownerAnimalCount[msg.sender]++;
}
| 8,727,437 |
/**
*Submitted for verification at Etherscan.io on 2021-04-27
*/
/**
*Submitted for verification at Etherscan.io on 2021-04-13
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT
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;
}
}
/**
* @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));
}
}
/**
* @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);
}
}
}
}
/*
* @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 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());
}
}
}
/**
* @notice Access Controls contract for the Digitalax Platform
* @author BlockRocket.tech
*/
contract DigitalaxAccessControls is AccessControl {
/// @notice Role definitions
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE");
bytes32 public constant VERIFIED_MINTER_ROLE = keccak256("VERIFIED_MINTER_ROLE");
/// @notice Events for adding and removing various roles
event AdminRoleGranted(
address indexed beneficiary,
address indexed caller
);
event AdminRoleRemoved(
address indexed beneficiary,
address indexed caller
);
event MinterRoleGranted(
address indexed beneficiary,
address indexed caller
);
event MinterRoleRemoved(
address indexed beneficiary,
address indexed caller
);
event SmartContractRoleGranted(
address indexed beneficiary,
address indexed caller
);
event SmartContractRoleRemoved(
address indexed beneficiary,
address indexed caller
);
event VerifiedMinterRoleGranted(
address indexed beneficiary,
address indexed caller
);
event VerifiedMinterRoleRemoved(
address indexed beneficiary,
address indexed caller
);
/**
* @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses
*/
constructor() public {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/////////////
// Lookups //
/////////////
/**
* @notice Used to check whether an address has the admin role
* @param _address EOA or contract being checked
* @return bool True if the account has the role or false if it does not
*/
function hasAdminRole(address _address) external view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _address);
}
/**
* @notice Used to check whether an address has the minter role
* @param _address EOA or contract being checked
* @return bool True if the account has the role or false if it does not
*/
function hasMinterRole(address _address) external view returns (bool) {
return hasRole(MINTER_ROLE, _address);
}
/**
* @notice Used to check whether an address has the verified minter role
* @param _address EOA or contract being checked
* @return bool True if the account has the role or false if it does not
*/
function hasVerifiedMinterRole(address _address)
external
view
returns (bool)
{
return hasRole(VERIFIED_MINTER_ROLE, _address);
}
/**
* @notice Used to check whether an address has the smart contract role
* @param _address EOA or contract being checked
* @return bool True if the account has the role or false if it does not
*/
function hasSmartContractRole(address _address) external view returns (bool) {
return hasRole(SMART_CONTRACT_ROLE, _address);
}
///////////////
// Modifiers //
///////////////
/**
* @notice Grants the admin role to an address
* @dev The sender must have the admin role
* @param _address EOA or contract receiving the new role
*/
function addAdminRole(address _address) external {
grantRole(DEFAULT_ADMIN_ROLE, _address);
emit AdminRoleGranted(_address, _msgSender());
}
/**
* @notice Removes the admin role from an address
* @dev The sender must have the admin role
* @param _address EOA or contract affected
*/
function removeAdminRole(address _address) external {
revokeRole(DEFAULT_ADMIN_ROLE, _address);
emit AdminRoleRemoved(_address, _msgSender());
}
/**
* @notice Grants the minter role to an address
* @dev The sender must have the admin role
* @param _address EOA or contract receiving the new role
*/
function addMinterRole(address _address) external {
grantRole(MINTER_ROLE, _address);
emit MinterRoleGranted(_address, _msgSender());
}
/**
* @notice Removes the minter role from an address
* @dev The sender must have the admin role
* @param _address EOA or contract affected
*/
function removeMinterRole(address _address) external {
revokeRole(MINTER_ROLE, _address);
emit MinterRoleRemoved(_address, _msgSender());
}
/**
* @notice Grants the verified minter role to an address
* @dev The sender must have the admin role
* @param _address EOA or contract receiving the new role
*/
function addVerifiedMinterRole(address _address) external {
grantRole(VERIFIED_MINTER_ROLE, _address);
emit VerifiedMinterRoleGranted(_address, _msgSender());
}
/**
* @notice Removes the verified minter role from an address
* @dev The sender must have the admin role
* @param _address EOA or contract affected
*/
function removeVerifiedMinterRole(address _address) external {
revokeRole(VERIFIED_MINTER_ROLE, _address);
emit VerifiedMinterRoleRemoved(_address, _msgSender());
}
/**
* @notice Grants the smart contract role to an address
* @dev The sender must have the admin role
* @param _address EOA or contract receiving the new role
*/
function addSmartContractRole(address _address) external {
grantRole(SMART_CONTRACT_ROLE, _address);
emit SmartContractRoleGranted(_address, _msgSender());
}
/**
* @notice Removes the smart contract role from an address
* @dev The sender must have the admin role
* @param _address EOA or contract affected
*/
function removeSmartContractRole(address _address) external {
revokeRole(SMART_CONTRACT_ROLE, _address);
emit SmartContractRoleRemoved(_address, _msgSender());
}
}
interface IStateSender {
function syncState(address receiver, bytes calldata data) external;
}
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 {
uint256 len;
uint256 memPtr;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item)
internal
pure
returns (RLPItem memory)
{
require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH");
uint256 memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item)
internal
pure
returns (RLPItem[] memory)
{
require(isList(item), "RLPReader: ITEM_NOT_LIST");
uint256 items = numItems(item);
RLPItem[] memory result = new RLPItem[](items);
uint256 listLength = _itemLength(item.memPtr);
require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH");
uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 dataLen;
for (uint256 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) {
uint8 byte0;
uint256 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);
uint256 ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS");
// 1 byte for the length prefix
require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH");
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint256) {
require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT");
require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH");
uint256 itemLength = _itemLength(item.memPtr);
require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH");
uint256 offset = _payloadOffset(item.memPtr);
uint256 len = item.len - offset;
uint256 result;
uint256 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 (uint256) {
uint256 itemLength = _itemLength(item.memPtr);
require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH");
// one byte prefix
require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH");
uint256 result;
uint256 memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
uint256 listLength = _itemLength(item.memPtr);
require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH");
uint256 offset = _payloadOffset(item.memPtr);
uint256 len = item.len - offset; // data length
bytes memory result = new bytes(len);
uint256 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 (uint256) {
// add `isList` check if `item` is expected to be passsed without a check from calling function
// require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST");
uint256 count = 0;
uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH");
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint256 memPtr) private pure returns (uint256) {
uint256 itemLen;
uint256 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(uint256 memPtr) private pure returns (uint256) {
uint256 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(
uint256 src,
uint256 dest,
uint256 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
uint256 mask = 256**(WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
library MerklePatriciaProof {
/*
* @dev Verifies a merkle patricia proof.
* @param value The terminating value in the trie.
* @param encodedPath The path in the trie leading to value.
* @param rlpParentNodes The rlp encoded stack of nodes.
* @param root The root hash of the trie.
* @return The boolean validity of the proof.
*/
function verify(
bytes memory value,
bytes memory encodedPath,
bytes memory rlpParentNodes,
bytes32 root
) internal pure returns (bool) {
RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes);
RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item);
bytes memory currentNode;
RLPReader.RLPItem[] memory currentNodeList;
bytes32 nodeKey = root;
uint256 pathPtr = 0;
bytes memory path = _getNibbleArray(encodedPath);
if (path.length == 0) {
return false;
}
for (uint256 i = 0; i < parentNodes.length; i++) {
if (pathPtr > path.length) {
return false;
}
currentNode = RLPReader.toRlpBytes(parentNodes[i]);
if (nodeKey != keccak256(currentNode)) {
return false;
}
currentNodeList = RLPReader.toList(parentNodes[i]);
if (currentNodeList.length == 17) {
if (pathPtr == path.length) {
if (
keccak256(RLPReader.toBytes(currentNodeList[16])) ==
keccak256(value)
) {
return true;
} else {
return false;
}
}
uint8 nextPathNibble = uint8(path[pathPtr]);
if (nextPathNibble > 16) {
return false;
}
nodeKey = bytes32(
RLPReader.toUintStrict(currentNodeList[nextPathNibble])
);
pathPtr += 1;
} else if (currentNodeList.length == 2) {
uint256 traversed = _nibblesToTraverse(
RLPReader.toBytes(currentNodeList[0]),
path,
pathPtr
);
if (pathPtr + traversed == path.length) {
//leaf node
if (
keccak256(RLPReader.toBytes(currentNodeList[1])) ==
keccak256(value)
) {
return true;
} else {
return false;
}
}
//extension node
if (traversed == 0) {
return false;
}
pathPtr += traversed;
nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1]));
} else {
return false;
}
}
}
function _nibblesToTraverse(
bytes memory encodedPartialPath,
bytes memory path,
uint256 pathPtr
) private pure returns (uint256) {
uint256 len = 0;
// encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath
// and slicedPath have elements that are each one hex character (1 nibble)
bytes memory partialPath = _getNibbleArray(encodedPartialPath);
bytes memory slicedPath = new bytes(partialPath.length);
// pathPtr counts nibbles in path
// partialPath.length is a number of nibbles
for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) {
bytes1 pathNibble = path[i];
slicedPath[i - pathPtr] = pathNibble;
}
if (keccak256(partialPath) == keccak256(slicedPath)) {
len = partialPath.length;
} else {
len = 0;
}
return len;
}
// bytes b must be hp encoded
function _getNibbleArray(bytes memory b)
internal
pure
returns (bytes memory)
{
bytes memory nibbles = "";
if (b.length > 0) {
uint8 offset;
uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b));
if (hpNibble == 1 || hpNibble == 3) {
nibbles = new bytes(b.length * 2 - 1);
bytes1 oddNibble = _getNthNibbleOfBytes(1, b);
nibbles[0] = oddNibble;
offset = 1;
} else {
nibbles = new bytes(b.length * 2 - 2);
offset = 0;
}
for (uint256 i = offset; i < nibbles.length; i++) {
nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b);
}
}
return nibbles;
}
function _getNthNibbleOfBytes(uint256 n, bytes memory str)
private
pure
returns (bytes1)
{
return
bytes1(
n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10
);
}
}
contract ICheckpointManager {
struct HeaderBlock {
bytes32 root;
uint256 start;
uint256 end;
uint256 createdAt;
address proposer;
}
/**
* @notice mapping of checkpoint header numbers to block details
* @dev These checkpoints are submited by plasma contracts
*/
mapping(uint256 => HeaderBlock) public headerBlocks;
}
library Merkle {
function checkMembership(
bytes32 leaf,
uint256 index,
bytes32 rootHash,
bytes memory proof
) internal 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;
}
}
abstract contract BaseRootTunnel {
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
using Merkle for bytes32;
using SafeMath for uint256;
DigitalaxAccessControls public accessControls;
// keccak256(MessageSent(bytes))
bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036;
// state sender contract
IStateSender public stateSender;
// root chain manager
ICheckpointManager public checkpointManager;
// child tunnel contract which receives and sends messages
address public childTunnel;
// storage to avoid duplicate exits
mapping(bytes32 => bool) public processedExits;
constructor(DigitalaxAccessControls _accessControls, address _stateSender) public {
// _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
// _setupContractId("RootTunnel");
accessControls = _accessControls;
stateSender = IStateSender(_stateSender);
}
/**
* @notice Set the state sender, callable only by admins
* @dev This should be the state sender from plasma contracts
* It is used to send bytes from root to child chain
* @param newStateSender address of state sender contract
*/
function setStateSender(address newStateSender)
external
{
require(
accessControls.hasAdminRole(msg.sender),
"BaseRootTunnel.setStateSender: Sender must have the admin role"
);
stateSender = IStateSender(newStateSender);
}
/**
* @notice Set the checkpoint manager, callable only by admins
* @dev This should be the plasma contract responsible for keeping track of checkpoints
* @param newCheckpointManager address of checkpoint manager contract
*/
function setCheckpointManager(address newCheckpointManager)
external
{
require(
accessControls.hasAdminRole(msg.sender),
"BaseRootTunnel.setCheckpointManager: Sender must have the admin role"
);
checkpointManager = ICheckpointManager(newCheckpointManager);
}
/**
* @notice Set the child chain tunnel, callable only by admins
* @dev This should be the contract responsible to receive data bytes on child chain
* @param newChildTunnel address of child tunnel contract
*/
function setChildTunnel(address newChildTunnel)
external
{
require(
accessControls.hasAdminRole(msg.sender),
"BaseRootTunnel.setChildTunnel: Sender must have the admin role"
);
require(newChildTunnel != address(0x0), "RootTunnel: INVALID_CHILD_TUNNEL_ADDRESS");
childTunnel = newChildTunnel;
}
/**
* @notice Send bytes message to Child Tunnel
* @param message bytes message that will be sent to Child Tunnel
* some message examples -
* abi.encode(tokenId);
* abi.encode(tokenId, tokenMetadata);
* abi.encode(messageType, messageData);
*/
function _sendMessageToChild(bytes memory message) internal {
stateSender.syncState(childTunnel, message);
}
function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) {
RLPReader.RLPItem[] memory inputDataRLPList = inputData
.toRlpItem()
.toList();
// checking if exit has already been processed
// unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex)
bytes32 exitHash = keccak256(
abi.encodePacked(
inputDataRLPList[2].toUint(), // blockNumber
// first 2 nibbles are dropped while generating nibble array
// this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only)
// so converting to nibble array and then hashing it
MerklePatriciaProof._getNibbleArray(inputDataRLPList[8].toBytes()), // branchMask
inputDataRLPList[9].toUint() // receiptLogIndex
)
);
require(
processedExits[exitHash] == false,
"RootTunnel: EXIT_ALREADY_PROCESSED"
);
processedExits[exitHash] = true;
RLPReader.RLPItem[] memory receiptRLPList = inputDataRLPList[6]
.toBytes()
.toRlpItem()
.toList();
RLPReader.RLPItem memory logRLP = receiptRLPList[3]
.toList()[
inputDataRLPList[9].toUint() // receiptLogIndex
];
RLPReader.RLPItem[] memory logRLPList = logRLP.toList();
// check child tunnel
require(childTunnel == RLPReader.toAddress(logRLPList[0]), "RootTunnel: INVALID_CHILD_TUNNEL");
// verify receipt inclusion
require(
MerklePatriciaProof.verify(
inputDataRLPList[6].toBytes(), // receipt
inputDataRLPList[8].toBytes(), // branchMask
inputDataRLPList[7].toBytes(), // receiptProof
bytes32(inputDataRLPList[5].toUint()) // receiptRoot
),
"RootTunnel: INVALID_RECEIPT_PROOF"
);
// verify checkpoint inclusion
_checkBlockMembershipInCheckpoint(
inputDataRLPList[2].toUint(), // blockNumber
inputDataRLPList[3].toUint(), // blockTime
bytes32(inputDataRLPList[4].toUint()), // txRoot
bytes32(inputDataRLPList[5].toUint()), // receiptRoot
inputDataRLPList[0].toUint(), // headerNumber
inputDataRLPList[1].toBytes() // blockProof
);
RLPReader.RLPItem[] memory logTopicRLPList = logRLPList[1].toList(); // topics
require(
bytes32(logTopicRLPList[0].toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig
"RootTunnel: INVALID_SIGNATURE"
);
// received message data
bytes memory receivedData = logRLPList[2].toBytes();
(bytes memory message) = abi.decode(receivedData, (bytes)); // event decodes params again, so decoding bytes to get message
return message;
}
function _checkBlockMembershipInCheckpoint(
uint256 blockNumber,
uint256 blockTime,
bytes32 txRoot,
bytes32 receiptRoot,
uint256 headerNumber,
bytes memory blockProof
) private view returns (uint256) {
(
bytes32 headerRoot,
uint256 startBlock,
,
uint256 createdAt,
) = checkpointManager.headerBlocks(headerNumber);
require(
keccak256(
abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)
)
.checkMembership(
blockNumber.sub(startBlock),
headerRoot,
blockProof
),
"RootTunnel: INVALID_HEADER"
);
return createdAt;
}
/**
* @notice receive message from L2 to L1, validated by proof
* @dev This function verifies if the transaction actually happened on child chain
*
* @param inputData RLP encoded data of the reference tx containing following list of fields
* 0 - headerNumber - Checkpoint header block number containing the reference tx
* 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root
* 2 - blockNumber - Block number containing the reference tx on child chain
* 3 - blockTime - Reference tx block time
* 4 - txRoot - Transactions root of block
* 5 - receiptRoot - Receipts root of block
* 6 - receipt - Receipt of the reference transaction
* 7 - receiptProof - Merkle proof of the reference receipt
* 8 - branchMask - 32 bits denoting the path of receipt in merkle tree
* 9 - receiptLogIndex - Log Index to read from the receipt
*/
function receiveMessage(bytes memory inputData) public virtual {
bytes memory message = _validateAndExtractMessage(inputData);
_processMessageFromChild(message);
}
/**
* @notice Process message received from Child Tunnel
* @dev function needs to be implemented to handle message as per requirement
* This is called by onStateReceive function.
* Since it is called via a system call, any event will not be emitted during its execution.
* @param message bytes message that was sent from Child Tunnel
*/
function _processMessageFromChild(bytes memory message) virtual internal;
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @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.
*/
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
constructor() internal {
_registerInterface(
ERC1155Receiver(address(0)).onERC1155Received.selector ^
ERC1155Receiver(address(0)).onERC1155BatchReceived.selector
);
}
}
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// Contract based from the following:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/aaa5ef81cf75454d1c337dc3de03d12480849ad1/contracts/token/ERC1155/ERC1155.sol
/**
*
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*
* @notice Modifications to uri logic made by BlockRocket.tech
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Token ID to its URI
mapping (uint256 => string) internal tokenUris;
// Token ID to its total supply
mapping(uint256 => uint256) public tokenTotalSupply;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
constructor () public {
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*/
function uri(uint256 tokenId) external view override returns (string memory) {
return tokenUris[tokenId];
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address");
batchBalances[i] = _balances[ids[i]][accounts[i]];
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) external virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
external
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
external
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for a given token ID
*/
function _setURI(uint256 tokenId, string memory newuri) internal virtual {
tokenUris[tokenId] = newuri;
emit URI(newuri, tokenId);
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
tokenTotalSupply[id] = tokenTotalSupply[id].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][to] = amount.add(_balances[id][to]);
tokenTotalSupply[id] = tokenTotalSupply[id].add(amount);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
tokenTotalSupply[id] = tokenTotalSupply[id].sub(amount);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
tokenTotalSupply[id] = tokenTotalSupply[id].sub(amount);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// Based on: https://github.com/rocksideio/ERC998-ERC1155-TopDown/blob/695963195606304374015c49d166ab2fbeb42ea9/contracts/IERC998ERC1155TopDown.sol
interface IERC998ERC1155TopDown is IERC1155Receiver {
event ReceivedChild(address indexed from, uint256 indexed toTokenId, address indexed childContract, uint256 childTokenId, uint256 amount);
event TransferBatchChild(uint256 indexed fromTokenId, address indexed to, address indexed childContract, uint256[] childTokenIds, uint256[] amounts);
function childContractsFor(uint256 tokenId) external view returns (address[] memory childContracts);
function childIdsForOn(uint256 tokenId, address childContract) external view returns (uint256[] memory childIds);
function childBalance(uint256 tokenId, address childContract, uint256 childTokenId) external view returns (uint256);
}
/**
* @notice Mock child tunnel contract to receive and send message from L2
*/
abstract contract BaseChildTunnel {
modifier onlyStateSyncer() {
require(
msg.sender == 0x0000000000000000000000000000000000001001,
"Child tunnel: caller is not the state syncer"
);
_;
}
// MessageTunnel on L1 will get data from this event
event MessageSent(bytes message);
/**
* @notice Receive state sync from matic contracts
* @dev This method will be called by Matic chain internally.
* This is executed without transaction using a system call.
*/
function onStateReceive(uint256, bytes memory message) public onlyStateSyncer{
_processMessageFromRoot(message);
}
/**
* @notice Emit message that can be received on Root Tunnel
* @dev Call the internal function when need to emit message
* @param message bytes message that will be sent to Root Tunnel
* some message examples -
* abi.encode(tokenId);
* abi.encode(tokenId, tokenMetadata);
* abi.encode(messageType, messageData);
*/
function _sendMessageToRoot(bytes memory message) internal {
emit MessageSent(message);
}
/**
* @notice Process message received from Root Tunnel
* @dev function needs to be implemented to handle message as per requirement
* This is called by onStateReceive function.
* Since it is called via a system call, any event will not be emitted during its execution.
* @param message bytes message that was sent from Root Tunnel
*/
function _processMessageFromRoot(bytes memory message) virtual internal;
}
/**
* a contract must implement this interface in order to support relayed transaction.
* It is better to inherit the BaseRelayRecipient as its implementation.
*/
abstract contract IRelayRecipient {
/**
* return if the forwarder is trusted to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function isTrustedForwarder(address forwarder) public virtual view returns(bool);
/**
* return the sender of this call.
* if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
* of the msg.data.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function msgSender() internal virtual view returns (address payable);
function versionRecipient() external virtual view returns (string memory);
}
/**
* A base contract to be inherited by any contract that want to receive relayed transactions
* A subclass must use "_msgSender()" instead of "msg.sender"
*/
abstract contract BaseRelayRecipient is IRelayRecipient {
/*
* Forwarder singleton we accept calls from
*/
address public trustedForwarder;
/*
* require a function to be called through GSN only
*/
modifier trustedForwarderOnly() {
require(msg.sender == address(trustedForwarder), "Function can only be called through the trusted Forwarder");
_;
}
function isTrustedForwarder(address forwarder) public override view returns(bool) {
return forwarder == trustedForwarder;
}
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/
function msgSender() internal override view returns (address payable ret) {
if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
assembly {
ret := shr(96,calldataload(sub(calldatasize(),20)))
}
} else {
return msg.sender;
}
}
}
/**
* @title Digitalax Garment NFT a.k.a. parent NFTs
* @dev Issues ERC-721 tokens as well as being able to hold child 1155 tokens
*/
contract DigitalaxGarmentNFT is ERC721("DigitalaxNFT", "DTX"), ERC1155Receiver, IERC998ERC1155TopDown, BaseChildTunnel, BaseRelayRecipient {
// @notice event emitted upon construction of this contract, used to bootstrap external indexers
event DigitalaxGarmentNFTContractDeployed();
// @notice event emitted when token URI is updated
event DigitalaxGarmentTokenUriUpdate(
uint256 indexed _tokenId,
string _tokenUri
);
// @notice event emitted when a tokens primary sale occurs
event TokenPrimarySalePriceSet(
uint256 indexed _tokenId,
uint256 _salePrice
);
event WithdrawnBatch(
address indexed user,
uint256[] tokenIds
);
/// @dev Child ERC1155 contract address
ERC1155 public childContract;
/// @dev current max tokenId
uint256 public tokenIdPointer;
/// @dev TokenID -> Designer address
mapping(uint256 => address) public garmentDesigners;
/// @dev TokenID -> Primary Ether Sale Price in Wei
mapping(uint256 => uint256) public primarySalePrice;
/// @dev ERC721 Token ID -> ERC1155 ID -> Balance
mapping(uint256 => mapping(uint256 => uint256)) private balances;
/// @dev ERC1155 ID -> ERC721 Token IDs that have a balance
mapping(uint256 => EnumerableSet.UintSet) private childToParentMapping;
/// @dev ERC721 Token ID -> ERC1155 child IDs owned by the token ID
mapping(uint256 => EnumerableSet.UintSet) private parentToChildMapping;
/// @dev max children NFTs a single 721 can hold
uint256 public maxChildrenPerToken = 10;
/// @dev limit batching of tokens due to gas limit restrictions
uint256 public constant BATCH_LIMIT = 20;
mapping (uint256 => bool) public withdrawnTokens;
address public childChain;
modifier onlyChildChain() {
require(
_msgSender() == childChain,
"Child token: caller is not the child chain contract"
);
_;
}
/// Required to govern who can call certain functions
DigitalaxAccessControls public accessControls;
/**
@param _accessControls Address of the Digitalax access control contract
@param _childContract ERC1155 the Digitalax child NFT contract
0xb5505a6d998549090530911180f38aC5130101c6
*/
constructor(DigitalaxAccessControls _accessControls, ERC1155 _childContract, address _childChain, address _trustedForwarder) public {
accessControls = _accessControls;
childContract = _childContract;
childChain = _childChain;
trustedForwarder = _trustedForwarder;
emit DigitalaxGarmentNFTContractDeployed();
}
/**
* Override this function.
* This version is to keep track of BaseRelayRecipient you are using
* in your contract.
*/
function versionRecipient() external view override returns (string memory) {
return "1";
}
function setTrustedForwarder(address _trustedForwarder) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxGarmentNFT.setTrustedForwarder: Sender must be admin"
);
trustedForwarder = _trustedForwarder;
}
// This is to support Native meta transactions
// never use msg.sender directly, use _msgSender() instead
function _msgSender()
internal
override
view
returns (address payable sender)
{
return BaseRelayRecipient.msgSender();
}
/**
@notice Mints a DigitalaxGarmentNFT AND when minting to a contract checks if the beneficiary is a 721 compatible
@dev Only senders with either the minter or smart contract role can invoke this method
@param _beneficiary Recipient of the NFT
@param _tokenUri URI for the token being minted
@param _designer Garment designer - will be required for issuing royalties from secondary sales
@return uint256 The token ID of the token that was minted
*/
function mint(address _beneficiary, string calldata _tokenUri, address _designer) external returns (uint256) {
require(
accessControls.hasSmartContractRole(_msgSender()) || accessControls.hasMinterRole(_msgSender()),
"DigitalaxGarmentNFT.mint: Sender must have the minter or contract role"
);
// Valid args
_assertMintingParamsValid(_tokenUri, _designer);
tokenIdPointer = tokenIdPointer.add(1);
uint256 tokenId = tokenIdPointer;
// MATIC guard, to catch tokens minted on chain
require(!withdrawnTokens[tokenId], "ChildMintableERC721: TOKEN_EXISTS_ON_ROOT_CHAIN");
// Mint token and set token URI
_safeMint(_beneficiary, tokenId);
_setTokenURI(tokenId, _tokenUri);
// Associate garment designer
garmentDesigners[tokenId] = _designer;
return tokenId;
}
/**
@notice Burns a DigitalaxGarmentNFT, releasing any composed 1155 tokens held by the token itself
@dev Only the owner or an approved sender can call this method
@param _tokenId the token ID to burn
*/
function burn(uint256 _tokenId) public {
address operator = _msgSender();
require(
ownerOf(_tokenId) == operator || isApproved(_tokenId, operator),
"DigitalaxGarmentNFT.burn: Only garment owner or approved"
);
// If there are any children tokens then send them as part of the burn
if (parentToChildMapping[_tokenId].length() > 0) {
// Transfer children to the burner
_extractAndTransferChildrenFromParent(_tokenId, _msgSender());
}
// Destroy token mappings
_burn(_tokenId);
// Clean up designer mapping
delete garmentDesigners[_tokenId];
delete primarySalePrice[_tokenId];
}
/**
@notice Single ERC1155 receiver callback hook, used to enforce children token binding to a given parent token
*/
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes memory _data)
virtual
external
override
returns (bytes4) {
require(_data.length == 32, "ERC998: data must contain the unique uint256 tokenId to transfer the child token to");
uint256 _receiverTokenId = _extractIncomingTokenId();
_validateReceiverParams(_receiverTokenId, _operator, _from);
_receiveChild(_receiverTokenId, _msgSender(), _id, _amount);
emit ReceivedChild(_from, _receiverTokenId, _msgSender(), _id, _amount);
// Check total tokens do not exceed maximum
require(
parentToChildMapping[_receiverTokenId].length() <= maxChildrenPerToken,
"Cannot exceed max child token allocation"
);
return this.onERC1155Received.selector;
}
/**
@notice Batch ERC1155 receiver callback hook, used to enforce child token bindings to a given parent token ID
*/
function onERC1155BatchReceived(address _operator, address _from, uint256[] memory _ids, uint256[] memory _values, bytes memory _data)
virtual
external
override
returns (bytes4) {
require(_data.length == 32, "ERC998: data must contain the unique uint256 tokenId to transfer the child token to");
uint256 _receiverTokenId = _extractIncomingTokenId();
_validateReceiverParams(_receiverTokenId, _operator, _from);
// Note: be mindful of GAS limits
for (uint256 i = 0; i < _ids.length; i++) {
_receiveChild(_receiverTokenId, _msgSender(), _ids[i], _values[i]);
emit ReceivedChild(_from, _receiverTokenId, _msgSender(), _ids[i], _values[i]);
}
// Check total tokens do not exceed maximum
require(
parentToChildMapping[_receiverTokenId].length() <= maxChildrenPerToken,
"Cannot exceed max child token allocation"
);
return this.onERC1155BatchReceived.selector;
}
function _extractIncomingTokenId() internal pure returns (uint256) {
// Extract out the embedded token ID from the sender
uint256 _receiverTokenId;
uint256 _index = msg.data.length - 32;
assembly {_receiverTokenId := calldataload(_index)}
return _receiverTokenId;
}
function _validateReceiverParams(uint256 _receiverTokenId, address _operator, address _from) internal view {
require(_exists(_receiverTokenId), "Token does not exist");
// We only accept children from the Digitalax child contract
require(_msgSender() == address(childContract), "Invalid child token contract");
// check the sender is the owner of the token or its just been birthed to this token
if (_from != address(0)) {
require(
ownerOf(_receiverTokenId) == _from,
"Cannot add children to tokens you dont own"
);
// Check the operator is also the owner, preventing an approved address adding tokens on the holders behalf
require(_operator == _from, "Operator is not owner");
}
}
//////////
// Admin /
//////////
/**
@notice Updates the token URI of a given token
@dev Only admin or smart contract
@param _tokenId The ID of the token being updated
@param _tokenUri The new URI
*/
function setTokenURI(uint256 _tokenId, string calldata _tokenUri) external {
require(
accessControls.hasSmartContractRole(_msgSender()) || accessControls.hasAdminRole(_msgSender()),
"DigitalaxGarmentNFT.setTokenURI: Sender must be an authorised contract or admin"
);
_setTokenURI(_tokenId, _tokenUri);
emit DigitalaxGarmentTokenUriUpdate(_tokenId, _tokenUri);
}
/**
@notice Records the Ether price that a given token was sold for (in WEI)
@dev Only admin or a smart contract can call this method
@param _tokenId The ID of the token being updated
@param _salePrice The primary Ether sale price in WEI
*/
function setPrimarySalePrice(uint256 _tokenId, uint256 _salePrice) external {
require(
accessControls.hasSmartContractRole(_msgSender()) || accessControls.hasAdminRole(_msgSender()),
"DigitalaxGarmentNFT.setPrimarySalePrice: Sender must be an authorised contract or admin"
);
require(_exists(_tokenId), "DigitalaxGarmentNFT.setPrimarySalePrice: Token does not exist");
require(_salePrice > 0, "DigitalaxGarmentNFT.setPrimarySalePrice: Invalid sale price");
// Only set it once
if (primarySalePrice[_tokenId] == 0) {
primarySalePrice[_tokenId] = _salePrice;
emit TokenPrimarySalePriceSet(_tokenId, _salePrice);
}
}
/**
@notice Method for updating the access controls contract used by the NFT
@dev Only admin
@param _accessControls Address of the new access controls contract
*/
function updateAccessControls(DigitalaxAccessControls _accessControls) external {
require(accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.updateAccessControls: Sender must be admin");
accessControls = _accessControls;
}
/**
@notice Method for updating max children a token can hold
@dev Only admin
@param _maxChildrenPerToken uint256 the max children a token can hold
*/
function updateMaxChildrenPerToken(uint256 _maxChildrenPerToken) external {
require(accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.updateMaxChildrenPerToken: Sender must be admin");
maxChildrenPerToken = _maxChildrenPerToken;
}
/////////////////
// View Methods /
/////////////////
/**
@notice View method for checking whether a token has been minted
@param _tokenId ID of the token being checked
*/
function exists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
/**
@dev Get the child token balances held by the contract, assumes caller knows the correct child contract
*/
function childBalance(uint256 _tokenId, address _childContract, uint256 _childTokenId)
public
view
override
returns (uint256) {
return _childContract == address(childContract) ? balances[_tokenId][_childTokenId] : 0;
}
/**
@dev Get list of supported child contracts, always a list of 0 or 1 in our case
*/
function childContractsFor(uint256 _tokenId) override external view returns (address[] memory) {
if (!_exists(_tokenId)) {
return new address[](0);
}
address[] memory childContracts = new address[](1);
childContracts[0] = address(childContract);
return childContracts;
}
/**
@dev Gets mapped IDs for child tokens
*/
function childIdsForOn(uint256 _tokenId, address _childContract) override public view returns (uint256[] memory) {
if (!_exists(_tokenId) || _childContract != address(childContract)) {
return new uint256[](0);
}
uint256[] memory childTokenIds = new uint256[](parentToChildMapping[_tokenId].length());
for (uint256 i = 0; i < parentToChildMapping[_tokenId].length(); i++) {
childTokenIds[i] = parentToChildMapping[_tokenId].at(i);
}
return childTokenIds;
}
/**
@dev Get total number of children mapped to the token
*/
function totalChildrenMapped(uint256 _tokenId) external view returns (uint256) {
return parentToChildMapping[_tokenId].length();
}
/**
* @dev checks the given token ID is approved either for all or the single token ID
*/
function isApproved(uint256 _tokenId, address _operator) public view returns (bool) {
return isApprovedForAll(ownerOf(_tokenId), _operator) || getApproved(_tokenId) == _operator;
}
/////////////////////////
// Internal and Private /
/////////////////////////
function _extractAndTransferChildrenFromParent(uint256 _fromTokenId, address _to) internal {
uint256[] memory _childTokenIds = childIdsForOn(_fromTokenId, address(childContract));
uint256[] memory _amounts = new uint256[](_childTokenIds.length);
for (uint256 i = 0; i < _childTokenIds.length; ++i) {
uint256 _childTokenId = _childTokenIds[i];
uint256 amount = childBalance(_fromTokenId, address(childContract), _childTokenId);
_amounts[i] = amount;
_removeChild(_fromTokenId, address(childContract), _childTokenId, amount);
}
childContract.safeBatchTransferFrom(address(this), _to, _childTokenIds, _amounts, abi.encodePacked(""));
emit TransferBatchChild(_fromTokenId, _to, address(childContract), _childTokenIds, _amounts);
}
function _receiveChild(uint256 _tokenId, address, uint256 _childTokenId, uint256 _amount) private {
if (balances[_tokenId][_childTokenId] == 0) {
parentToChildMapping[_tokenId].add(_childTokenId);
}
balances[_tokenId][_childTokenId] = balances[_tokenId][_childTokenId].add(_amount);
}
function _removeChild(uint256 _tokenId, address, uint256 _childTokenId, uint256 _amount) private {
require(_amount != 0 || balances[_tokenId][_childTokenId] >= _amount, "ERC998: insufficient child balance for transfer");
balances[_tokenId][_childTokenId] = balances[_tokenId][_childTokenId].sub(_amount);
if (balances[_tokenId][_childTokenId] == 0) {
childToParentMapping[_childTokenId].remove(_tokenId);
parentToChildMapping[_tokenId].remove(_childTokenId);
}
}
/**
@notice Checks that the URI is not empty and the designer is a real address
@param _tokenUri URI supplied on minting
@param _designer Address supplied on minting
*/
function _assertMintingParamsValid(string calldata _tokenUri, address _designer) pure internal {
require(bytes(_tokenUri).length > 0, "DigitalaxGarmentNFT._assertMintingParamsValid: Token URI is empty");
require(_designer != address(0), "DigitalaxGarmentNFT._assertMintingParamsValid: Designer is zero address");
}
/**
* @notice called when token is deposited on root chain
* @dev Should be callable only by ChildChainManager
* Should handle deposit by minting the required tokenId for user
* Make sure minting is done only by this function
* @param user user address for whom deposit is being done
* @param depositData abi encoded tokenId
*/
function deposit(address user, bytes calldata depositData)
external
onlyChildChain
{
// deposit single
if (depositData.length == 32) {
uint256 tokenId = abi.decode(depositData, (uint256));
withdrawnTokens[tokenId] = false;
_safeMint(user, tokenId);
// deposit batch
} else {
uint256[] memory tokenIds = abi.decode(depositData, (uint256[]));
uint256 length = tokenIds.length;
for (uint256 i; i < length; i++) {
withdrawnTokens[tokenIds[i]] = false;
_safeMint(user, tokenIds[i]);
}
}
}
/**
* @notice called when user wants to withdraw token back to root chain
* @dev Should burn user's token. This transaction will be verified when exiting on root chain
* @param tokenId tokenId to withdraw
*/
function withdraw(uint256 tokenId) external {
withdrawnTokens[tokenId] = true;
burn(tokenId);
}
/**
* @notice called when user wants to withdraw multiple tokens back to root chain
* @dev Should burn user's tokens. This transaction will be verified when exiting on root chain
* @param tokenIds tokenId list to withdraw
*/
function withdrawBatch(uint256[] calldata tokenIds) external {
uint256 length = tokenIds.length;
require(length <= BATCH_LIMIT, "ChildERC721: EXCEEDS_BATCH_LIMIT");
for (uint256 i; i < length; i++) {
uint256 tokenId = tokenIds[i];
withdrawnTokens[tokenIds[i]] = true;
burn(tokenId);
}
emit WithdrawnBatch(_msgSender(), tokenIds);
}
function _processMessageFromRoot(bytes memory message) internal override {
uint256 _tokenId;
uint256 _primarySalePrice;
address _garmentDesigner;
string memory _tokenUri;
uint256[] memory _children;
uint256[] memory _childrenBalances;
(_tokenId, _primarySalePrice, _garmentDesigner, _tokenUri, _children, _childrenBalances) = abi.decode(message, (uint256, uint256, address, string, uint256[], uint256[]));
// With the information above, rebuild the 721 token in matic!
primarySalePrice[_tokenId] = _primarySalePrice;
garmentDesigners[_tokenId] = _garmentDesigner;
_setTokenURI(_tokenId, _tokenUri);
for (uint256 i = 0; i< _children.length; i++) {
_receiveChild(_tokenId, _msgSender(), _children[i], _childrenBalances[i]);
}
}
// Send the nft to root - if it does not exist then we can handle it on that side
function sendNFTToRoot(uint256 tokenId) external {
uint256 _primarySalePrice = primarySalePrice[tokenId];
address _garmentDesigner= garmentDesigners[tokenId];
string memory _tokenUri = tokenURI(tokenId);
uint256[] memory _children = childIdsForOn(tokenId, address(childContract));
uint256 len = _children.length;
uint256[] memory childBalances = new uint256[](len);
for( uint256 i; i< _children.length; i++){
childBalances[i] = childBalance(tokenId, address(childContract), _children[i]);
}
_sendMessageToRoot(abi.encode(tokenId, ownerOf(tokenId), _primarySalePrice, _garmentDesigner, _tokenUri, _children, childBalances));
}
}
//imported from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/aaa5ef81cf75454d1c337dc3de03d12480849ad1/contracts/token/ERC1155/ERC1155Burnable.sol
/**
* @dev Extension of {ERC1155} that allows token holders to destroy both their
* own tokens and those that they have been approved to use.
*
* _Available since v3.1._
*/
abstract contract ERC1155Burnable is ERC1155 {
function burn(address account, uint256 id, uint256 amount) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burn(account, id, amount);
}
function burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burnBatch(account, ids, amounts);
}
}
/**
* @title Digitalax Materials NFT a.k.a. child NFTs
* @dev Issues ERC-1155 tokens which can be held by the parent ERC-721 contract
*/
contract DigitalaxMaterials is ERC1155Burnable, BaseRelayRecipient {
// @notice event emitted on contract creation
event DigitalaxMaterialsDeployed();
// @notice a single child has been created
event ChildCreated(
uint256 indexed childId
);
// @notice a batch of children have been created
event ChildrenCreated(
uint256[] childIds
);
string public name;
string public symbol;
// @notice current token ID pointer
uint256 public tokenIdPointer;
// @notice enforcing access controls
DigitalaxAccessControls public accessControls;
address public childChain;
modifier onlyChildChain() {
require(
_msgSender() == childChain,
"Child token: caller is not the child chain contract"
);
_;
}
constructor(
string memory _name,
string memory _symbol,
DigitalaxAccessControls _accessControls,
address _childChain,
address _trustedForwarder
) public {
name = _name;
symbol = _symbol;
accessControls = _accessControls;
trustedForwarder = _trustedForwarder;
childChain = _childChain;
emit DigitalaxMaterialsDeployed();
}
/**
* Override this function.
* This version is to keep track of BaseRelayRecipient you are using
* in your contract.
*/
function versionRecipient() external view override returns (string memory) {
return "1";
}
function setTrustedForwarder(address _trustedForwarder) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMaterials.setTrustedForwarder: Sender must be admin"
);
trustedForwarder = _trustedForwarder;
}
// This is to support Native meta transactions
// never use msg.sender directly, use _msgSender() instead
function _msgSender()
internal
override
view
returns (address payable sender)
{
return BaseRelayRecipient.msgSender();
}
///////////////////////////
// Creating new children //
///////////////////////////
/**
@notice Creates a single child ERC1155 token
@dev Only callable with smart contact role
@return id the generated child Token ID
*/
function createChild(string calldata _uri) external returns (uint256 id) {
require(
accessControls.hasSmartContractRole(_msgSender()),
"DigitalaxMaterials.createChild: Sender must be smart contract"
);
require(bytes(_uri).length > 0, "DigitalaxMaterials.createChild: URI is a blank string");
tokenIdPointer = tokenIdPointer.add(1);
id = tokenIdPointer;
_setURI(id, _uri);
emit ChildCreated(id);
}
/**
@notice Creates a batch of child ERC1155 tokens
@dev Only callable with smart contact role
@return tokenIds the generated child Token IDs
*/
function batchCreateChildren(string[] calldata _uris) external returns (uint256[] memory tokenIds) {
require(
accessControls.hasSmartContractRole(_msgSender()),
"DigitalaxMaterials.batchCreateChildren: Sender must be smart contract"
);
require(_uris.length > 0, "DigitalaxMaterials.batchCreateChildren: No data supplied in array");
uint256 urisLength = _uris.length;
tokenIds = new uint256[](urisLength);
for (uint256 i = 0; i < urisLength; i++) {
string memory uri = _uris[i];
require(bytes(uri).length > 0, "DigitalaxMaterials.batchCreateChildren: URI is a blank string");
tokenIdPointer = tokenIdPointer.add(1);
_setURI(tokenIdPointer, uri);
tokenIds[i] = tokenIdPointer;
}
// Batched event for GAS savings
emit ChildrenCreated(tokenIds);
}
//////////////////////////////////
// Minting of existing children //
//////////////////////////////////
/**
@notice Mints a single child ERC1155 tokens, increasing its supply by the _amount specified. msg.data along with the
parent contract as the recipient can be used to map the created children to a given parent token
@dev Only callable with smart contact role
*/
function mintChild(uint256 _childTokenId, uint256 _amount, address _beneficiary, bytes calldata _data) external {
require(
accessControls.hasSmartContractRole(_msgSender()),
"DigitalaxMaterials.mintChild: Sender must be smart contract"
);
require(bytes(tokenUris[_childTokenId]).length > 0, "DigitalaxMaterials.mintChild: Strand does not exist");
require(_amount > 0, "DigitalaxMaterials.mintChild: No amount specified");
_mint(_beneficiary, _childTokenId, _amount, _data);
}
/**
@notice Mints a batch of child ERC1155 tokens, increasing its supply by the _amounts specified. msg.data along with the
parent contract as the recipient can be used to map the created children to a given parent token
@dev Only callable with smart contact role
*/
function batchMintChildren(
uint256[] calldata _childTokenIds,
uint256[] calldata _amounts,
address _beneficiary,
bytes calldata _data
) external {
require(
accessControls.hasSmartContractRole(_msgSender()),
"DigitalaxMaterials.batchMintChildren: Sender must be smart contract"
);
require(_childTokenIds.length == _amounts.length, "DigitalaxMaterials.batchMintChildren: Array lengths are invalid");
require(_childTokenIds.length > 0, "DigitalaxMaterials.batchMintChildren: No data supplied in arrays");
// Check the strands exist and no zero amounts
for (uint256 i = 0; i < _childTokenIds.length; i++) {
uint256 strandId = _childTokenIds[i];
require(bytes(tokenUris[strandId]).length > 0, "DigitalaxMaterials.batchMintChildren: Strand does not exist");
uint256 amount = _amounts[i];
require(amount > 0, "DigitalaxMaterials.batchMintChildren: Invalid amount");
}
_mintBatch(_beneficiary, _childTokenIds, _amounts, _data);
}
function updateAccessControls(DigitalaxAccessControls _accessControls) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMaterials.updateAccessControls: Sender must be admin"
);
require(
address(_accessControls) != address(0),
"DigitalaxMaterials.updateAccessControls: New access controls cannot be ZERO address"
);
accessControls = _accessControls;
}
/**
* @notice called when tokens are deposited on root chain
* @dev Should be callable only by ChildChainManager
* Should handle deposit by minting the required tokens for user
* Make sure minting is done only by this function
* @param user user address for whom deposit is being done
* @param depositData abi encoded ids array and amounts array
*/
function deposit(address user, bytes calldata depositData)
external
onlyChildChain
{
(
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) = abi.decode(depositData, (uint256[], uint256[], bytes));
require(user != address(0x0), "DigitalaxMaterials: INVALID_DEPOSIT_USER");
_mintBatch(user, ids, amounts, data);
}
/**
* @notice called when user wants to withdraw single token back to root chain
* @dev Should burn user's tokens. This transaction will be verified when exiting on root chain
* @param id id to withdraw
* @param amount amount to withdraw
*/
function withdrawSingle(uint256 id, uint256 amount) external {
_burn(_msgSender(), id, amount);
}
/**
* @notice called when user wants to batch withdraw tokens back to root chain
* @dev Should burn user's tokens. This transaction will be verified when exiting on root chain
* @param ids ids to withdraw
* @param amounts amounts to withdraw
*/
function withdrawBatch(uint256[] calldata ids, uint256[] calldata amounts)
external
{
_burnBatch(_msgSender(), ids, amounts);
}
}
contract DigitalaxRootTunnel is BaseRootTunnel {
DigitalaxGarmentNFT public nft;
DigitalaxMaterials public materials;
/**
@param _accessControls Address of the Digitalax access control contract
*/
constructor(DigitalaxAccessControls _accessControls, DigitalaxGarmentNFT _nft, DigitalaxMaterials _materials, address _stateSender) BaseRootTunnel(_accessControls, _stateSender) public {
nft = _nft;
materials = _materials;
}
function _processMessageFromChild(bytes memory message) internal override {
address[] memory _owners;
uint256[] memory _tokenIds;
uint256[] memory _primarySalePrices;
address[] memory _garmentDesigners;
string[] memory _tokenUris;
uint256[][] memory _children;
string[][] memory _childrenURIs;
uint256[][] memory _childrenBalances;
( _tokenIds, _owners, _primarySalePrices, _garmentDesigners, _tokenUris, _children, _childrenURIs, _childrenBalances) = abi.decode(message, (uint256[], address[], uint256[], address[], string[], uint256[][], string[][], uint256[][]));
for( uint256 i; i< _tokenIds.length; i++){
// With the information above, rebuild the 721 token on mainnet
if(!nft.exists(_tokenIds[i])){
uint256 newTokenId = nft.mint(_owners[i], _tokenUris[i], _garmentDesigners[i]);
if(_primarySalePrices[i] > 0) {
nft.setPrimarySalePrice(newTokenId, _primarySalePrices[i]);
}
if(_children[i].length > 0){
for( uint256 j; j< _children[i].length; j++){
uint256 newChildId = materials.createChild(_childrenURIs[i][j]);
materials.mintChild(newChildId, _childrenBalances[i][j], address(nft), abi.encodePacked(newTokenId));
}
}
}
}
}
// Send the nft to matic
uint256[][] childNftIdArray;
string[][] childNftURIArray;
uint256[][] childNftBalanceArray;
// For children nfts, these should be setup on the matic network before the 721 if there are any
// This should be done before doing a classic matic deposit, that is why anyone can call it for now
function transferNFTsDataToMatic(uint256[] memory _tokenIds) external {
uint256 length = _tokenIds.length;
uint256[] memory _salePrices = new uint256[](length);
address[] memory _designers = new address[](length);
string[] memory _tokenUris = new string[](length);
for( uint256 i; i< _tokenIds.length; i++){
_salePrices[i] = nft.primarySalePrice(_tokenIds[i]);
_designers[i] = nft.garmentDesigners(_tokenIds[i]);
_tokenUris[i] = nft.tokenURI(_tokenIds[i]);
}
_sendMessageToChild(abi.encode(_tokenIds, _salePrices, _designers, _tokenUris));
}
}
|
Receive state sync from matic contracts This method will be called by Matic chain internally. This is executed without transaction using a system call./
|
function onStateReceive(uint256, bytes memory message) public onlyStateSyncer{
_processMessageFromRoot(message);
}
| 520,506 |
./full_match/41/0xB59b7c521223bfB1a9b428ae1117733Cc027Af29/sources/contracts/Smart_Contract.sol
|
Add Payment Add Limiting of Supply
|
function publicMint() public payable{
require(publicMintOpen, "Public Mint Closed");
require(msg.value == 0.01 ether, "Not Enough Funds");
require(totalSupply() < maxSupply, "Sold Out!");
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenId);
}
| 16,380,038 |
./full_match/137/0xD12345Cd15352ef5d4259BD2a918Fcb6943ce7a4/sources/contracts/core/connext/helpers/StableSwap.sol
|
Return A, the amplification coefficient n (n - 1) See the StableSwap paper for details return A parameter/
|
function getA() external view override returns (uint256) {
return swapStorage.getA();
}
| 4,729,521 |
./full_match/43114/0x46655CE994041664163489B278CF0eE576322118/sources/project_/contracts/MasterChef.sol
|
Update reward variables of the given pool to be up-to-date. Dev does not take any emission Accounts for Total Supply together with rewards
|
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTime) {
return;
}
if (pool.lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardTime = block.timestamp;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
uint256 meltReward = multiplier.mul(meltPerSecond).mul(pool.allocPoint).div(totalAllocPoint);
if(melt.totalSupply().add(meltReward) <= MAX_SUPPLY) {
melt.mint(address(this), meltReward);
melt.mint(address(this), MAX_SUPPLY.sub(melt.totalSupply()));
}
pool.accMeltPerShare = pool.accMeltPerShare.add(meltReward.mul(1e18).div(pool.lpSupply));
pool.lastRewardTime = block.timestamp;
}
| 4,559,559 |
./full_match/97/0xFa65FeB730Bc85214eB4e7C07e4810ca8381A5aE/sources/project_/contracts/LakeToken.sol
|
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "LAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 3,284,442 |
pragma solidity ^0.4.24;
import "@aragon/os/contracts/apps/AragonApp.sol";
import "@aragon/os/contracts/lib/math/SafeMath.sol";
import "./interfaces/IVICoinAdjustable.sol";
import "@nomiclabs/buidler/console.sol";
contract VCommunityApp is AragonApp {
using SafeMath for uint256;
/// Events
event SetVICoinAddress(address _viCoinAddress);
event UnapproveAccount(address _account);
event VerifyAccount(address _account);
event Updatelifetime(uint256 _lifetime);
event UpdateInitialBalance(uint256 _initialBalance);
event UpdateGenerationPeriod(uint256 _generationPeriod);
event UpdateController(address _controller);
event UpdateGenerationAmount(uint256 _generationAmount);
event BlowFuse(uint256 _fuseID, bool _confirm);
event BlowAllFuses(bool _confirm);
event ChangeCommunityContributionAccount(
address _newCommunityContributionAccount
);
event UpdateCommunityContribution(uint256 _communityContribution);
event UpdateTransactionFee(uint256 _transactionFee);
/// State
IVICoinAdjustable public viCoin;
string public name;
/// ACL
bytes32 public constant SETCOINADDRESS = keccak256("SETCOINADDRESS");
bytes32 public constant UNAPPROVEACCOUNT = keccak256("UNAPPROVEACCOUNT");
bytes32 public constant VERIFYACCOUNT = keccak256("VERIFYACCOUNT");
bytes32 public constant UPDATELIFETIME = keccak256("UPDATELIFETIME");
bytes32 public constant UPDATEINITIALBALANCE = keccak256(
"UPDATEINITIALBALANCE"
);
bytes32 public constant UPDATEGENERATIONPERIOD = keccak256(
"UPDATEGENERATIONPERIOD"
);
bytes32 public constant UPDATECONTROLLER = keccak256("UPDATECONTROLLER");
bytes32 public constant UPDATEGENERATIONAMOUNT = keccak256(
"UPDATEGENERATIONAMOUNT"
);
bytes32 public constant BLOWFUSE = keccak256("BLOWFUSE");
bytes32 public constant UPDATECOMMUNITYCONTRIBUTIONACCOUNT = keccak256(
"UPDATECOMMUNITYCONTRIBUTIONACCOUNT"
);
bytes32 public constant UPDATECOMMUNITYCONTRIBUTION = keccak256(
"UPDATECOMMUNITYCONTRIBUTION"
);
bytes32 public constant UPDATETRANSACTIONFEE = keccak256(
"UPDATETRANSACTIONFEE"
);
bytes32 public constant UPDATENAME = keccak256("UPDATENAME");
bytes32 public constant UPDATESYMBOL = keccak256("UPDATESYMBOL");
bytes32 public constant TERMINATE = keccak256("TERMINATE");
function initialize(address _viCoinAddress, string memory _name)
public
onlyInit
{
if (_viCoinAddress != address(0)) {
viCoin = IVICoinAdjustable(_viCoinAddress);
}
name = _name;
initialized();
}
/**
* @notice Set the address of the Value Instrument currency governed by this DAO to `_viCoinAddress`
*
*/
function setVICoinAddress(address _viCoinAddress)
external
auth(SETCOINADDRESS)
{
viCoin = IVICoinAdjustable(_viCoinAddress);
emit SetVICoinAddress(_viCoinAddress);
}
/**
* @notice Unapprove account `_account` so that it no logner receives basic income
*
*/
function unapproveAccount(address _account)
external
auth(UNAPPROVEACCOUNT)
{
viCoin.unapproveAccount(_account);
emit UnapproveAccount(_account);
}
/**
* @notice Verify account `_account` for the first time, so that it receives an initial balance and basic income
*
*/
function verifyAccount(address _account) external auth(VERIFYACCOUNT) {
console.log("About to verify account");
viCoin.verifyAccount(_account);
emit VerifyAccount(_account);
}
function updateLifetime(uint256 _lifetime) external auth(UPDATELIFETIME) {
viCoin.updateLifetime(_lifetime);
emit Updatelifetime(_lifetime);
}
function updateInitialBalance(uint256 _initialBalance)
external
auth(UPDATEINITIALBALANCE)
{
viCoin.updateInitialBalance(_initialBalance);
emit UpdateInitialBalance(_initialBalance);
}
function updateGenerationPeriod(uint256 _generationPeriod)
external
auth(UPDATEGENERATIONPERIOD)
{
viCoin.updateGenerationPeriod(_generationPeriod);
emit UpdateGenerationPeriod(_generationPeriod);
}
function updateGenerationAmount(uint256 _generationAmount)
external
auth(UPDATEGENERATIONAMOUNT)
{
viCoin.updateGenerationAmount(_generationAmount);
emit UpdateGenerationAmount(_generationAmount);
}
/**
* @notice Change the controller address of the currency to `controller`
*
*/
function updateController(address _controller)
external
auth(UPDATECONTROLLER)
{
viCoin.updateController(_controller);
emit UpdateController(_controller);
}
function blowFuse(uint256 _fuseID, bool _confirm) external auth(BLOWFUSE) {
viCoin.blowFuse(_fuseID, _confirm);
emit BlowFuse(_fuseID, _confirm);
}
function blowAllFuses(bool _confirm) external auth(BLOWFUSE) {
viCoin.blowAllFuses(_confirm);
emit BlowAllFuses(_confirm);
}
function updateCommunityContributionAccount(
address _newCommunityContributionAccount
) external auth(UPDATECOMMUNITYCONTRIBUTIONACCOUNT) {
viCoin.updateCommunityContributionAccount(
_newCommunityContributionAccount
);
emit ChangeCommunityContributionAccount(
_newCommunityContributionAccount
);
}
function updateCommunityContribution(uint256 _communityContribution)
external
auth(UPDATECOMMUNITYCONTRIBUTION)
{
viCoin.updateCommunityContribution(_communityContribution);
emit UpdateCommunityContribution(_communityContribution);
}
function updateTransactionFee(uint256 _transactionFee)
external
auth(UPDATETRANSACTIONFEE)
{
viCoin.updateTransactionFee(_transactionFee);
emit UpdateTransactionFee(_transactionFee);
}
function updateName(string _name) external auth(UPDATENAME) {
viCoin.updateName(_name);
}
function updateSymbol(string _symbol) external auth(UPDATESYMBOL) {
viCoin.updateSymbol(_symbol);
}
function totalSupply() external returns (uint256) {
return viCoin.totalSupply();
}
function liveBalanceOf(address _account) external returns (uint256) {
return viCoin.liveBalanceOf(_account);
}
function balanceOf(address _account) external returns (uint256) {
return viCoin.balanceOf(_account);
}
function triggerOnchainBalanceUpdate(address _account)
external
returns (uint256)
{
return viCoin.triggerOnchainBalanceUpdate(_account);
}
// function terminateCurrency(bool _confirm, address _recoverFunds)
// external
// auth(TERMINATE)
// {
// viCoin.terminateCurrency(_confirm, _recoverFunds);
// }
function terminateAragonApp(bool _confirm, address _recoverFunds)
external
auth(TERMINATE)
{
require(
_confirm == true,
"Please confirm you want to destroy this contract"
);
selfdestruct(_recoverFunds);
}
function getTransactionFee() external returns (uint256) {
return viCoin.getTransactionFee();
}
function getCommunityContribution() external returns (uint256) {
return viCoin.getCommunityContribution();
}
}
|
Unapprove account `_account` so that it no logner receives basic income/
|
function unapproveAccount(address _account)
external
auth(UNAPPROVEACCOUNT)
{
viCoin.unapproveAccount(_account);
emit UnapproveAccount(_account);
}
| 12,656,060 |
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Owned contract with safe ownership pass.
*
* Note: all the non constant functions return false instead of throwing in case if state change
* didn't happen yet.
*/
contract Owned {
/**
* Contract owner address
*/
address public contractOwner;
/**
* Contract owner address
*/
address public pendingContractOwner;
function Owned() {
contractOwner = msg.sender;
}
/**
* @dev Owner check modifier
*/
modifier onlyContractOwner() {
if (contractOwner == msg.sender) {
_;
}
}
/**
* @dev Destroy contract and scrub a data
* @notice Only owner can call it
*/
function destroy() onlyContractOwner {
suicide(msg.sender);
}
/**
* Prepares ownership pass.
*
* Can only be called by current owner.
*
* @param _to address of the next owner. 0x0 is not allowed.
*
* @return success.
*/
function changeContractOwnership(address _to) onlyContractOwner() returns(bool) {
if (_to == 0x0) {
return false;
}
pendingContractOwner = _to;
return true;
}
/**
* Finalize ownership pass.
*
* Can only be called by pending owner.
*
* @return success.
*/
function claimContractOwnership() returns(bool) {
if (pendingContractOwner != msg.sender) {
return false;
}
contractOwner = pendingContractOwner;
delete pendingContractOwner;
return true;
}
}
contract ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
/**
* @title Generic owned destroyable contract
*/
contract Object is Owned {
/**
* Common result code. Means everything is fine.
*/
uint constant OK = 1;
uint constant OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER = 8;
function withdrawnTokens(address[] tokens, address _to) onlyContractOwner returns(uint) {
for(uint i=0;i<tokens.length;i++) {
address token = tokens[i];
uint balance = ERC20Interface(token).balanceOf(this);
if(balance != 0)
ERC20Interface(token).transfer(_to,balance);
}
return OK;
}
function checkOnlyContractOwner() internal constant returns(uint) {
if (contractOwner == msg.sender) {
return OK;
}
return OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER;
}
}
contract OracleMethodAdapter is Object {
event OracleAdded(bytes4 _sig, address _oracle);
event OracleRemoved(bytes4 _sig, address _oracle);
mapping(bytes4 => mapping(address => bool)) public oracles;
/// @dev Allow access only for oracle
modifier onlyOracle {
if (oracles[msg.sig][msg.sender]) {
_;
}
}
modifier onlyOracleOrOwner {
if (oracles[msg.sig][msg.sender] || msg.sender == contractOwner) {
_;
}
}
function addOracles(bytes4[] _signatures, address[] _oracles) onlyContractOwner external returns (uint) {
require(_signatures.length == _oracles.length);
bytes4 _sig;
address _oracle;
for (uint _idx = 0; _idx < _signatures.length; ++_idx) {
(_sig, _oracle) = (_signatures[_idx], _oracles[_idx]);
if (!oracles[_sig][_oracle]) {
oracles[_sig][_oracle] = true;
_emitOracleAdded(_sig, _oracle);
}
}
return OK;
}
function removeOracles(bytes4[] _signatures, address[] _oracles) onlyContractOwner external returns (uint) {
require(_signatures.length == _oracles.length);
bytes4 _sig;
address _oracle;
for (uint _idx = 0; _idx < _signatures.length; ++_idx) {
(_sig, _oracle) = (_signatures[_idx], _oracles[_idx]);
if (oracles[_sig][_oracle]) {
delete oracles[_sig][_oracle];
_emitOracleRemoved(_sig, _oracle);
}
}
return OK;
}
function _emitOracleAdded(bytes4 _sig, address _oracle) internal {
OracleAdded(_sig, _oracle);
}
function _emitOracleRemoved(bytes4 _sig, address _oracle) internal {
OracleRemoved(_sig, _oracle);
}
}
/// @title Provides possibility manage holders? country limits and limits for holders.
contract DataControllerInterface {
/// @notice Checks user is holder.
/// @param _address - checking address.
/// @return `true` if _address is registered holder, `false` otherwise.
function isHolderAddress(address _address) public view returns (bool);
function allowance(address _user) public view returns (uint);
function changeAllowance(address _holder, uint _value) public returns (uint);
}
/// @title ServiceController
///
/// Base implementation
/// Serves for managing service instances
contract ServiceControllerInterface {
/// @notice Check target address is service
/// @param _address target address
/// @return `true` when an address is a service, `false` otherwise
function isService(address _address) public view returns (bool);
}
contract ATxAssetInterface {
DataControllerInterface public dataController;
ServiceControllerInterface public serviceController;
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool);
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool);
function __approve(address _spender, uint _value, address _sender) public returns (bool);
function __process(bytes /*_data*/, address /*_sender*/) payable public {
revert();
}
}
/// @title ServiceAllowance.
///
/// Provides a way to delegate operation allowance decision to a service contract
contract ServiceAllowance {
function isTransferAllowed(address _from, address _to, address _sender, address _token, uint _value) public view returns (bool);
}
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
contract Platform {
mapping(bytes32 => address) public proxies;
function name(bytes32 _symbol) public view returns (string);
function setProxy(address _address, bytes32 _symbol) public returns (uint errorCode);
function isOwner(address _owner, bytes32 _symbol) public view returns (bool);
function totalSupply(bytes32 _symbol) public view returns (uint);
function balanceOf(address _holder, bytes32 _symbol) public view returns (uint);
function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint);
function baseUnit(bytes32 _symbol) public view returns (uint8);
function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode);
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode);
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns (uint errorCode);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) public returns (uint errorCode);
function reissueAsset(bytes32 _symbol, uint _value) public returns (uint errorCode);
function revokeAsset(bytes32 _symbol, uint _value) public returns (uint errorCode);
function isReissuable(bytes32 _symbol) public view returns (bool);
function changeOwnership(bytes32 _symbol, address _newOwner) public returns (uint errorCode);
}
contract ATxAssetProxy is ERC20, Object, ServiceAllowance {
// Timespan for users to review the new implementation and make decision.
uint constant UPGRADE_FREEZE_TIME = 3 days;
using SafeMath for uint;
/**
* Indicates an upgrade freeze-time start, and the next asset implementation contract.
*/
event UpgradeProposal(address newVersion);
// Current asset implementation contract address.
address latestVersion;
// Proposed next asset implementation contract address.
address pendingVersion;
// Upgrade freeze-time start.
uint pendingVersionTimestamp;
// Assigned platform, immutable.
Platform public platform;
// Assigned symbol, immutable.
bytes32 public smbl;
// Assigned name, immutable.
string public name;
/**
* Only platform is allowed to call.
*/
modifier onlyPlatform() {
if (msg.sender == address(platform)) {
_;
}
}
/**
* Only current asset owner is allowed to call.
*/
modifier onlyAssetOwner() {
if (platform.isOwner(msg.sender, smbl)) {
_;
}
}
/**
* Only asset implementation contract assigned to sender is allowed to call.
*/
modifier onlyAccess(address _sender) {
if (getLatestVersion() == msg.sender) {
_;
}
}
/**
* Resolves asset implementation contract for the caller and forwards there transaction data,
* along with the value. This allows for proxy interface growth.
*/
function() public payable {
_getAsset().__process.value(msg.value)(msg.data, msg.sender);
}
/**
* Sets platform address, assigns symbol and name.
*
* Can be set only once.
*
* @param _platform platform contract address.
* @param _symbol assigned symbol.
* @param _name assigned name.
*
* @return success.
*/
function init(Platform _platform, string _symbol, string _name) public returns (bool) {
if (address(platform) != 0x0) {
return false;
}
platform = _platform;
symbol = _symbol;
smbl = stringToBytes32(_symbol);
name = _name;
return true;
}
/**
* Returns asset total supply.
*
* @return asset total supply.
*/
function totalSupply() public view returns (uint) {
return platform.totalSupply(smbl);
}
/**
* Returns asset balance for a particular holder.
*
* @param _owner holder address.
*
* @return holder balance.
*/
function balanceOf(address _owner) public view returns (uint) {
return platform.balanceOf(_owner, smbl);
}
/**
* Returns asset allowance from one holder to another.
*
* @param _from holder that allowed spending.
* @param _spender holder that is allowed to spend.
*
* @return holder to spender allowance.
*/
function allowance(address _from, address _spender) public view returns (uint) {
return platform.allowance(_from, _spender, smbl);
}
/**
* Returns asset decimals.
*
* @return asset decimals.
*/
function decimals() public view returns (uint8) {
return platform.baseUnit(smbl);
}
/**
* Transfers asset balance from the caller to specified receiver.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transfer(address _to, uint _value) public returns (bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, "");
}
else {
return false;
}
}
/**
* Transfers asset balance from the caller to specified receiver adding specified comment.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
*
* @return success.
*/
function transferWithReference(address _to, uint _value, string _reference) public returns (bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, _reference);
}
else {
return false;
}
}
/**
* Performs transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK;
}
/**
* Prforms allowance transfer of asset balance between holders.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
if (_to != 0x0) {
return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK;
}
/**
* Sets asset spending allowance for a specified spender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
*
* @return success.
*/
function approve(address _spender, uint _value) public returns (bool) {
if (_spender != 0x0) {
return _getAsset().__approve(_spender, _value, msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance setting call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
* @param _sender initial caller.
*
* @return success.
*/
function __approve(address _spender, uint _value, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyApprove(_spender, _value, smbl, _sender) == OK;
}
/**
* Emits ERC20 Transfer event on this contract.
*
* Can only be, and, called by assigned platform when asset transfer happens.
*/
function emitTransfer(address _from, address _to, uint _value) public onlyPlatform() {
Transfer(_from, _to, _value);
}
/**
* Emits ERC20 Approval event on this contract.
*
* Can only be, and, called by assigned platform when asset allowance set happens.
*/
function emitApprove(address _from, address _spender, uint _value) public onlyPlatform() {
Approval(_from, _spender, _value);
}
/**
* Returns current asset implementation contract address.
*
* @return asset implementation contract address.
*/
function getLatestVersion() public view returns (address) {
return latestVersion;
}
/**
* Returns proposed next asset implementation contract address.
*
* @return asset implementation contract address.
*/
function getPendingVersion() public view returns (address) {
return pendingVersion;
}
/**
* Returns upgrade freeze-time start.
*
* @return freeze-time start.
*/
function getPendingVersionTimestamp() public view returns (uint) {
return pendingVersionTimestamp;
}
/**
* Propose next asset implementation contract address.
*
* Can only be called by current asset owner.
*
* Note: freeze-time should not be applied for the initial setup.
*
* @param _newVersion asset implementation contract address.
*
* @return success.
*/
function proposeUpgrade(address _newVersion) public onlyAssetOwner returns (bool) {
// Should not already be in the upgrading process.
if (pendingVersion != 0x0) {
return false;
}
// New version address should be other than 0x0.
if (_newVersion == 0x0) {
return false;
}
// Don't apply freeze-time for the initial setup.
if (latestVersion == 0x0) {
latestVersion = _newVersion;
return true;
}
pendingVersion = _newVersion;
pendingVersionTimestamp = now;
UpgradeProposal(_newVersion);
return true;
}
/**
* Cancel the pending upgrade process.
*
* Can only be called by current asset owner.
*
* @return success.
*/
function purgeUpgrade() public onlyAssetOwner returns (bool) {
if (pendingVersion == 0x0) {
return false;
}
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
/**
* Finalize an upgrade process setting new asset implementation contract address.
*
* Can only be called after an upgrade freeze-time.
*
* @return success.
*/
function commitUpgrade() public returns (bool) {
if (pendingVersion == 0x0) {
return false;
}
if (pendingVersionTimestamp.add(UPGRADE_FREEZE_TIME) > now) {
return false;
}
latestVersion = pendingVersion;
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
function isTransferAllowed(address, address, address, address, uint) public view returns (bool) {
return true;
}
/**
* Returns asset implementation contract for current caller.
*
* @return asset implementation contract.
*/
function _getAsset() internal view returns (ATxAssetInterface) {
return ATxAssetInterface(getLatestVersion());
}
/**
* Resolves asset implementation contract for the caller and forwards there arguments along with
* the caller address.
*
* @return success.
*/
function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) {
return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender);
}
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
}
contract DataControllerEmitter {
event CountryCodeAdded(uint _countryCode, uint _countryId, uint _maxHolderCount);
event CountryCodeChanged(uint _countryCode, uint _countryId, uint _maxHolderCount);
event HolderRegistered(bytes32 _externalHolderId, uint _accessIndex, uint _countryCode);
event HolderAddressAdded(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex);
event HolderAddressRemoved(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex);
event HolderOperationalChanged(bytes32 _externalHolderId, bool _operational);
event DayLimitChanged(bytes32 _externalHolderId, uint _from, uint _to);
event MonthLimitChanged(bytes32 _externalHolderId, uint _from, uint _to);
event Error(uint _errorCode);
function _emitHolderAddressAdded(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex) internal {
HolderAddressAdded(_externalHolderId, _holderPrototype, _accessIndex);
}
function _emitHolderAddressRemoved(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex) internal {
HolderAddressRemoved(_externalHolderId, _holderPrototype, _accessIndex);
}
function _emitHolderRegistered(bytes32 _externalHolderId, uint _accessIndex, uint _countryCode) internal {
HolderRegistered(_externalHolderId, _accessIndex, _countryCode);
}
function _emitHolderOperationalChanged(bytes32 _externalHolderId, bool _operational) internal {
HolderOperationalChanged(_externalHolderId, _operational);
}
function _emitCountryCodeAdded(uint _countryCode, uint _countryId, uint _maxHolderCount) internal {
CountryCodeAdded(_countryCode, _countryId, _maxHolderCount);
}
function _emitCountryCodeChanged(uint _countryCode, uint _countryId, uint _maxHolderCount) internal {
CountryCodeChanged(_countryCode, _countryId, _maxHolderCount);
}
function _emitDayLimitChanged(bytes32 _externalHolderId, uint _from, uint _to) internal {
DayLimitChanged(_externalHolderId, _from, _to);
}
function _emitMonthLimitChanged(bytes32 _externalHolderId, uint _from, uint _to) internal {
MonthLimitChanged(_externalHolderId, _from, _to);
}
function _emitError(uint _errorCode) internal returns (uint) {
Error(_errorCode);
return _errorCode;
}
}
contract GroupsAccessManagerEmitter {
event UserCreated(address user);
event UserDeleted(address user);
event GroupCreated(bytes32 groupName);
event GroupActivated(bytes32 groupName);
event GroupDeactivated(bytes32 groupName);
event UserToGroupAdded(address user, bytes32 groupName);
event UserFromGroupRemoved(address user, bytes32 groupName);
}
/// @title Group Access Manager
///
/// Base implementation
/// This contract serves as group manager
contract GroupsAccessManager is Object, GroupsAccessManagerEmitter {
uint constant USER_MANAGER_SCOPE = 111000;
uint constant USER_MANAGER_MEMBER_ALREADY_EXIST = USER_MANAGER_SCOPE + 1;
uint constant USER_MANAGER_GROUP_ALREADY_EXIST = USER_MANAGER_SCOPE + 2;
uint constant USER_MANAGER_OBJECT_ALREADY_SECURED = USER_MANAGER_SCOPE + 3;
uint constant USER_MANAGER_CONFIRMATION_HAS_COMPLETED = USER_MANAGER_SCOPE + 4;
uint constant USER_MANAGER_USER_HAS_CONFIRMED = USER_MANAGER_SCOPE + 5;
uint constant USER_MANAGER_NOT_ENOUGH_GAS = USER_MANAGER_SCOPE + 6;
uint constant USER_MANAGER_INVALID_INVOCATION = USER_MANAGER_SCOPE + 7;
uint constant USER_MANAGER_DONE = USER_MANAGER_SCOPE + 11;
uint constant USER_MANAGER_CANCELLED = USER_MANAGER_SCOPE + 12;
using SafeMath for uint;
struct Member {
address addr;
uint groupsCount;
mapping(bytes32 => uint) groupName2index;
mapping(uint => uint) index2globalIndex;
}
struct Group {
bytes32 name;
uint priority;
uint membersCount;
mapping(address => uint) memberAddress2index;
mapping(uint => uint) index2globalIndex;
}
uint public membersCount;
mapping(uint => address) index2memberAddress;
mapping(address => uint) memberAddress2index;
mapping(address => Member) address2member;
uint public groupsCount;
mapping(uint => bytes32) index2groupName;
mapping(bytes32 => uint) groupName2index;
mapping(bytes32 => Group) groupName2group;
mapping(bytes32 => bool) public groupsBlocked; // if groupName => true, then couldn't be used for confirmation
function() payable public {
revert();
}
/// @notice Register user
/// Can be called only by contract owner
///
/// @param _user user address
///
/// @return code
function registerUser(address _user) external onlyContractOwner returns (uint) {
require(_user != 0x0);
if (isRegisteredUser(_user)) {
return USER_MANAGER_MEMBER_ALREADY_EXIST;
}
uint _membersCount = membersCount.add(1);
membersCount = _membersCount;
memberAddress2index[_user] = _membersCount;
index2memberAddress[_membersCount] = _user;
address2member[_user] = Member(_user, 0);
UserCreated(_user);
return OK;
}
/// @notice Discard user registration
/// Can be called only by contract owner
///
/// @param _user user address
///
/// @return code
function unregisterUser(address _user) external onlyContractOwner returns (uint) {
require(_user != 0x0);
uint _memberIndex = memberAddress2index[_user];
if (_memberIndex == 0 || address2member[_user].groupsCount != 0) {
return USER_MANAGER_INVALID_INVOCATION;
}
uint _membersCount = membersCount;
delete memberAddress2index[_user];
if (_memberIndex != _membersCount) {
address _lastUser = index2memberAddress[_membersCount];
index2memberAddress[_memberIndex] = _lastUser;
memberAddress2index[_lastUser] = _memberIndex;
}
delete address2member[_user];
delete index2memberAddress[_membersCount];
delete memberAddress2index[_user];
membersCount = _membersCount.sub(1);
UserDeleted(_user);
return OK;
}
/// @notice Create group
/// Can be called only by contract owner
///
/// @param _groupName group name
/// @param _priority group priority
///
/// @return code
function createGroup(bytes32 _groupName, uint _priority) external onlyContractOwner returns (uint) {
require(_groupName != bytes32(0));
if (isGroupExists(_groupName)) {
return USER_MANAGER_GROUP_ALREADY_EXIST;
}
uint _groupsCount = groupsCount.add(1);
groupName2index[_groupName] = _groupsCount;
index2groupName[_groupsCount] = _groupName;
groupName2group[_groupName] = Group(_groupName, _priority, 0);
groupsCount = _groupsCount;
GroupCreated(_groupName);
return OK;
}
/// @notice Change group status
/// Can be called only by contract owner
///
/// @param _groupName group name
/// @param _blocked block status
///
/// @return code
function changeGroupActiveStatus(bytes32 _groupName, bool _blocked) external onlyContractOwner returns (uint) {
require(isGroupExists(_groupName));
groupsBlocked[_groupName] = _blocked;
return OK;
}
/// @notice Add users in group
/// Can be called only by contract owner
///
/// @param _groupName group name
/// @param _users user array
///
/// @return code
function addUsersToGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) {
require(isGroupExists(_groupName));
Group storage _group = groupName2group[_groupName];
uint _groupMembersCount = _group.membersCount;
for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) {
address _user = _users[_userIdx];
uint _memberIndex = memberAddress2index[_user];
require(_memberIndex != 0);
if (_group.memberAddress2index[_user] != 0) {
continue;
}
_groupMembersCount = _groupMembersCount.add(1);
_group.memberAddress2index[_user] = _groupMembersCount;
_group.index2globalIndex[_groupMembersCount] = _memberIndex;
_addGroupToMember(_user, _groupName);
UserToGroupAdded(_user, _groupName);
}
_group.membersCount = _groupMembersCount;
return OK;
}
/// @notice Remove users in group
/// Can be called only by contract owner
///
/// @param _groupName group name
/// @param _users user array
///
/// @return code
function removeUsersFromGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) {
require(isGroupExists(_groupName));
Group storage _group = groupName2group[_groupName];
uint _groupMembersCount = _group.membersCount;
for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) {
address _user = _users[_userIdx];
uint _memberIndex = memberAddress2index[_user];
uint _groupMemberIndex = _group.memberAddress2index[_user];
if (_memberIndex == 0 || _groupMemberIndex == 0) {
continue;
}
if (_groupMemberIndex != _groupMembersCount) {
uint _lastUserGlobalIndex = _group.index2globalIndex[_groupMembersCount];
address _lastUser = index2memberAddress[_lastUserGlobalIndex];
_group.index2globalIndex[_groupMemberIndex] = _lastUserGlobalIndex;
_group.memberAddress2index[_lastUser] = _groupMemberIndex;
}
delete _group.memberAddress2index[_user];
delete _group.index2globalIndex[_groupMembersCount];
_groupMembersCount = _groupMembersCount.sub(1);
_removeGroupFromMember(_user, _groupName);
UserFromGroupRemoved(_user, _groupName);
}
_group.membersCount = _groupMembersCount;
return OK;
}
/// @notice Check is user registered
///
/// @param _user user address
///
/// @return status
function isRegisteredUser(address _user) public view returns (bool) {
return memberAddress2index[_user] != 0;
}
/// @notice Check is user in group
///
/// @param _groupName user array
/// @param _user user array
///
/// @return status
function isUserInGroup(bytes32 _groupName, address _user) public view returns (bool) {
return isRegisteredUser(_user) && address2member[_user].groupName2index[_groupName] != 0;
}
/// @notice Check is group exist
///
/// @param _groupName group name
///
/// @return status
function isGroupExists(bytes32 _groupName) public view returns (bool) {
return groupName2index[_groupName] != 0;
}
/// @notice Get current group names
///
/// @return group names
function getGroups() public view returns (bytes32[] _groups) {
uint _groupsCount = groupsCount;
_groups = new bytes32[](_groupsCount);
for (uint _groupIdx = 0; _groupIdx < _groupsCount; ++_groupIdx) {
_groups[_groupIdx] = index2groupName[_groupIdx + 1];
}
}
// PRIVATE
function _removeGroupFromMember(address _user, bytes32 _groupName) private {
Member storage _member = address2member[_user];
uint _memberGroupsCount = _member.groupsCount;
uint _memberGroupIndex = _member.groupName2index[_groupName];
if (_memberGroupIndex != _memberGroupsCount) {
uint _lastGroupGlobalIndex = _member.index2globalIndex[_memberGroupsCount];
bytes32 _lastGroupName = index2groupName[_lastGroupGlobalIndex];
_member.index2globalIndex[_memberGroupIndex] = _lastGroupGlobalIndex;
_member.groupName2index[_lastGroupName] = _memberGroupIndex;
}
delete _member.groupName2index[_groupName];
delete _member.index2globalIndex[_memberGroupsCount];
_member.groupsCount = _memberGroupsCount.sub(1);
}
function _addGroupToMember(address _user, bytes32 _groupName) private {
Member storage _member = address2member[_user];
uint _memberGroupsCount = _member.groupsCount.add(1);
_member.groupName2index[_groupName] = _memberGroupsCount;
_member.index2globalIndex[_memberGroupsCount] = groupName2index[_groupName];
_member.groupsCount = _memberGroupsCount;
}
}
contract PendingManagerEmitter {
event PolicyRuleAdded(bytes4 sig, address contractAddress, bytes32 key, bytes32 groupName, uint acceptLimit, uint declinesLimit);
event PolicyRuleRemoved(bytes4 sig, address contractAddress, bytes32 key, bytes32 groupName);
event ProtectionTxAdded(bytes32 key, bytes32 sig, uint blockNumber);
event ProtectionTxAccepted(bytes32 key, address indexed sender, bytes32 groupNameVoted);
event ProtectionTxDone(bytes32 key);
event ProtectionTxDeclined(bytes32 key, address indexed sender, bytes32 groupNameVoted);
event ProtectionTxCancelled(bytes32 key);
event ProtectionTxVoteRevoked(bytes32 key, address indexed sender, bytes32 groupNameVoted);
event TxDeleted(bytes32 key);
event Error(uint errorCode);
function _emitError(uint _errorCode) internal returns (uint) {
Error(_errorCode);
return _errorCode;
}
}
contract PendingManagerInterface {
function signIn(address _contract) external returns (uint);
function signOut(address _contract) external returns (uint);
function addPolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName,
uint _acceptLimit,
uint _declineLimit
)
external returns (uint);
function removePolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName
)
external returns (uint);
function addTx(bytes32 _key, bytes4 _sig, address _contract) external returns (uint);
function deleteTx(bytes32 _key) external returns (uint);
function accept(bytes32 _key, bytes32 _votingGroupName) external returns (uint);
function decline(bytes32 _key, bytes32 _votingGroupName) external returns (uint);
function revoke(bytes32 _key) external returns (uint);
function hasConfirmedRecord(bytes32 _key) public view returns (uint);
function getPolicyDetails(bytes4 _sig, address _contract) public view returns (
bytes32[] _groupNames,
uint[] _acceptLimits,
uint[] _declineLimits,
uint _totalAcceptedLimit,
uint _totalDeclinedLimit
);
}
/// @title PendingManager
///
/// Base implementation
/// This contract serves as pending manager for transaction status
contract PendingManager is Object, PendingManagerEmitter, PendingManagerInterface {
uint constant NO_RECORDS_WERE_FOUND = 4;
uint constant PENDING_MANAGER_SCOPE = 4000;
uint constant PENDING_MANAGER_INVALID_INVOCATION = PENDING_MANAGER_SCOPE + 1;
uint constant PENDING_MANAGER_HASNT_VOTED = PENDING_MANAGER_SCOPE + 2;
uint constant PENDING_DUPLICATE_TX = PENDING_MANAGER_SCOPE + 3;
uint constant PENDING_MANAGER_CONFIRMED = PENDING_MANAGER_SCOPE + 4;
uint constant PENDING_MANAGER_REJECTED = PENDING_MANAGER_SCOPE + 5;
uint constant PENDING_MANAGER_IN_PROCESS = PENDING_MANAGER_SCOPE + 6;
uint constant PENDING_MANAGER_TX_DOESNT_EXIST = PENDING_MANAGER_SCOPE + 7;
uint constant PENDING_MANAGER_TX_WAS_DECLINED = PENDING_MANAGER_SCOPE + 8;
uint constant PENDING_MANAGER_TX_WAS_NOT_CONFIRMED = PENDING_MANAGER_SCOPE + 9;
uint constant PENDING_MANAGER_INSUFFICIENT_GAS = PENDING_MANAGER_SCOPE + 10;
uint constant PENDING_MANAGER_POLICY_NOT_FOUND = PENDING_MANAGER_SCOPE + 11;
using SafeMath for uint;
enum GuardState {
Decline, Confirmed, InProcess
}
struct Requirements {
bytes32 groupName;
uint acceptLimit;
uint declineLimit;
}
struct Policy {
uint groupsCount;
mapping(uint => Requirements) participatedGroups; // index => globalGroupIndex
mapping(bytes32 => uint) groupName2index; // groupName => localIndex
uint totalAcceptedLimit;
uint totalDeclinedLimit;
uint securesCount;
mapping(uint => uint) index2txIndex;
mapping(uint => uint) txIndex2index;
}
struct Vote {
bytes32 groupName;
bool accepted;
}
struct Guard {
GuardState state;
uint basePolicyIndex;
uint alreadyAccepted;
uint alreadyDeclined;
mapping(address => Vote) votes; // member address => vote
mapping(bytes32 => uint) acceptedCount; // groupName => how many from group has already accepted
mapping(bytes32 => uint) declinedCount; // groupName => how many from group has already declined
}
address public accessManager;
mapping(address => bool) public authorized;
uint public policiesCount;
mapping(uint => bytes32) index2PolicyId; // index => policy hash
mapping(bytes32 => uint) policyId2Index; // policy hash => index
mapping(bytes32 => Policy) policyId2policy; // policy hash => policy struct
uint public txCount;
mapping(uint => bytes32) index2txKey;
mapping(bytes32 => uint) txKey2index; // tx key => index
mapping(bytes32 => Guard) txKey2guard;
/// @dev Execution is allowed only by authorized contract
modifier onlyAuthorized {
if (authorized[msg.sender] || address(this) == msg.sender) {
_;
}
}
/// @dev Pending Manager's constructor
///
/// @param _accessManager access manager's address
function PendingManager(address _accessManager) public {
require(_accessManager != 0x0);
accessManager = _accessManager;
}
function() payable public {
revert();
}
/// @notice Update access manager address
///
/// @param _accessManager access manager's address
function setAccessManager(address _accessManager) external onlyContractOwner returns (uint) {
require(_accessManager != 0x0);
accessManager = _accessManager;
return OK;
}
/// @notice Sign in contract
///
/// @param _contract contract's address
function signIn(address _contract) external onlyContractOwner returns (uint) {
require(_contract != 0x0);
authorized[_contract] = true;
return OK;
}
/// @notice Sign out contract
///
/// @param _contract contract's address
function signOut(address _contract) external onlyContractOwner returns (uint) {
require(_contract != 0x0);
delete authorized[_contract];
return OK;
}
/// @notice Register new policy rule
/// Can be called only by contract owner
///
/// @param _sig target method signature
/// @param _contract target contract address
/// @param _groupName group's name
/// @param _acceptLimit accepted vote limit
/// @param _declineLimit decline vote limit
///
/// @return code
function addPolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName,
uint _acceptLimit,
uint _declineLimit
)
onlyContractOwner
external
returns (uint)
{
require(_sig != 0x0);
require(_contract != 0x0);
require(GroupsAccessManager(accessManager).isGroupExists(_groupName));
require(_acceptLimit != 0);
require(_declineLimit != 0);
bytes32 _policyHash = keccak256(_sig, _contract);
if (policyId2Index[_policyHash] == 0) {
uint _policiesCount = policiesCount.add(1);
index2PolicyId[_policiesCount] = _policyHash;
policyId2Index[_policyHash] = _policiesCount;
policiesCount = _policiesCount;
}
Policy storage _policy = policyId2policy[_policyHash];
uint _policyGroupsCount = _policy.groupsCount;
if (_policy.groupName2index[_groupName] == 0) {
_policyGroupsCount += 1;
_policy.groupName2index[_groupName] = _policyGroupsCount;
_policy.participatedGroups[_policyGroupsCount].groupName = _groupName;
_policy.groupsCount = _policyGroupsCount;
}
uint _previousAcceptLimit = _policy.participatedGroups[_policyGroupsCount].acceptLimit;
uint _previousDeclineLimit = _policy.participatedGroups[_policyGroupsCount].declineLimit;
_policy.participatedGroups[_policyGroupsCount].acceptLimit = _acceptLimit;
_policy.participatedGroups[_policyGroupsCount].declineLimit = _declineLimit;
_policy.totalAcceptedLimit = _policy.totalAcceptedLimit.sub(_previousAcceptLimit).add(_acceptLimit);
_policy.totalDeclinedLimit = _policy.totalDeclinedLimit.sub(_previousDeclineLimit).add(_declineLimit);
PolicyRuleAdded(_sig, _contract, _policyHash, _groupName, _acceptLimit, _declineLimit);
return OK;
}
/// @notice Remove policy rule
/// Can be called only by contract owner
///
/// @param _groupName group's name
///
/// @return code
function removePolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName
)
onlyContractOwner
external
returns (uint)
{
require(_sig != bytes4(0));
require(_contract != 0x0);
require(GroupsAccessManager(accessManager).isGroupExists(_groupName));
bytes32 _policyHash = keccak256(_sig, _contract);
Policy storage _policy = policyId2policy[_policyHash];
uint _policyGroupNameIndex = _policy.groupName2index[_groupName];
if (_policyGroupNameIndex == 0) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
uint _policyGroupsCount = _policy.groupsCount;
if (_policyGroupNameIndex != _policyGroupsCount) {
Requirements storage _requirements = _policy.participatedGroups[_policyGroupsCount];
_policy.participatedGroups[_policyGroupNameIndex] = _requirements;
_policy.groupName2index[_requirements.groupName] = _policyGroupNameIndex;
}
_policy.totalAcceptedLimit = _policy.totalAcceptedLimit.sub(_policy.participatedGroups[_policyGroupsCount].acceptLimit);
_policy.totalDeclinedLimit = _policy.totalDeclinedLimit.sub(_policy.participatedGroups[_policyGroupsCount].declineLimit);
delete _policy.groupName2index[_groupName];
delete _policy.participatedGroups[_policyGroupsCount];
_policy.groupsCount = _policyGroupsCount.sub(1);
PolicyRuleRemoved(_sig, _contract, _policyHash, _groupName);
return OK;
}
/// @notice Add transaction
///
/// @param _key transaction id
///
/// @return code
function addTx(bytes32 _key, bytes4 _sig, address _contract) external onlyAuthorized returns (uint) {
require(_key != bytes32(0));
require(_sig != bytes4(0));
require(_contract != 0x0);
bytes32 _policyHash = keccak256(_sig, _contract);
require(isPolicyExist(_policyHash));
if (isTxExist(_key)) {
return _emitError(PENDING_DUPLICATE_TX);
}
if (_policyHash == bytes32(0)) {
return _emitError(PENDING_MANAGER_POLICY_NOT_FOUND);
}
uint _index = txCount.add(1);
txCount = _index;
index2txKey[_index] = _key;
txKey2index[_key] = _index;
Guard storage _guard = txKey2guard[_key];
_guard.basePolicyIndex = policyId2Index[_policyHash];
_guard.state = GuardState.InProcess;
Policy storage _policy = policyId2policy[_policyHash];
uint _counter = _policy.securesCount.add(1);
_policy.securesCount = _counter;
_policy.index2txIndex[_counter] = _index;
_policy.txIndex2index[_index] = _counter;
ProtectionTxAdded(_key, _policyHash, block.number);
return OK;
}
/// @notice Delete transaction
/// @param _key transaction id
/// @return code
function deleteTx(bytes32 _key) external onlyContractOwner returns (uint) {
require(_key != bytes32(0));
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
uint _txsCount = txCount;
uint _txIndex = txKey2index[_key];
if (_txIndex != _txsCount) {
bytes32 _last = index2txKey[txCount];
index2txKey[_txIndex] = _last;
txKey2index[_last] = _txIndex;
}
delete txKey2index[_key];
delete index2txKey[_txsCount];
txCount = _txsCount.sub(1);
uint _basePolicyIndex = txKey2guard[_key].basePolicyIndex;
Policy storage _policy = policyId2policy[index2PolicyId[_basePolicyIndex]];
uint _counter = _policy.securesCount;
uint _policyTxIndex = _policy.txIndex2index[_txIndex];
if (_policyTxIndex != _counter) {
uint _movedTxIndex = _policy.index2txIndex[_counter];
_policy.index2txIndex[_policyTxIndex] = _movedTxIndex;
_policy.txIndex2index[_movedTxIndex] = _policyTxIndex;
}
delete _policy.index2txIndex[_counter];
delete _policy.txIndex2index[_txIndex];
_policy.securesCount = _counter.sub(1);
TxDeleted(_key);
return OK;
}
/// @notice Accept transaction
/// Can be called only by registered user in GroupsAccessManager
///
/// @param _key transaction id
///
/// @return code
function accept(bytes32 _key, bytes32 _votingGroupName) external returns (uint) {
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
if (!GroupsAccessManager(accessManager).isUserInGroup(_votingGroupName, msg.sender)) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Guard storage _guard = txKey2guard[_key];
if (_guard.state != GuardState.InProcess) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
if (_guard.votes[msg.sender].groupName != bytes32(0) && _guard.votes[msg.sender].accepted) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Policy storage _policy = policyId2policy[index2PolicyId[_guard.basePolicyIndex]];
uint _policyGroupIndex = _policy.groupName2index[_votingGroupName];
uint _groupAcceptedVotesCount = _guard.acceptedCount[_votingGroupName];
if (_groupAcceptedVotesCount == _policy.participatedGroups[_policyGroupIndex].acceptLimit) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
_guard.votes[msg.sender] = Vote(_votingGroupName, true);
_guard.acceptedCount[_votingGroupName] = _groupAcceptedVotesCount + 1;
uint _alreadyAcceptedCount = _guard.alreadyAccepted + 1;
_guard.alreadyAccepted = _alreadyAcceptedCount;
ProtectionTxAccepted(_key, msg.sender, _votingGroupName);
if (_alreadyAcceptedCount == _policy.totalAcceptedLimit) {
_guard.state = GuardState.Confirmed;
ProtectionTxDone(_key);
}
return OK;
}
/// @notice Decline transaction
/// Can be called only by registered user in GroupsAccessManager
///
/// @param _key transaction id
///
/// @return code
function decline(bytes32 _key, bytes32 _votingGroupName) external returns (uint) {
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
if (!GroupsAccessManager(accessManager).isUserInGroup(_votingGroupName, msg.sender)) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Guard storage _guard = txKey2guard[_key];
if (_guard.state != GuardState.InProcess) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
if (_guard.votes[msg.sender].groupName != bytes32(0) && !_guard.votes[msg.sender].accepted) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Policy storage _policy = policyId2policy[index2PolicyId[_guard.basePolicyIndex]];
uint _policyGroupIndex = _policy.groupName2index[_votingGroupName];
uint _groupDeclinedVotesCount = _guard.declinedCount[_votingGroupName];
if (_groupDeclinedVotesCount == _policy.participatedGroups[_policyGroupIndex].declineLimit) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
_guard.votes[msg.sender] = Vote(_votingGroupName, false);
_guard.declinedCount[_votingGroupName] = _groupDeclinedVotesCount + 1;
uint _alreadyDeclinedCount = _guard.alreadyDeclined + 1;
_guard.alreadyDeclined = _alreadyDeclinedCount;
ProtectionTxDeclined(_key, msg.sender, _votingGroupName);
if (_alreadyDeclinedCount == _policy.totalDeclinedLimit) {
_guard.state = GuardState.Decline;
ProtectionTxCancelled(_key);
}
return OK;
}
/// @notice Revoke user votes for transaction
/// Can be called only by contract owner
///
/// @param _key transaction id
/// @param _user target user address
///
/// @return code
function forceRejectVotes(bytes32 _key, address _user) external onlyContractOwner returns (uint) {
return _revoke(_key, _user);
}
/// @notice Revoke vote for transaction
/// Can be called only by authorized user
/// @param _key transaction id
/// @return code
function revoke(bytes32 _key) external returns (uint) {
return _revoke(_key, msg.sender);
}
/// @notice Check transaction status
/// @param _key transaction id
/// @return code
function hasConfirmedRecord(bytes32 _key) public view returns (uint) {
require(_key != bytes32(0));
if (!isTxExist(_key)) {
return NO_RECORDS_WERE_FOUND;
}
Guard storage _guard = txKey2guard[_key];
return _guard.state == GuardState.InProcess
? PENDING_MANAGER_IN_PROCESS
: _guard.state == GuardState.Confirmed
? OK
: PENDING_MANAGER_REJECTED;
}
/// @notice Check policy details
///
/// @return _groupNames group names included in policies
/// @return _acceptLimits accept limit for group
/// @return _declineLimits decline limit for group
function getPolicyDetails(bytes4 _sig, address _contract)
public
view
returns (
bytes32[] _groupNames,
uint[] _acceptLimits,
uint[] _declineLimits,
uint _totalAcceptedLimit,
uint _totalDeclinedLimit
) {
require(_sig != bytes4(0));
require(_contract != 0x0);
bytes32 _policyHash = keccak256(_sig, _contract);
uint _policyIdx = policyId2Index[_policyHash];
if (_policyIdx == 0) {
return;
}
Policy storage _policy = policyId2policy[_policyHash];
uint _policyGroupsCount = _policy.groupsCount;
_groupNames = new bytes32[](_policyGroupsCount);
_acceptLimits = new uint[](_policyGroupsCount);
_declineLimits = new uint[](_policyGroupsCount);
for (uint _idx = 0; _idx < _policyGroupsCount; ++_idx) {
Requirements storage _requirements = _policy.participatedGroups[_idx + 1];
_groupNames[_idx] = _requirements.groupName;
_acceptLimits[_idx] = _requirements.acceptLimit;
_declineLimits[_idx] = _requirements.declineLimit;
}
(_totalAcceptedLimit, _totalDeclinedLimit) = (_policy.totalAcceptedLimit, _policy.totalDeclinedLimit);
}
/// @notice Check policy include target group
/// @param _policyHash policy hash (sig, contract address)
/// @param _groupName group id
/// @return bool
function isGroupInPolicy(bytes32 _policyHash, bytes32 _groupName) public view returns (bool) {
Policy storage _policy = policyId2policy[_policyHash];
return _policy.groupName2index[_groupName] != 0;
}
/// @notice Check is policy exist
/// @param _policyHash policy hash (sig, contract address)
/// @return bool
function isPolicyExist(bytes32 _policyHash) public view returns (bool) {
return policyId2Index[_policyHash] != 0;
}
/// @notice Check is transaction exist
/// @param _key transaction id
/// @return bool
function isTxExist(bytes32 _key) public view returns (bool){
return txKey2index[_key] != 0;
}
function _updateTxState(Policy storage _policy, Guard storage _guard, uint confirmedAmount, uint declineAmount) private {
if (declineAmount != 0 && _guard.state != GuardState.Decline) {
_guard.state = GuardState.Decline;
} else if (confirmedAmount >= _policy.groupsCount && _guard.state != GuardState.Confirmed) {
_guard.state = GuardState.Confirmed;
} else if (_guard.state != GuardState.InProcess) {
_guard.state = GuardState.InProcess;
}
}
function _revoke(bytes32 _key, address _user) private returns (uint) {
require(_key != bytes32(0));
require(_user != 0x0);
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
Guard storage _guard = txKey2guard[_key];
if (_guard.state != GuardState.InProcess) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
bytes32 _votedGroupName = _guard.votes[_user].groupName;
if (_votedGroupName == bytes32(0)) {
return _emitError(PENDING_MANAGER_HASNT_VOTED);
}
bool isAcceptedVote = _guard.votes[_user].accepted;
if (isAcceptedVote) {
_guard.acceptedCount[_votedGroupName] = _guard.acceptedCount[_votedGroupName].sub(1);
_guard.alreadyAccepted = _guard.alreadyAccepted.sub(1);
} else {
_guard.declinedCount[_votedGroupName] = _guard.declinedCount[_votedGroupName].sub(1);
_guard.alreadyDeclined = _guard.alreadyDeclined.sub(1);
}
delete _guard.votes[_user];
ProtectionTxVoteRevoked(_key, _user, _votedGroupName);
return OK;
}
}
/// @title MultiSigAdapter
///
/// Abstract implementation
/// This contract serves as transaction signer
contract MultiSigAdapter is Object {
uint constant MULTISIG_ADDED = 3;
uint constant NO_RECORDS_WERE_FOUND = 4;
modifier isAuthorized {
if (msg.sender == contractOwner || msg.sender == getPendingManager()) {
_;
}
}
/// @notice Get pending address
/// @dev abstract. Needs child implementation
///
/// @return pending address
function getPendingManager() public view returns (address);
/// @notice Sign current transaction and add it to transaction pending queue
///
/// @return code
function _multisig(bytes32 _args, uint _block) internal returns (uint _code) {
bytes32 _txHash = _getKey(_args, _block);
address _manager = getPendingManager();
_code = PendingManager(_manager).hasConfirmedRecord(_txHash);
if (_code != NO_RECORDS_WERE_FOUND) {
return _code;
}
if (OK != PendingManager(_manager).addTx(_txHash, msg.sig, address(this))) {
revert();
}
return MULTISIG_ADDED;
}
function _isTxExistWithArgs(bytes32 _args, uint _block) internal view returns (bool) {
bytes32 _txHash = _getKey(_args, _block);
address _manager = getPendingManager();
return PendingManager(_manager).isTxExist(_txHash);
}
function _getKey(bytes32 _args, uint _block) private view returns (bytes32 _txHash) {
_block = _block != 0 ? _block : block.number;
_txHash = keccak256(msg.sig, _args, _block);
}
}
/// @title ServiceController
///
/// Base implementation
/// Serves for managing service instances
contract ServiceController is MultiSigAdapter {
uint constant SERVICE_CONTROLLER = 350000;
uint constant SERVICE_CONTROLLER_EMISSION_EXIST = SERVICE_CONTROLLER + 1;
uint constant SERVICE_CONTROLLER_BURNING_MAN_EXIST = SERVICE_CONTROLLER + 2;
uint constant SERVICE_CONTROLLER_ALREADY_INITIALIZED = SERVICE_CONTROLLER + 3;
uint constant SERVICE_CONTROLLER_SERVICE_EXIST = SERVICE_CONTROLLER + 4;
address public profiterole;
address public treasury;
address public pendingManager;
address public proxy;
mapping(address => bool) public sideServices;
mapping(address => bool) emissionProviders;
mapping(address => bool) burningMans;
/// @notice Default ServiceController's constructor
///
/// @param _pendingManager pending manager address
/// @param _proxy ERC20 proxy address
/// @param _profiterole profiterole address
/// @param _treasury treasury address
function ServiceController(address _pendingManager, address _proxy, address _profiterole, address _treasury) public {
require(_pendingManager != 0x0);
require(_proxy != 0x0);
require(_profiterole != 0x0);
require(_treasury != 0x0);
pendingManager = _pendingManager;
proxy = _proxy;
profiterole = _profiterole;
treasury = _treasury;
}
/// @notice Return pending manager address
///
/// @return code
function getPendingManager() public view returns (address) {
return pendingManager;
}
/// @notice Add emission provider
///
/// @param _provider emission provider address
///
/// @return code
function addEmissionProvider(address _provider, uint _block) public returns (uint _code) {
if (emissionProviders[_provider]) {
return SERVICE_CONTROLLER_EMISSION_EXIST;
}
_code = _multisig(keccak256(_provider), _block);
if (OK != _code) {
return _code;
}
emissionProviders[_provider] = true;
return OK;
}
/// @notice Remove emission provider
///
/// @param _provider emission provider address
///
/// @return code
function removeEmissionProvider(address _provider, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_provider), _block);
if (OK != _code) {
return _code;
}
delete emissionProviders[_provider];
return OK;
}
/// @notice Add burning man
///
/// @param _burningMan burning man address
///
/// @return code
function addBurningMan(address _burningMan, uint _block) public returns (uint _code) {
if (burningMans[_burningMan]) {
return SERVICE_CONTROLLER_BURNING_MAN_EXIST;
}
_code = _multisig(keccak256(_burningMan), _block);
if (OK != _code) {
return _code;
}
burningMans[_burningMan] = true;
return OK;
}
/// @notice Remove burning man
///
/// @param _burningMan burning man address
///
/// @return code
function removeBurningMan(address _burningMan, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_burningMan), _block);
if (OK != _code) {
return _code;
}
delete burningMans[_burningMan];
return OK;
}
/// @notice Update a profiterole address
///
/// @param _profiterole profiterole address
///
/// @return result code of an operation
function updateProfiterole(address _profiterole, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_profiterole), _block);
if (OK != _code) {
return _code;
}
profiterole = _profiterole;
return OK;
}
/// @notice Update a treasury address
///
/// @param _treasury treasury address
///
/// @return result code of an operation
function updateTreasury(address _treasury, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_treasury), _block);
if (OK != _code) {
return _code;
}
treasury = _treasury;
return OK;
}
/// @notice Update pending manager address
///
/// @param _pendingManager pending manager address
///
/// @return result code of an operation
function updatePendingManager(address _pendingManager, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_pendingManager), _block);
if (OK != _code) {
return _code;
}
pendingManager = _pendingManager;
return OK;
}
function addSideService(address _service, uint _block) public returns (uint _code) {
if (sideServices[_service]) {
return SERVICE_CONTROLLER_SERVICE_EXIST;
}
_code = _multisig(keccak256(_service), _block);
if (OK != _code) {
return _code;
}
sideServices[_service] = true;
return OK;
}
function removeSideService(address _service, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_service), _block);
if (OK != _code) {
return _code;
}
delete sideServices[_service];
return OK;
}
/// @notice Check target address is service
///
/// @param _address target address
///
/// @return `true` when an address is a service, `false` otherwise
function isService(address _address) public view returns (bool check) {
return _address == profiterole ||
_address == treasury ||
_address == proxy ||
_address == pendingManager ||
emissionProviders[_address] ||
burningMans[_address] ||
sideServices[_address];
}
}
/// @title Provides possibility manage holders? country limits and limits for holders.
contract DataController is OracleMethodAdapter, DataControllerEmitter {
/* CONSTANTS */
uint constant DATA_CONTROLLER = 109000;
uint constant DATA_CONTROLLER_ERROR = DATA_CONTROLLER + 1;
uint constant DATA_CONTROLLER_CURRENT_WRONG_LIMIT = DATA_CONTROLLER + 2;
uint constant DATA_CONTROLLER_WRONG_ALLOWANCE = DATA_CONTROLLER + 3;
uint constant DATA_CONTROLLER_COUNTRY_CODE_ALREADY_EXISTS = DATA_CONTROLLER + 4;
uint constant MAX_TOKEN_HOLDER_NUMBER = 2 ** 256 - 1;
using SafeMath for uint;
/* STRUCTS */
/// @title HoldersData couldn't be public because of internal structures, so needed to provide getters for different parts of _holderData
struct HoldersData {
uint countryCode;
uint sendLimPerDay;
uint sendLimPerMonth;
bool operational;
bytes text;
uint holderAddressCount;
mapping(uint => address) index2Address;
mapping(address => uint) address2Index;
}
struct CountryLimits {
uint countryCode;
uint maxTokenHolderNumber;
uint currentTokenHolderNumber;
}
/* FIELDS */
address public withdrawal;
address assetAddress;
address public serviceController;
mapping(address => uint) public allowance;
// Iterable mapping pattern is used for holders.
/// @dev This is an access address mapping. Many addresses may have access to a single holder.
uint public holdersCount;
mapping(uint => HoldersData) holders;
mapping(address => bytes32) holderAddress2Id;
mapping(bytes32 => uint) public holderIndex;
// This is an access address mapping. Many addresses may have access to a single holder.
uint public countriesCount;
mapping(uint => CountryLimits) countryLimitsList;
mapping(uint => uint) countryIndex;
/* MODIFIERS */
modifier onlyWithdrawal {
if (msg.sender != withdrawal) {
revert();
}
_;
}
modifier onlyAsset {
if (msg.sender == assetAddress) {
_;
}
}
modifier onlyContractOwner {
if (msg.sender == contractOwner) {
_;
}
}
/// @notice Constructor for _holderData controller.
/// @param _serviceController service controller
function DataController(address _serviceController, address _asset) public {
require(_serviceController != 0x0);
require(_asset != 0x0);
serviceController = _serviceController;
assetAddress = _asset;
}
function() payable public {
revert();
}
function setWithdraw(address _withdrawal) onlyContractOwner external returns (uint) {
require(_withdrawal != 0x0);
withdrawal = _withdrawal;
return OK;
}
function getPendingManager() public view returns (address) {
return ServiceController(serviceController).getPendingManager();
}
function getHolderInfo(bytes32 _externalHolderId) public view returns (
uint _countryCode,
uint _limPerDay,
uint _limPerMonth,
bool _operational,
bytes _text
) {
HoldersData storage _data = holders[holderIndex[_externalHolderId]];
return (_data.countryCode, _data.sendLimPerDay, _data.sendLimPerMonth, _data.operational, _data.text);
}
function getHolderAddresses(bytes32 _externalHolderId) public view returns (address[] _addresses) {
HoldersData storage _holderData = holders[holderIndex[_externalHolderId]];
uint _addressesCount = _holderData.holderAddressCount;
_addresses = new address[](_addressesCount);
for (uint _holderAddressIdx = 0; _holderAddressIdx < _addressesCount; ++_holderAddressIdx) {
_addresses[_holderAddressIdx] = _holderData.index2Address[_holderAddressIdx + 1];
}
}
function getHolderCountryCode(bytes32 _externalHolderId) public view returns (uint) {
return holders[holderIndex[_externalHolderId]].countryCode;
}
function getHolderExternalIdByAddress(address _address) public view returns (bytes32) {
return holderAddress2Id[_address];
}
/// @notice Checks user is holder.
/// @param _address checking address.
/// @return `true` if _address is registered holder, `false` otherwise.
function isRegisteredAddress(address _address) public view returns (bool) {
return holderIndex[holderAddress2Id[_address]] != 0;
}
function isHolderOwnAddress(bytes32 _externalHolderId, address _address) public view returns (bool) {
uint _holderIndex = holderIndex[_externalHolderId];
if (_holderIndex == 0) {
return false;
}
return holders[_holderIndex].address2Index[_address] != 0;
}
function getCountryInfo(uint _countryCode) public view returns (uint _maxHolderNumber, uint _currentHolderCount) {
CountryLimits storage _data = countryLimitsList[countryIndex[_countryCode]];
return (_data.maxTokenHolderNumber, _data.currentTokenHolderNumber);
}
function getCountryLimit(uint _countryCode) public view returns (uint limit) {
uint _index = countryIndex[_countryCode];
require(_index != 0);
return countryLimitsList[_index].maxTokenHolderNumber;
}
function addCountryCode(uint _countryCode) onlyContractOwner public returns (uint) {
var (,_created) = _createCountryId(_countryCode);
if (!_created) {
return _emitError(DATA_CONTROLLER_COUNTRY_CODE_ALREADY_EXISTS);
}
return OK;
}
/// @notice Returns holder id for the specified address, creates it if needed.
/// @param _externalHolderId holder address.
/// @param _countryCode country code.
/// @return error code.
function registerHolder(bytes32 _externalHolderId, address _holderAddress, uint _countryCode) onlyOracleOrOwner external returns (uint) {
require(_holderAddress != 0x0);
require(holderIndex[_externalHolderId] == 0);
uint _holderIndex = holderIndex[holderAddress2Id[_holderAddress]];
require(_holderIndex == 0);
_createCountryId(_countryCode);
_holderIndex = holdersCount.add(1);
holdersCount = _holderIndex;
HoldersData storage _holderData = holders[_holderIndex];
_holderData.countryCode = _countryCode;
_holderData.operational = true;
_holderData.sendLimPerDay = MAX_TOKEN_HOLDER_NUMBER;
_holderData.sendLimPerMonth = MAX_TOKEN_HOLDER_NUMBER;
uint _firstAddressIndex = 1;
_holderData.holderAddressCount = _firstAddressIndex;
_holderData.address2Index[_holderAddress] = _firstAddressIndex;
_holderData.index2Address[_firstAddressIndex] = _holderAddress;
holderIndex[_externalHolderId] = _holderIndex;
holderAddress2Id[_holderAddress] = _externalHolderId;
_emitHolderRegistered(_externalHolderId, _holderIndex, _countryCode);
return OK;
}
/// @notice Adds new address equivalent to holder.
/// @param _externalHolderId external holder identifier.
/// @param _newAddress adding address.
/// @return error code.
function addHolderAddress(bytes32 _externalHolderId, address _newAddress) onlyOracleOrOwner external returns (uint) {
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
uint _newAddressId = holderIndex[holderAddress2Id[_newAddress]];
require(_newAddressId == 0);
HoldersData storage _holderData = holders[_holderIndex];
if (_holderData.address2Index[_newAddress] == 0) {
_holderData.holderAddressCount = _holderData.holderAddressCount.add(1);
_holderData.address2Index[_newAddress] = _holderData.holderAddressCount;
_holderData.index2Address[_holderData.holderAddressCount] = _newAddress;
}
holderAddress2Id[_newAddress] = _externalHolderId;
_emitHolderAddressAdded(_externalHolderId, _newAddress, _holderIndex);
return OK;
}
/// @notice Remove an address owned by a holder.
/// @param _externalHolderId external holder identifier.
/// @param _address removing address.
/// @return error code.
function removeHolderAddress(bytes32 _externalHolderId, address _address) onlyOracleOrOwner external returns (uint) {
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
HoldersData storage _holderData = holders[_holderIndex];
uint _tempIndex = _holderData.address2Index[_address];
require(_tempIndex != 0);
address _lastAddress = _holderData.index2Address[_holderData.holderAddressCount];
_holderData.address2Index[_lastAddress] = _tempIndex;
_holderData.index2Address[_tempIndex] = _lastAddress;
delete _holderData.address2Index[_address];
_holderData.holderAddressCount = _holderData.holderAddressCount.sub(1);
delete holderAddress2Id[_address];
_emitHolderAddressRemoved(_externalHolderId, _address, _holderIndex);
return OK;
}
/// @notice Change operational status for holder.
/// Can be accessed by contract owner or oracle only.
///
/// @param _externalHolderId external holder identifier.
/// @param _operational operational status.
///
/// @return result code.
function changeOperational(bytes32 _externalHolderId, bool _operational) onlyOracleOrOwner external returns (uint) {
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
holders[_holderIndex].operational = _operational;
_emitHolderOperationalChanged(_externalHolderId, _operational);
return OK;
}
/// @notice Changes text for holder.
/// Can be accessed by contract owner or oracle only.
///
/// @param _externalHolderId external holder identifier.
/// @param _text changing text.
///
/// @return result code.
function updateTextForHolder(bytes32 _externalHolderId, bytes _text) onlyOracleOrOwner external returns (uint) {
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
holders[_holderIndex].text = _text;
return OK;
}
/// @notice Updates limit per day for holder.
///
/// Can be accessed by contract owner only.
///
/// @param _externalHolderId external holder identifier.
/// @param _limit limit value.
///
/// @return result code.
function updateLimitPerDay(bytes32 _externalHolderId, uint _limit) onlyOracleOrOwner external returns (uint) {
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
uint _currentLimit = holders[_holderIndex].sendLimPerDay;
holders[_holderIndex].sendLimPerDay = _limit;
_emitDayLimitChanged(_externalHolderId, _currentLimit, _limit);
return OK;
}
/// @notice Updates limit per month for holder.
/// Can be accessed by contract owner or oracle only.
///
/// @param _externalHolderId external holder identifier.
/// @param _limit limit value.
///
/// @return result code.
function updateLimitPerMonth(bytes32 _externalHolderId, uint _limit) onlyOracleOrOwner external returns (uint) {
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
uint _currentLimit = holders[_holderIndex].sendLimPerDay;
holders[_holderIndex].sendLimPerMonth = _limit;
_emitMonthLimitChanged(_externalHolderId, _currentLimit, _limit);
return OK;
}
/// @notice Change country limits.
/// Can be accessed by contract owner or oracle only.
///
/// @param _countryCode country code.
/// @param _limit limit value.
///
/// @return result code.
function changeCountryLimit(uint _countryCode, uint _limit) onlyOracleOrOwner external returns (uint) {
uint _countryIndex = countryIndex[_countryCode];
require(_countryIndex != 0);
uint _currentTokenHolderNumber = countryLimitsList[_countryIndex].currentTokenHolderNumber;
if (_currentTokenHolderNumber > _limit) {
return DATA_CONTROLLER_CURRENT_WRONG_LIMIT;
}
countryLimitsList[_countryIndex].maxTokenHolderNumber = _limit;
_emitCountryCodeChanged(_countryIndex, _countryCode, _limit);
return OK;
}
function withdrawFrom(address _holderAddress, uint _value) public onlyAsset returns (uint) {
bytes32 _externalHolderId = holderAddress2Id[_holderAddress];
HoldersData storage _holderData = holders[holderIndex[_externalHolderId]];
_holderData.sendLimPerDay = _holderData.sendLimPerDay.sub(_value);
_holderData.sendLimPerMonth = _holderData.sendLimPerMonth.sub(_value);
return OK;
}
function depositTo(address _holderAddress, uint _value) public onlyAsset returns (uint) {
bytes32 _externalHolderId = holderAddress2Id[_holderAddress];
HoldersData storage _holderData = holders[holderIndex[_externalHolderId]];
_holderData.sendLimPerDay = _holderData.sendLimPerDay.add(_value);
_holderData.sendLimPerMonth = _holderData.sendLimPerMonth.add(_value);
return OK;
}
function updateCountryHoldersCount(uint _countryCode, uint _updatedHolderCount) public onlyAsset returns (uint) {
CountryLimits storage _data = countryLimitsList[countryIndex[_countryCode]];
assert(_data.maxTokenHolderNumber >= _updatedHolderCount);
_data.currentTokenHolderNumber = _updatedHolderCount;
return OK;
}
function changeAllowance(address _from, uint _value) public onlyWithdrawal returns (uint) {
ServiceController _serviceController = ServiceController(serviceController);
ATxAssetProxy token = ATxAssetProxy(_serviceController.proxy());
if (token.balanceOf(_from) < _value) {
return DATA_CONTROLLER_WRONG_ALLOWANCE;
}
allowance[_from] = _value;
return OK;
}
function _createCountryId(uint _countryCode) internal returns (uint, bool _created) {
uint countryId = countryIndex[_countryCode];
if (countryId == 0) {
uint _countriesCount = countriesCount;
countryId = _countriesCount.add(1);
countriesCount = countryId;
CountryLimits storage limits = countryLimitsList[countryId];
limits.countryCode = _countryCode;
limits.maxTokenHolderNumber = MAX_TOKEN_HOLDER_NUMBER;
countryIndex[_countryCode] = countryId;
_emitCountryCodeAdded(countryIndex[_countryCode], _countryCode, MAX_TOKEN_HOLDER_NUMBER);
_created = true;
}
return (countryId, _created);
}
}
|
Get pending address abstract. Needs child implementation return pending address Sign current transaction and add it to transaction pending queue return code
|
function getPendingManager() public view returns (address);
function _multisig(bytes32 _args, uint _block) internal returns (uint _code) {
bytes32 _txHash = _getKey(_args, _block);
address _manager = getPendingManager();
_code = PendingManager(_manager).hasConfirmedRecord(_txHash);
if (_code != NO_RECORDS_WERE_FOUND) {
return _code;
}
if (OK != PendingManager(_manager).addTx(_txHash, msg.sig, address(this))) {
revert();
}
return MULTISIG_ADDED;
}
| 259,246 |
pragma solidity ^0.4.11;
interface CommonWallet {
function receive() external payable;
}
library StringUtils {
function concat(string _a, string _b)
internal
pure
returns (string)
{
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory bab = new bytes(_ba.length + _bb.length);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
}
library UintStringUtils {
function toString(uint i)
internal
pure
returns (string)
{
if (i == 0) return '0';
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}
// @title AddressUtils
// @dev Utility library of inline functions on addresses
library AddressUtils {
// Returns whether the target address is a contract
// @dev This function will return false if invoked during the constructor of a contract,
// as the code is not actually created until after the constructor finishes.
// @param addr address to check
// @return whether the target address is a contract
function isContract(address addr)
internal
view
returns(bool)
{
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
// @title SafeMath256
// @dev Math operations with safety checks that throw on error
library SafeMath256 {
// @dev Multiplies two numbers, throws on overflow.
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
// @dev Integer division of two numbers, truncating the quotient.
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
// @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
// @dev Adds two numbers, throws on overflow.
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
library SafeMath32 {
// @dev Multiplies two numbers, throws on overflow.
function mul(uint32 a, uint32 b) internal pure returns (uint32 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
// @dev Integer division of two numbers, truncating the quotient.
function div(uint32 a, uint32 b) internal pure returns (uint32) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a - b;
}
// @dev Adds two numbers, throws on overflow.
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
c = a + b;
assert(c >= a);
return c;
}
}
library SafeMath8 {
// @dev Multiplies two numbers, throws on overflow.
function mul(uint8 a, uint8 b) internal pure returns (uint8 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
// @dev Integer division of two numbers, truncating the quotient.
function div(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint8 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(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
// @dev Adds two numbers, throws on overflow.
function add(uint8 a, uint8 b) internal pure returns (uint8 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/// @title A facet of DragonCore that manages special access privileges.
contract DragonAccessControl
{
// @dev Non Assigned address.
address constant NA = address(0);
/// @dev Contract owner
address internal controller_;
/// @dev Contract modes
enum Mode {TEST, PRESALE, OPERATE}
/// @dev Contract state
Mode internal mode_ = Mode.TEST;
/// @dev OffChain Server accounts ('minions') addresses
/// It's used for money withdrawal and export of tokens
mapping(address => bool) internal minions_;
/// @dev Presale contract address. Can call `presale` method.
address internal presale_;
// Modifiers ---------------------------------------------------------------
/// @dev Limit execution to controller account only.
modifier controllerOnly() {
require(controller_ == msg.sender, "controller_only");
_;
}
/// @dev Limit execution to minion account only.
modifier minionOnly() {
require(minions_[msg.sender], "minion_only");
_;
}
/// @dev Limit execution to test time only.
modifier testModeOnly {
require(mode_ == Mode.TEST, "test_mode_only");
_;
}
/// @dev Limit execution to presale time only.
modifier presaleModeOnly {
require(mode_ == Mode.PRESALE, "presale_mode_only");
_;
}
/// @dev Limit execution to operate time only.
modifier operateModeOnly {
require(mode_ == Mode.OPERATE, "operate_mode_only");
_;
}
/// @dev Limit execution to presale account only.
modifier presaleOnly() {
require(msg.sender == presale_, "presale_only");
_;
}
/// @dev set state to Mode.OPERATE.
function setOperateMode()
external
controllerOnly
presaleModeOnly
{
mode_ = Mode.OPERATE;
}
/// @dev Set presale contract address. Becomes useless when presale is over.
/// @param _presale Presale contract address.
function setPresale(address _presale)
external
controllerOnly
{
presale_ = _presale;
}
/// @dev set state to Mode.PRESALE.
function setPresaleMode()
external
controllerOnly
testModeOnly
{
mode_ = Mode.PRESALE;
}
/// @dev Get controller address.
/// @return Address of contract's controller.
function controller()
external
view
returns(address)
{
return controller_;
}
/// @dev Transfer control to new address. Set controller an approvee for
/// tokens that managed by contract itself. Remove previous controller value
/// from contract's approvees.
/// @param _to New controller address.
function setController(address _to)
external
controllerOnly
{
require(_to != NA, "_to");
require(controller_ != _to, "already_controller");
controller_ = _to;
}
/// @dev Check if address is a minion.
/// @param _addr Address to check.
/// @return True if address is a minion.
function isMinion(address _addr)
public view returns(bool)
{
return minions_[_addr];
}
function getCurrentMode()
public view returns (Mode)
{
return mode_;
}
}
/// @dev token description, storage and transfer functions
contract DragonBase is DragonAccessControl
{
using SafeMath8 for uint8;
using SafeMath32 for uint32;
using SafeMath256 for uint256;
using StringUtils for string;
using UintStringUtils for uint;
/// @dev The Birth event is fired whenever a new dragon comes into existence.
event Birth(address owner, uint256 petId, uint256 tokenId, uint256 parentA, uint256 parentB, string genes, string params);
/// @dev Token name
string internal name_;
/// @dev Token symbol
string internal symbol_;
/// @dev Token resolving url
string internal url_;
struct DragonToken {
// Constant Token params
uint8 genNum; // generation number. uses for dragon view
string genome; // genome description
uint256 petId; // offchain dragon identifier
// Parents
uint256 parentA;
uint256 parentB;
// Game-depening Token params
string params; // can change in export operation
// State
address owner;
}
/// @dev Count of minted tokens
uint256 internal mintCount_;
/// @dev Maximum token supply
uint256 internal maxSupply_;
/// @dev Count of burn tokens
uint256 internal burnCount_;
// Tokens state
/// @dev Token approvals values
mapping(uint256 => address) internal approvals_;
/// @dev Operator approvals
mapping(address => mapping(address => bool)) internal operatorApprovals_;
/// @dev Index of token in owner's token list
mapping(uint256 => uint256) internal ownerIndex_;
/// @dev Owner's tokens list
mapping(address => uint256[]) internal ownTokens_;
/// @dev Tokens
mapping(uint256 => DragonToken) internal tokens_;
// @dev Non Assigned address.
address constant NA = address(0);
/// @dev Add token to new owner. Increase owner's balance.
/// @param _to Token receiver.
/// @param _tokenId New token id.
function _addTo(address _to, uint256 _tokenId)
internal
{
DragonToken storage token = tokens_[_tokenId];
require(token.owner == NA, "taken");
uint256 lastIndex = ownTokens_[_to].length;
ownTokens_[_to].push(_tokenId);
ownerIndex_[_tokenId] = lastIndex;
token.owner = _to;
}
/// @dev Create new token and increase mintCount.
/// @param _genome New token's genome.
/// @param _params Token params string.
/// @param _parentA Token A parent.
/// @param _parentB Token B parent.
/// @return New token id.
function _createToken(
address _to,
// Constant Token params
uint8 _genNum,
string _genome,
uint256 _parentA,
uint256 _parentB,
// Game-depening Token params
uint256 _petId,
string _params
)
internal returns(uint256)
{
uint256 tokenId = mintCount_.add(1);
mintCount_ = tokenId;
DragonToken memory token = DragonToken(
_genNum,
_genome,
_petId,
_parentA,
_parentB,
_params,
NA
);
tokens_[tokenId] = token;
_addTo(_to, tokenId);
emit Birth(_to, _petId, tokenId, _parentA, _parentB, _genome, _params);
return tokenId;
}
/// @dev Get token genome.
/// @param _tokenId Token id.
/// @return Token's genome.
function getGenome(uint256 _tokenId)
external view returns(string)
{
return tokens_[_tokenId].genome;
}
/// @dev Get token params.
/// @param _tokenId Token id.
/// @return Token's params.
function getParams(uint256 _tokenId)
external view returns(string)
{
return tokens_[_tokenId].params;
}
/// @dev Get token parentA.
/// @param _tokenId Token id.
/// @return Parent token id.
function getParentA(uint256 _tokenId)
external view returns(uint256)
{
return tokens_[_tokenId].parentA;
}
/// @dev Get token parentB.
/// @param _tokenId Token id.
/// @return Parent token id.
function getParentB(uint256 _tokenId)
external view returns(uint256)
{
return tokens_[_tokenId].parentB;
}
/// @dev Check if `_tokenId` exists. Check if owner is not addres(0).
/// @param _tokenId Token id
/// @return Return true if token owner is real.
function isExisting(uint256 _tokenId)
public view returns(bool)
{
return tokens_[_tokenId].owner != NA;
}
/// @dev Receive maxium token supply value.
/// @return Contracts `maxSupply_` variable.
function maxSupply()
external view returns(uint256)
{
return maxSupply_;
}
/// @dev Set url prefix for tokenURI generation.
/// @param _url Url prefix value.
function setUrl(string _url)
external controllerOnly
{
url_ = _url;
}
/// @dev Get token symbol.
/// @return Token symbol name.
function symbol()
external view returns(string)
{
return symbol_;
}
/// @dev Get token URI to receive offchain information by it's id.
/// @param _tokenId Token id.
/// @return URL string. For example "http://erc721.tld/tokens/1".
function tokenURI(uint256 _tokenId)
external view returns(string)
{
return url_.concat(_tokenId.toString());
}
/// @dev Get token name.
/// @return Token name string.
function name()
external view returns(string)
{
return name_;
}
/// @dev return information about _owner tokens
function getTokens(address _owner)
external view returns (uint256[], uint256[], byte[])
{
uint256[] memory tokens = ownTokens_[_owner];
uint256[] memory tokenIds = new uint256[](tokens.length);
uint256[] memory petIds = new uint256[](tokens.length);
byte[] memory genomes = new byte[](tokens.length * 77);
uint index = 0;
for(uint i = 0; i < tokens.length; i++) {
uint256 tokenId = tokens[i];
DragonToken storage token = tokens_[tokenId];
tokenIds[i] = tokenId;
petIds[i] = token.petId;
bytes storage genome = bytes(token.genome);
for(uint j = 0; j < genome.length; j++) {
genomes[index++] = genome[j];
}
}
return (tokenIds, petIds, genomes);
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @dev See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC721/ERC721.sol
contract ERC721Basic
{
/// @dev Emitted when token approvee is set
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
/// @dev Emitted when owner approve all own tokens to operator.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @dev Emitted when user deposit some funds.
event Deposit(address indexed _sender, uint256 _value);
/// @dev Emitted when user deposit some funds.
event Withdraw(address indexed _sender, uint256 _value);
/// @dev Emitted when token transferred to new owner
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
// Required methods
function balanceOf(address _owner) external view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) external;
function getApproved(uint256 _tokenId) public view returns (address _to);
//function transfer(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic
{
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) external view returns (string);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver
{
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data )
public returns(bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Metadata, ERC721Receiver
{
/// @dev Interface signature 721 for interface detection.
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7;
/*
bytes4(keccak256('supportsInterface(bytes4)'));
*/
bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63;
/*
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
bytes4(keccak256('tokenByIndex(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f;
/*
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('tokenURI(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721 = 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)'));
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165)
|| (_interfaceID == InterfaceSignature_ERC721)
|| (_interfaceID == InterfaceSignature_ERC721Enumerable)
|| (_interfaceID == InterfaceSignature_ERC721Metadata));
}
}
/// @dev ERC721 methods
contract DragonOwnership is ERC721, DragonBase
{
using StringUtils for string;
using UintStringUtils for uint;
using AddressUtils for address;
/// @dev Emitted when token transferred to new owner. Additional fields is petId, genes, params
/// it uses for client-side indication
event TransferInfo(address indexed _from, address indexed _to, uint256 _tokenId, uint256 petId, string genes, string params);
/// @dev Specify if _addr is token owner or approvee. Also check if `_addr`
/// is operator for token owner.
/// @param _tokenId Token to check ownership of.
/// @param _addr Address to check if it's an owner or an aprovee of `_tokenId`.
/// @return True if token can be managed by provided `_addr`.
function isOwnerOrApproved(uint256 _tokenId, address _addr)
public view returns(bool)
{
DragonToken memory token = tokens_[_tokenId];
if (token.owner == _addr) {
return true;
}
else if (isApprovedFor(_tokenId, _addr)) {
return true;
}
else if (isApprovedForAll(token.owner, _addr)) {
return true;
}
return false;
}
/// @dev Limit execution to token owner or approvee only.
/// @param _tokenId Token to check ownership of.
modifier ownerOrApprovedOnly(uint256 _tokenId) {
require(isOwnerOrApproved(_tokenId, msg.sender), "tokenOwnerOrApproved_only");
_;
}
/// @dev Contract's own token only acceptable.
/// @param _tokenId Contract's token id.
modifier ownOnly(uint256 _tokenId) {
require(tokens_[_tokenId].owner == address(this), "own_only");
_;
}
/// @dev Determine if token is approved for specified approvee.
/// @param _tokenId Target token id.
/// @param _approvee Approvee address.
/// @return True if so.
function isApprovedFor(uint256 _tokenId, address _approvee)
public view returns(bool)
{
return approvals_[_tokenId] == _approvee;
}
/// @dev Specify is given address set as operator with setApprovalForAll.
/// @param _owner Token owner.
/// @param _operator Address to check if it an operator.
/// @return True if operator is set.
function isApprovedForAll(address _owner, address _operator)
public view returns(bool)
{
return operatorApprovals_[_owner][_operator];
}
/// @dev Check if `_tokenId` exists. Check if owner is not addres(0).
/// @param _tokenId Token id
/// @return Return true if token owner is real.
function exists(uint256 _tokenId)
public view returns(bool)
{
return tokens_[_tokenId].owner != NA;
}
/// @dev Get owner of a token.
/// @param _tokenId Token owner id.
/// @return Token owner address.
function ownerOf(uint256 _tokenId)
public view returns(address)
{
return tokens_[_tokenId].owner;
}
/// @dev Get approvee address. If there is not approvee returns 0x0.
/// @param _tokenId Token id to get approvee of.
/// @return Approvee address or 0x0.
function getApproved(uint256 _tokenId)
public view returns(address)
{
return approvals_[_tokenId];
}
/// @dev Grant owner alike controll permissions to third party.
/// @param _to Permission receiver.
/// @param _tokenId Granted token id.
function approve(address _to, uint256 _tokenId)
external ownerOrApprovedOnly(_tokenId)
{
address owner = ownerOf(_tokenId);
require(_to != owner);
if (getApproved(_tokenId) != NA || _to != NA) {
approvals_[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/// @dev Current total tokens supply. Always less then maxSupply.
/// @return Difference between minted and burned tokens.
function totalSupply()
public view returns(uint256)
{
return mintCount_;
}
/// @dev Get number of tokens which `_owner` owns.
/// @param _owner Address to count own tokens.
/// @return Count of owned tokens.
function balanceOf(address _owner)
external view returns(uint256)
{
return ownTokens_[_owner].length;
}
/// @dev Internal set approval for all without _owner check.
/// @param _owner Granting user.
/// @param _to New account approvee.
/// @param _approved Set new approvee status.
function _setApprovalForAll(address _owner, address _to, bool _approved)
internal
{
operatorApprovals_[_owner][_to] = _approved;
emit ApprovalForAll(_owner, _to, _approved);
}
/// @dev Set approval for all account tokens.
/// @param _to Approvee address.
/// @param _approved Value true or false.
function setApprovalForAll(address _to, bool _approved)
external
{
require(_to != msg.sender);
_setApprovalForAll(msg.sender, _to, _approved);
}
/// @dev Remove approval bindings for token. Do nothing if no approval
/// exists.
/// @param _from Address of token owner.
/// @param _tokenId Target token id.
function _clearApproval(address _from, uint256 _tokenId)
internal
{
if (approvals_[_tokenId] == NA) {
return;
}
approvals_[_tokenId] = NA;
emit Approval(_from, NA, _tokenId);
}
/// @dev Check if contract was received by other side properly if receiver
/// is a ctontract.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
/// @param _data Transaction data.
/// @return True on success.
function _checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal returns(bool)
{
if (! _to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
_from, _tokenId, _data
);
return (retval == ERC721_RECEIVED);
}
/// @dev Remove token from owner. Unrecoverable.
/// @param _tokenId Removing token id.
function _remove(uint256 _tokenId)
internal
{
address owner = tokens_[_tokenId].owner;
_removeFrom(owner, _tokenId);
}
/// @dev Completely remove token from the contract. Unrecoverable.
/// @param _owner Owner of removing token.
/// @param _tokenId Removing token id.
function _removeFrom(address _owner, uint256 _tokenId)
internal
{
uint256 lastIndex = ownTokens_[_owner].length.sub(1);
uint256 lastToken = ownTokens_[_owner][lastIndex];
// Swap users token
ownTokens_[_owner][ownerIndex_[_tokenId]] = lastToken;
ownTokens_[_owner].length--;
// Swap token indexes
ownerIndex_[lastToken] = ownerIndex_[_tokenId];
ownerIndex_[_tokenId] = 0;
DragonToken storage token = tokens_[_tokenId];
token.owner = NA;
}
/// @dev Transfer token from owner `_from` to another address or contract
/// `_to` by it's `_tokenId`.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
function transferFrom( address _from, address _to, uint256 _tokenId )
public ownerOrApprovedOnly(_tokenId)
{
require(_from != NA);
require(_to != NA);
_clearApproval(_from, _tokenId);
_removeFrom(_from, _tokenId);
_addTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
DragonToken storage token = tokens_[_tokenId];
emit TransferInfo(_from, _to, _tokenId, token.petId, token.genome, token.params);
}
/// @dev Update token params and transfer to new owner. Only contract's own
/// tokens could be updated. Also notifies receiver of the token.
/// @param _to Address to transfer token to.
/// @param _tokenId Id of token that should be transferred.
/// @param _params New token params.
function updateAndSafeTransferFrom(
address _to,
uint256 _tokenId,
string _params
)
public
{
updateAndSafeTransferFrom(_to, _tokenId, _params, "");
}
/// @dev Update token params and transfer to new owner. Only contract's own
/// tokens could be updated. Also notifies receiver of the token and send
/// protion of _data to it.
/// @param _to Address to transfer token to.
/// @param _tokenId Id of token that should be transferred.
/// @param _params New token params.
/// @param _data Notification data.
function updateAndSafeTransferFrom(
address _to,
uint256 _tokenId,
string _params,
bytes _data
)
public
{
// Safe transfer from
updateAndTransferFrom(_to, _tokenId, _params, 0, 0);
require(_checkAndCallSafeTransfer(address(this), _to, _tokenId, _data));
}
/// @dev Update token params and transfer to new owner. Only contract's own
/// tokens could be updated.
/// @param _to Address to transfer token to.
/// @param _tokenId Id of token that should be transferred.
/// @param _params New token params.
function updateAndTransferFrom(
address _to,
uint256 _tokenId,
string _params,
uint256 _petId,
uint256 _transferCost
)
public
ownOnly(_tokenId)
minionOnly
{
require(bytes(_params).length > 0, "params_length");
// Update
tokens_[_tokenId].params = _params;
if (tokens_[_tokenId].petId == 0 ) {
tokens_[_tokenId].petId = _petId;
}
address from = tokens_[_tokenId].owner;
// Transfer from
transferFrom(from, _to, _tokenId);
// send to the server's wallet the transaction cost
// withdraw it from the balance of the contract. this amount must be withdrawn from the player
// on the side of the game server
if (_transferCost > 0) {
msg.sender.transfer(_transferCost);
}
}
/// @dev Transfer token from one owner to new one and check if it was
/// properly received if receiver is a contact.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
safeTransferFrom(_from, _to, _tokenId, "");
}
/// @dev Transfer token from one owner to new one and check if it was
/// properly received if receiver is a contact.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
/// @param _data Transaction data.
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
{
transferFrom(_from, _to, _tokenId);
require(_checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/// @dev Burn owned token. Increases `burnCount_` and decrease `totalSupply`
/// value.
/// @param _tokenId Id of burning token.
function burn(uint256 _tokenId)
public
ownerOrApprovedOnly(_tokenId)
{
address owner = tokens_[_tokenId].owner;
_remove(_tokenId);
burnCount_ += 1;
emit Transfer(owner, NA, _tokenId);
}
/// @dev Receive count of burned tokens. Should be greater than `totalSupply`
/// but less than `mintCount`.
/// @return Number of burned tokens
function burnCount()
external
view
returns(uint256)
{
return burnCount_;
}
function onERC721Received(address, uint256, bytes)
public returns(bytes4)
{
return ERC721_RECEIVED;
}
}
/// @title Managing contract. implements the logic of buying tokens, depositing / withdrawing funds
/// to the project account and importing / exporting tokens
contract EtherDragonsCore is DragonOwnership
{
using SafeMath8 for uint8;
using SafeMath32 for uint32;
using SafeMath256 for uint256;
using AddressUtils for address;
using StringUtils for string;
using UintStringUtils for uint;
// @dev Non Assigned address.
address constant NA = address(0);
/// @dev Bounty tokens count limit
uint256 public constant BOUNTY_LIMIT = 2500;
/// @dev Presale tokens count limit
uint256 public constant PRESALE_LIMIT = 7500;
///@dev Total gen0tokens generation limit
uint256 public constant GEN0_CREATION_LIMIT = 90000;
/// @dev Number of tokens minted in presale stage
uint256 internal presaleCount_;
/// @dev Number of tokens minted for bounty campaign
uint256 internal bountyCount_;
///@dev Company bank address
address internal bank_;
// Extension ---------------------------------------------------------------
/// @dev Contract is not payable. To fullfil balance method `depositTo`
/// should be used.
function ()
public payable
{
revert();
}
/// @dev amount on the account of the contract. This amount consists of deposits from players and the system reserve for payment of transactions
/// the player at any time to withdraw the amount corresponding to his account in the game, minus the cost of the transaction
function getBalance()
public view returns (uint256)
{
return address(this).balance;
}
/// @dev at the moment of creation of the contract we transfer the address of the bank
/// presell contract address set later
constructor(
address _bank
)
public
{
require(_bank != NA);
controller_ = msg.sender;
bank_ = _bank;
// Meta
name_ = "EtherDragons";
symbol_ = "ED";
url_ = "https://game.etherdragons.world/token/";
// Token mint limit
maxSupply_ = GEN0_CREATION_LIMIT + BOUNTY_LIMIT + PRESALE_LIMIT;
}
/// Number of tokens minted in presale stage
function totalPresaleCount()
public view returns(uint256)
{
return presaleCount_;
}
/// @dev Number of tokens minted for bounty campaign
function totalBountyCount()
public view returns(uint256)
{
return bountyCount_;
}
/// @dev Check if new token could be minted. Return true if count of minted
/// tokens less than could be minted through contract deploy.
/// Also, tokens can not be created more often than once in mintDelay_ minutes
/// @return True if current count is less then maximum tokens available for now.
function canMint()
public view returns(bool)
{
return (mintCount_ + presaleCount_ + bountyCount_) < maxSupply_;
}
/// @dev Here we write the addresses of the wallets of the server from which it is accessed
/// to contract methods.
/// @param _to New minion address
function minionAdd(address _to)
external controllerOnly
{
require(minions_[_to] == false, "already_minion");
// разрешаем этому адресу пользоваться токенами контакта
// allow the address to use contract tokens
_setApprovalForAll(address(this), _to, true);
minions_[_to] = true;
}
/// @dev delete the address of the server wallet
/// @param _to Minion address
function minionRemove(address _to)
external controllerOnly
{
require(minions_[_to], "not_a_minion");
// and forbid this wallet to use tokens of the contract
_setApprovalForAll(address(this), _to, false);
minions_[_to] = false;
}
/// @dev Here the player can put funds to the account of the contract
/// and get the same amount of in-game currency
/// the game server understands who puts money at the wallet address
function depositTo()
public payable
{
emit Deposit(msg.sender, msg.value);
}
/// @dev Transfer amount of Ethers to specified receiver. Only owner can
// call this method.
/// @param _to Transfer receiver.
/// @param _amount Transfer value.
/// @param _transferCost Transfer cost.
function transferAmount(address _to, uint256 _amount, uint256 _transferCost)
external minionOnly
{
require((_amount + _transferCost) <= address(this).balance, "not enough money!");
_to.transfer(_amount);
// send to the wallet of the server the transfer cost
// withdraw it from the balance of the contract. this amount must be withdrawn from the player
// on the side of the game server
if (_transferCost > 0) {
msg.sender.transfer(_transferCost);
}
emit Withdraw(_to, _amount);
}
/// @dev Mint new token with specified params. Transfer `_fee` to the
/// `bank`.
/// @param _to New token owner.
/// @param _fee Transaction fee.
/// @param _genNum Generation number..
/// @param _genome New genome unique value.
/// @param _parentA Parent A.
/// @param _parentB Parent B.
/// @param _petId Pet identifier.
/// @param _params List of parameters for pet.
/// @param _transferCost Transfer cost.
/// @return New token id.
function mintRelease(
address _to,
uint256 _fee,
// Constant Token params
uint8 _genNum,
string _genome,
uint256 _parentA,
uint256 _parentB,
// Game-depening Token params
uint256 _petId, //if petID = 0, then it was created outside of the server
string _params,
uint256 _transferCost
)
external minionOnly operateModeOnly returns(uint256)
{
require(canMint(), "can_mint");
require(_to != NA, "_to");
require((_fee + _transferCost) <= address(this).balance, "_fee");
require(bytes(_params).length != 0, "params_length");
require(bytes(_genome).length == 77, "genome_length");
// Parents should be both 0 or both not.
if (_parentA != 0 && _parentB != 0) {
require(_parentA != _parentB, "same_parent");
}
else if (_parentA == 0 && _parentB != 0) {
revert("parentA_empty");
}
else if (_parentB == 0 && _parentA != 0) {
revert("parentB_empty");
}
uint256 tokenId = _createToken(_to, _genNum, _genome, _parentA, _parentB, _petId, _params);
require(_checkAndCallSafeTransfer(NA, _to, tokenId, ""), "safe_transfer");
// Transfer mint fee to the fund
CommonWallet(bank_).receive.value(_fee)();
emit Transfer(NA, _to, tokenId);
// send to the server wallet server the transfer cost,
// withdraw it from the balance of the contract. this amount must be withdrawn from the player
// on the side of the game server
if (_transferCost > 0) {
msg.sender.transfer(_transferCost);
}
return tokenId;
}
/// @dev Create new token via presale state
/// @param _to New token owner.
/// @param _genome New genome unique value.
/// @return New token id.
/// at the pre-sale stage we sell the zero-generation pets, which have only a genome.
/// other attributes of such a token get when importing to the server
function mintPresell(address _to, string _genome)
external presaleOnly presaleModeOnly returns(uint256)
{
require(presaleCount_ < PRESALE_LIMIT, "presale_limit");
// у пресейл пета нет параметров. Их он получит после ввода в игру.
uint256 tokenId = _createToken(_to, 0, _genome, 0, 0, 0, "");
presaleCount_ += 1;
require(_checkAndCallSafeTransfer(NA, _to, tokenId, ""), "safe_transfer");
emit Transfer(NA, _to, tokenId);
return tokenId;
}
/// @dev Create new token for bounty activity
/// @param _to New token owner.
/// @return New token id.
function mintBounty(address _to, string _genome)
external controllerOnly returns(uint256)
{
require(bountyCount_ < BOUNTY_LIMIT, "bounty_limit");
// bounty pet has no parameters. They will receive them after importing to the game.
uint256 tokenId = _createToken(_to, 0, _genome, 0, 0, 0, "");
bountyCount_ += 1;
require(_checkAndCallSafeTransfer(NA, _to, tokenId, ""), "safe_transfer");
emit Transfer(NA, _to, tokenId);
return tokenId;
}
}
contract Presale
{
// Extension ---------------------------------------------------------------
using AddressUtils for address;
// Events ------------------------------------------------------------------
///the event is fired when starting a new wave presale stage
event StageBegin(uint8 stage, uint256 timestamp);
///the event is fired when token sold
event TokensBought(address buyerAddr, uint256[] tokenIds, bytes genomes);
// Types -------------------------------------------------------------------
struct Stage {
// Predefined values
uint256 price; // token's price on the stage
uint16 softcap; // stage softCap
uint16 hardcap; // stage hardCap
// Unknown values
uint16 bought; // sold on stage
uint32 startDate; // stage's beginDate
uint32 endDate; // stage's endDate
}
// Constants ---------------------------------------------------------------
// 10 stages of 5 genocodes
uint8 public constant STAGES = 10;
uint8 internal constant TOKENS_PER_STAGE = 5;
address constant NA = address(0);
// State -------------------------------------------------------------------
address internal CEOAddress; // contract owner
address internal bank_; // profit wallet address (not a contract)
address internal erc721_; // main contract address
/// @dev genomes for bounty stage
string[TOKENS_PER_STAGE][STAGES] internal genomes_;
/// stages data
Stage[STAGES] internal stages_;
// internal transaction counter, it uses for random generator
uint32 internal counter_;
/// stage is over
bool internal isOver_;
/// stage number
uint8 internal stageIndex_;
/// stage start Data
uint32 internal stageStart_;
// Lifetime ----------------------------------------------------------------
constructor(
address _bank,
address _erc721
)
public
{
require(_bank != NA, '_bank');
require(_erc721.isContract(), '_erc721');
CEOAddress = msg.sender;
// Addresses should not be the same.
require(_bank != CEOAddress, "bank = CEO");
require(CEOAddress != _erc721, "CEO = erc721");
require(_erc721 != _bank, "bank = erc721");
// Update state
bank_ = _bank;
erc721_ = _erc721;
// stages data
stages_[0].price = 10 finney;
stages_[0].softcap = 100;
stages_[0].hardcap = 300;
stages_[1].price = 20 finney;
stages_[1].softcap = 156;
stages_[1].hardcap = 400;
stages_[2].price = 32 finney;
stages_[2].softcap = 212;
stages_[2].hardcap = 500;
stages_[3].price = 45 finney;
stages_[3].softcap = 268;
stages_[3].hardcap = 600;
stages_[4].price = 58 finney;
stages_[4].softcap = 324;
stages_[4].hardcap = 700;
stages_[5].price = 73 finney;
stages_[5].softcap = 380;
stages_[5].hardcap = 800;
stages_[6].price = 87 finney;
stages_[6].softcap = 436;
stages_[6].hardcap = 900;
stages_[7].price = 102 finney;
stages_[7].softcap = 492;
stages_[7].hardcap = 1000;
stages_[8].price = 118 finney;
stages_[8].softcap = 548;
stages_[8].hardcap = 1100;
stages_[9].price = 129 finney;
stages_[9].softcap = 604;
stages_[9].hardcap = 1200;
}
/// fill the genomes data
function setStageGenomes(
uint8 _stage,
string _genome0,
string _genome1,
string _genome2,
string _genome3,
string _genome4
)
external controllerOnly
{
genomes_[_stage][0] = _genome0;
genomes_[_stage][1] = _genome1;
genomes_[_stage][2] = _genome2;
genomes_[_stage][3] = _genome3;
genomes_[_stage][4] = _genome4;
}
/// @dev Contract itself is non payable
function ()
public payable
{
revert();
}
// Modifiers ---------------------------------------------------------------
/// only from contract owner
modifier controllerOnly() {
require(msg.sender == CEOAddress, 'controller_only');
_;
}
/// only for active stage
modifier notOverOnly() {
require(isOver_ == false, 'notOver_only');
_;
}
// Getters -----------------------------------------------------------------
/// owner address
function getCEOAddress()
public view returns(address)
{
return CEOAddress;
}
/// counter from random number generator
function counter()
internal view returns(uint32)
{
return counter_;
}
// tokens sold by stage ...
function stageTokensBought(uint8 _stage)
public view returns(uint16)
{
return stages_[_stage].bought;
}
// stage softcap
function stageSoftcap(uint8 _stage)
public view returns(uint16)
{
return stages_[_stage].softcap;
}
/// stage hardcap
function stageHardcap(uint8 _stage)
public view returns(uint16)
{
return stages_[_stage].hardcap;
}
/// stage Start Date
function stageStartDate(uint8 _stage)
public view returns(uint)
{
return stages_[_stage].startDate;
}
/// stage Finish Date
function stageEndDate(uint8 _stage)
public view returns(uint)
{
return stages_[_stage].endDate;
}
/// stage token price
function stagePrice(uint _stage)
public view returns(uint)
{
return stages_[_stage].price;
}
// Genome Logic -----------------------------------------------------------------
/// within the prelase , the dragons are generated, which are the ancestors of the destiny
/// newborns have a high chance of mutation and are unlikely to be purebred
/// the player will have to collect the breed, crossing a lot of pets
/// In addition, you will need to pick up combat abilities
/// these characteristics are assigned to the pet when the dragon is imported to the game server.
function nextGenome()
internal returns(string)
{
uint8 n = getPseudoRandomNumber();
counter_ += 1;
return genomes_[stageIndex_][n];
}
function getPseudoRandomNumber()
internal view returns(uint8 index)
{
uint8 n = uint8(
keccak256(abi.encode(msg.sender, block.timestamp + counter_))
);
return n % TOKENS_PER_STAGE;
}
// PreSale Logic -----------------------------------------------------------------
/// Presale stage0 begin date set
/// presale start is possible only once
function setStartDate(uint32 _startDate)
external controllerOnly
{
require(stages_[0].startDate == 0, 'already_set');
stages_[0].startDate = _startDate;
stageStart_ = _startDate;
stageIndex_ = 0;
emit StageBegin(stageIndex_, stageStart_);
}
/// current stage number
/// switches to the next stage if the time has come
function stageIndex()
external view returns(uint8)
{
Stage memory stage = stages_[stageIndex_];
if (stage.endDate > 0 && stage.endDate <= now) {
return stageIndex_ + 1;
}
else {
return stageIndex_;
}
}
/// check whether the phase started
/// switch to the next stage, if necessary
function beforeBuy()
internal
{
if (stageStart_ == 0) {
revert('presale_not_started');
}
else if (stageStart_ > now) {
revert('stage_not_started');
}
Stage memory stage = stages_[stageIndex_];
if (stage.endDate > 0 && stage.endDate <= now)
{
stageIndex_ += 1;
stageStart_ = stages_[stageIndex_].startDate;
if (stageStart_ > now) {
revert('stage_not_started');
}
}
}
/// time to next midnight
function midnight()
public view returns(uint32)
{
uint32 tomorrow = uint32(now + 1 days);
uint32 remain = uint32(tomorrow % 1 days);
return tomorrow - remain;
}
/// buying a specified number of tokens
function buyTokens(uint16 numToBuy)
public payable notOverOnly returns(uint256[])
{
beforeBuy();
require(numToBuy > 0 && numToBuy <= 10, "numToBuy error");
Stage storage stage = stages_[stageIndex_];
require((stage.price * numToBuy) <= msg.value, 'price');
uint16 prevBought = stage.bought;
require(prevBought + numToBuy <= stage.hardcap, "have required tokens");
stage.bought += numToBuy;
uint256[] memory tokenIds = new uint256[](numToBuy);
bytes memory genomes = new bytes(numToBuy * 77);
uint32 genomeByteIndex = 0;
for(uint16 t = 0; t < numToBuy; t++)
{
string memory genome = nextGenome();
uint256 tokenId = EtherDragonsCore(erc721_).mintPresell(msg.sender, genome);
bytes memory genomeBytes = bytes(genome);
for(uint8 gi = 0; gi < genomeBytes.length; gi++) {
genomes[genomeByteIndex++] = genomeBytes[gi];
}
tokenIds[t] = tokenId;
}
// Transfer mint fee to the fund
bank_.transfer(address(this).balance);
if (stage.bought == stage.hardcap) {
stage.endDate = uint32(now);
stageStart_ = midnight() + 1 days + 1 seconds;
if (stageIndex_ < STAGES - 1) {
stageIndex_ += 1;
}
else {
isOver_ = true;
}
}
else if (stage.bought >= stage.softcap && prevBought < stage.softcap) {
stage.endDate = midnight() + 1 days;
if (stageIndex_ < STAGES - 1) {
stages_[stageIndex_ + 1].startDate = stage.endDate + 1 days;
}
}
emit TokensBought(msg.sender, tokenIds, genomes);
return tokenIds;
}
function currTime()
public view returns(uint)
{
return now;
}
/// stages data
function getStagesInfo()
public view returns (uint256[] prices, uint16[] softcaps, uint16[] hardcaps, uint16[] boughts)
{
prices = new uint256[](STAGES);
softcaps = new uint16[](STAGES);
hardcaps = new uint16[](STAGES);
boughts = new uint16[](STAGES);
for(uint8 s = 0; s < STAGES; s++) {
prices[s] = stages_[s].price;
softcaps[s] = stages_[s].softcap;
hardcaps[s] = stages_[s].hardcap;
boughts[s] = stages_[s].bought;
}
}
/// stages dates data
function getStagesBeginEnd()
public view returns (uint32[] startDates, uint32[] endDates)
{
startDates = new uint32[](STAGES);
endDates = new uint32[](STAGES);
for(uint8 s = 0; s < STAGES; s++) {
startDates[s] = stages_[s].startDate;
endDates[s] = stages_[s].endDate;
}
}
/// returns data which genomes can be purchased at the stage
function stageGenomes(uint8 _stage)
public view returns(byte[])
{
byte[] memory genomes = new byte[](uint16(TOKENS_PER_STAGE) * 77);
uint32 gbIndex = 0;
for(uint8 tokenIndex = 0; tokenIndex < TOKENS_PER_STAGE; tokenIndex++) {
bytes memory genomeBytes = bytes(genomes_[_stage][tokenIndex]);
for(uint8 gi = 0; gi < genomeBytes.length; gi++) {
genomes[gbIndex++] = genomeBytes[gi];
}
}
return genomes;
}
}
|
Number of tokens minted for bounty campaign
|
function totalBountyCount()
public view returns(uint256)
{
return bountyCount_;
}
| 5,397,228 |
./partial_match/1/0xB5E2C8fa04Ae426167490a0437c4F20556c9B07C/sources/AggKeyNonceConsumer.sol
|
Update KeyManager reference. Used if KeyManager contract is updated sigData Struct containing the signature data over the message to verify, signed by the aggregate key. keyManager New KeyManager's address omitChecks Allow the omission of the extra checks in a special case/ Check that the new KeyManager is a contract Allow the child to check compatibility with the new KeyManager
|
function updateKeyManager(
SigData calldata sigData,
IKeyManager keyManager,
bool omitChecks
)
external
override
nzAddr(address(keyManager))
consumesKeyNonce(sigData, keccak256(abi.encode(this.updateKeyManager.selector, keyManager, omitChecks)))
{
require(address(keyManager).code.length > 0);
_checkUpdateKeyManager(keyManager, omitChecks);
_keyManager = keyManager;
emit UpdatedKeyManager(address(keyManager));
}
| 2,813,187 |
./partial_match/1/0xa202D5B0892f2981bA86C981884cebA49B8AE096/sources/DigitalaxGenesisStaking.sol
|
Unstake without caring about rewards. EMERGENCY ONLY.
|
function emergencyUnstake(uint256 _tokenId) external {
require(
tokenOwner[_tokenId] == msg.sender,
"DigitalaxGenesisStaking._unstake: Sender must have staked tokenID"
);
_unstake(msg.sender, _tokenId);
emit EmergencyUnstake(msg.sender, _tokenId);
}
| 2,671,400 |
./partial_match/1/0xDB0655752A3CD23B8fD360aF596E71EE924c5253/sources/contracts/v2-migration/V2ToV3Rollover.sol
|
Callback function for flash loan. The caller of this function must be the lending pool. assets The ERC20 address that was borrowed in Flash Loan. amounts The amount that was borrowed in Flash Loan. feeAmounts The fees that are due to the lending pool. params The data to be executed after receiving Flash Loan./ verify this contract started the flash loan borrower must be set
|
function receiveFlashLoan(
IERC20[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata feeAmounts,
bytes calldata params
) external nonReentrant {
if (msg.sender != address(VAULT)) revert R_UnknownCaller(msg.sender, address(VAULT));
OperationData memory opData = abi.decode(params, (OperationData));
if (opData.borrower != borrower) revert R_UnknownBorrower(opData.borrower, borrower);
if (borrower == address(0)) revert R_ZeroAddress("borrower");
_executeOperation(assets, amounts, feeAmounts, opData);
}
| 4,068,944 |
./partial_match/421613/0xF5f25AC08eA0FA565Be14fBe1136f2B38b073ABA/sources/contracts/libraries/LibDiamond.sol
|
add new facet address if it does not exist
|
function replaceFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
DiamondStorage storage ds = diamondStorage();
require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)");
uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length);
if (selectorPosition == 0) {
addFacet(ds, _facetAddress);
}
for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
require(
oldFacetAddress != _facetAddress,
"LibDiamondCut: Can't replace function with same function"
);
removeFunction(ds, oldFacetAddress, selector);
addFunction(ds, selector, selectorPosition, _facetAddress);
selectorPosition++;
}
}
| 16,826,025 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ILootComponents.sol";
contract LootStats {
struct Item {
uint256 hp;
uint256 armor;
uint256 attack;
uint256 agility;
uint256 dexterity;
}
address public lootComponentsAddress;
constructor(address _lootComponentsAddress) {
lootComponentsAddress = _lootComponentsAddress;
}
function getWeaponStats(uint256 tokenId) public view returns (Item memory) {
ILootComponents components = ILootComponents(lootComponentsAddress);
uint256[5] memory weaponComponents = components.weaponComponents(
tokenId
);
uint256 attack = _getItemStat(weaponComponents, 3) + 2;
// Item memory weaponStats = _getTotalStat(
// weaponComponents,
// _getWeaponStats(weaponComponents[0])
// );
return Item(0, 0, attack, 0, 0);
}
function getAccessoryStats(uint256 tokenId)
public
view
returns (Item memory)
{
ILootComponents components = ILootComponents(lootComponentsAddress);
uint256[5] memory neckComponents = components.neckComponents(tokenId);
uint256[5] memory ringComponents = components.ringComponents(tokenId);
Item memory neckStats = _getAccessoryBonusStat(neckComponents);
Item memory ringStats = _getAccessoryBonusStat(ringComponents);
// Item memory neckStats = _getTotalStat(
// neckComponents,
// Item(0, 0, 0, 0, 0)
// );
// Item memory ringStats = _getTotalStat(
// ringComponents,
// Item(0, 0, 0, 0, 0)
// );
return
Item(
neckStats.hp + ringStats.hp,
neckStats.armor + ringStats.armor,
neckStats.attack + ringStats.attack,
neckStats.agility + ringStats.agility,
neckStats.dexterity + ringStats.dexterity
);
}
function _getAccessoryBonusStat(uint256[5] memory components)
internal
pure
returns (Item memory)
{
uint256 bonusStat = _getItemStat(components, 0);
uint256 hp = 0;
uint256 armor = 0;
uint256 attack = 0;
uint256 agility = 0;
uint256 dexterity = 0;
if (bonusStat < 1) {
hp += 5;
} else if (bonusStat < 2) {
dexterity += 3;
} else if (bonusStat < 3) {
agility += 3;
} else if (bonusStat < 4) {
attack += 3;
} else {
armor += 2;
}
return Item(hp, armor, attack, agility, dexterity);
}
function getArmorStats(uint256 tokenId) public view returns (Item memory) {
ILootComponents components = ILootComponents(lootComponentsAddress);
uint256[5] memory chestComponents = components.chestComponents(tokenId);
uint256[5] memory headComponents = components.headComponents(tokenId);
uint256[5] memory waistComponents = components.waistComponents(tokenId);
uint256[5] memory footComponents = components.footComponents(tokenId);
uint256[5] memory handComponents = components.handComponents(tokenId);
uint256 hp = _getItemStat(headComponents, 1) +
_getItemStat(waistComponents, 5);
uint256 armor = _getItemStat(chestComponents, 3);
uint256 agility = _getItemStat(footComponents, 2) + 1;
uint256 dexterity = _getItemStat(handComponents, 4) + 1;
return Item(hp, armor, 0, agility, dexterity);
// Item memory chestStats = _getTotalStat(
// chestComponents,
// Item(_getChestHpStat(chestComponents[0]), 0, 0, 0, 0)
// );
// Item memory headStats = _getTotalStat(
// headComponents,
// Item(0, _getHeadArmorStat(headComponents[0]), 0, 0, 0)
// );
// Item memory waistStats = _getTotalStat(
// waistComponents,
// Item(0, _getWaistArmorStat(waistComponents[0]), 0, 0, 0)
// );
// Item memory footStats = _getTotalStat(
// footComponents,
// Item(0, 0, 0, _getFootAgilityStat(footComponents[0]), 0)
// );
// Item memory handStats = _getTotalStat(
// handComponents,
// Item(0, 0, 0, 0, _getHandDexStat(handComponents[0]))
// );
// return
// Item(
// chestStats.hp +
// headStats.hp +
// waistStats.hp +
// footStats.hp +
// handStats.hp,
// chestStats.armor +
// headStats.armor +
// waistStats.armor +
// footStats.armor +
// handStats.armor,
// chestStats.attack +
// headStats.attack +
// waistStats.attack +
// footStats.attack +
// handStats.attack,
// chestStats.agility +
// headStats.agility +
// waistStats.agility +
// footStats.agility +
// handStats.agility,
// chestStats.dexterity +
// headStats.dexterity +
// waistStats.dexterity +
// footStats.dexterity +
// handStats.dexterity
// );
}
function _getItemStat(uint256[5] memory components, uint256 offset)
internal
pure
returns (uint256)
{
uint256 baseStat = (components[0] + offset) % 4;
if (components[1] > 0) {
baseStat += components[1] % 2;
}
if (components[2] > 0) {
baseStat += components[2] % 3;
}
if (components[4] > 0) {
baseStat++;
}
return baseStat;
}
// function _getTotalStat(uint256[5] memory components, Item memory baseStats)
// internal
// pure
// returns (Item memory)
// {
// Item memory suffixStats = _getSuffixBonusStats(components[1]);
// Item memory multipliers = _getExtraMultipliers(components);
// uint256 hp = suffixStats.hp == 0 ? 0 : suffixStats.hp + multipliers.hp;
// uint256 arm = suffixStats.armor == 0
// ? 0
// : suffixStats.armor + multipliers.armor;
// uint256 att = suffixStats.attack == 0
// ? 0
// : suffixStats.attack + multipliers.attack;
// uint256 agi = suffixStats.agility == 0
// ? 0
// : suffixStats.agility + multipliers.agility;
// uint256 dex = suffixStats.dexterity == 0
// ? 0
// : suffixStats.dexterity + multipliers.dexterity;
// return
// Item(
// baseStats.hp + hp,
// baseStats.armor + arm,
// baseStats.attack + att,
// baseStats.agility + agi,
// baseStats.dexterity + dex
// );
// }
// function _getExtraMultipliers(uint256[5] memory components)
// internal
// pure
// returns (Item memory)
// {
// if (components[3] > 0) {
// return Item(2, 2, 2, 2, 2);
// }
// if (components[2] > 0) {
// return Item(1, 1, 1, 1, 1);
// }
// return Item(0, 0, 0, 0, 0);
// }
// function _getSuffixBonusStats(uint256 suffix)
// internal
// pure
// returns (Item memory item)
// {
// // hp, armor, attack, agility, dexterity
// // <no suffix> // 0
// if (suffix == 0) {
// return Item(0, 0, 0, 0, 0);
// }
// // "of Power", // 1
// if (suffix == 1) {
// return Item(0, 0, 4, 0, 0);
// }
// // "of Giants", // 2
// if (suffix == 2) {
// return Item(2, 0, 1, 0, 0);
// }
// // "of Titans", // 3
// if (suffix == 3) {
// return Item(4, 0, 1, 0, 0);
// }
// // "of Skill", // 4
// if (suffix == 4) {
// return Item(0, 0, 1, 0, 4);
// }
// // "of Perfection", // 5
// if (suffix == 5) {
// return Item(1, 1, 1, 1, 2);
// }
// // "of Brilliance", // 6
// if (suffix == 6) {
// return Item(0, 0, 2, 1, 2);
// }
// // "of Enlightenment", // 7
// if (suffix == 7) {
// return Item(0, 1, 3, 0, 0);
// }
// // "of Protection", // 8
// if (suffix == 8) {
// return Item(5, 1, 0, 0, 0);
// }
// // "of Anger", // 9
// if (suffix == 9) {
// return Item(0, 0, 4, 0, 0);
// }
// // "of Rage", // 10
// if (suffix == 10) {
// return Item(0, 0, 3, 1, 0);
// }
// // "of Fury", // 11
// if (suffix == 11) {
// return Item(0, 0, 2, 2, 0);
// }
// // "of Vitriol", // 12
// if (suffix == 12) {
// return Item(0, 0, 0, 0, 5);
// }
// // "of the Fox", // 13
// if (suffix == 13) {
// return Item(0, 0, 1, 3, 2);
// }
// // "of Detection", // 14
// if (suffix == 14) {
// return Item(0, 0, 0, 0, 6);
// }
// // "of Reflection", // 15
// if (suffix == 15) {
// return Item(0, 1, 0, 1, 0);
// }
// // "of the Twins" // 16
// if (suffix == 16) {
// return Item(0, 0, 2, 4, 0);
// }
// }
// function _getChestHpStat(uint256 component)
// internal
// pure
// returns (uint256)
// {
// // "Divine Robe", // 0
// if (component == 0) {
// return 7;
// }
// // "Silk Robe", // 1
// if (component == 1) {
// return 2;
// }
// // "Linen Robe", // 2
// if (component == 2) {
// return 2;
// }
// // "Robe", // 3
// if (component == 3) {
// return 2;
// }
// // "Shirt", // 4
// if (component == 4) {
// return 1;
// }
// // "Demon Husk", // 5
// if (component == 5) {
// return 8;
// }
// // "Dragonskin Armor", // 6
// if (component == 6) {
// return 9;
// }
// // "Studded Leather Armor", // 7
// if (component == 7) {
// return 5;
// }
// // "Hard Leather Armor", // 8
// if (component == 8) {
// return 4;
// }
// // "Leather Armor", // 9
// if (component == 9) {
// return 3;
// }
// // "Holy Chestplate", // 10
// if (component == 10) {
// return 6;
// }
// // " ", // 11
// if (component == 11) {
// return 0;
// }
// // "Plate Mail", // 12
// if (component == 12) {
// return 7;
// }
// // "Chain Mail", // 13
// if (component == 13) {
// return 6;
// }
// // "Ring Mail" // 14
// if (component == 14) {
// return 6;
// }
// return 0;
// }
// function _getWeaponStats(uint256 component)
// internal
// pure
// returns (Item memory)
// {
// // hp, armor, attack, agility, dexterity
// // "Warhammer", // 0
// if (component == 0) {
// return Item(0, 0, 4, 0, 0);
// }
// // "Quarterstaff", // 1
// if (component == 1) {
// return Item(0, 0, 2, 1, 1);
// }
// // "Maul", // 2
// if (component == 2) {
// return Item(0, 0, 3, 0, 1);
// }
// // "Mace", // 3
// if (component == 3) {
// return Item(0, 0, 3, 1, 0);
// }
// // "Club", // 4
// if (component == 4) {
// return Item(0, 0, 2, 1, 0);
// }
// // "Katana", // 5
// if (component == 5) {
// return Item(0, 0, 4, 0, 2);
// }
// // "Falchion", // 6
// if (component == 6) {
// return Item(0, 0, 3, 1, 1);
// }
// // "Scimitar", // 7
// if (component == 7) {
// return Item(0, 0, 3, 0, 1);
// }
// // "Long Sword", // 8
// if (component == 8) {
// return Item(0, 0, 4, 0, 1);
// }
// // "Short Sword", // 9
// if (component == 9) {
// return Item(0, 0, 3, 1, 1);
// }
// // "Ghost Wand", // 10
// if (component == 10) {
// return Item(0, 0, 3, 0, 3);
// }
// // "Grave Wand", // 11
// if (component == 11) {
// return Item(0, 0, 2, 1, 2);
// }
// // "Bone Wand", // 12
// if (component == 12) {
// return Item(0, 0, 2, 1, 0);
// }
// // "Wand", // 13
// if (component == 13) {
// return Item(0, 0, 2, 0, 1);
// }
// // "Grimoire", // 14
// if (component == 14) {
// return Item(0, 0, 3, 0, 3);
// }
// // "Chronicle", // 15
// if (component == 15) {
// return Item(0, 0, 3, 0, 1);
// }
// // "Tome", // 16
// if (component == 16) {
// return Item(0, 0, 2, 0, 0);
// }
// // "Book" // 17
// if (component == 17) {
// return Item(0, 0, 1, 0, 0);
// }
// return Item(0, 0, 1, 0, 0);
// }
// function _getHeadArmorStat(uint256 component)
// internal
// pure
// returns (uint256)
// {
// // "Ancient Helm", // 0
// if (component == 0) {
// return 2;
// }
// // "Ornate Helm", // 1
// if (component == 1) {
// return 1;
// }
// // "Great Helm", // 2
// if (component == 2) {
// return 2;
// }
// // "Full Helm", // 3
// if (component == 3) {
// return 1;
// }
// // "Helm", // 4
// if (component == 4) {
// return 1;
// }
// // "Demon Crown", // 5
// if (component == 5) {
// return 2;
// }
// // "Dragon's Crown", // 6
// if (component == 6) {
// return 3;
// }
// // "War Cap", // 7
// if (component == 7) {
// return 2;
// }
// // "Leather Cap", // 8
// if (component == 8) {
// return 1;
// }
// // "Cap", // 9
// if (component == 9) {
// return 0;
// }
// // "Crown", // 10
// if (component == 10) {
// return 0;
// }
// // "Divine Hood", // 11
// if (component == 11) {
// return 2;
// }
// // "Silk Hood", // 12
// if (component == 12) {
// return 0;
// }
// // "Linen Hood", // 13
// if (component == 13) {
// return 0;
// }
// // "Hood" // 14
// if (component == 14) {
// return 0;
// }
// return 0;
// }
// function _getWaistArmorStat(uint256 component)
// public
// pure
// returns (uint256)
// {
// // "Ornate Belt", // 0
// if (component == 0) {
// return 0;
// }
// // "War Belt", // 1
// if (component == 1) {
// return 1;
// }
// // "Plated Belt", // 2
// if (component == 2) {
// return 1;
// }
// // "Mesh Belt", // 3
// if (component == 3) {
// return 1;
// }
// // "Heavy Belt", // 4
// if (component == 4) {
// return 1;
// }
// // "Demonhide Belt", // 5
// if (component == 5) {
// return 2;
// }
// // "Dragonskin Belt", // 6
// if (component == 6) {
// return 2;
// }
// // "Studded Leather Belt", // 7
// if (component == 7) {
// return 1;
// }
// // "Hard Leather Belt", // 8
// if (component == 8) {
// return 1;
// }
// // "Leather Belt", // 9
// if (component == 9) {
// return 1;
// }
// // "Brightsilk Sash", // 10
// if (component == 10) {
// return 0;
// }
// // "Silk Sash", // 11
// if (component == 11) {
// return 0;
// }
// // "Wool Sash", // 12
// if (component == 12) {
// return 0;
// }
// // "Linen Sash", // 13
// if (component == 13) {
// return 0;
// }
// // "Sash" // 14
// if (component == 14) {
// return 0;
// }
// return 0;
// }
// function _getFootAgilityStat(uint256 component)
// internal
// pure
// returns (uint256)
// {
// // "Holy Greaves", // 0
// if (component == 0) {
// return 2;
// }
// // "Ornate Greaves", // 1
// if (component == 1) {
// return 1;
// }
// // "Greaves", // 2
// if (component == 2) {
// return 1;
// }
// // "Chain Boots", // 3
// if (component == 3) {
// return 1;
// }
// // "Heavy Boots", // 4
// if (component == 4) {
// return 1;
// }
// // "Demonhide Boots", // 5
// if (component == 5) {
// return 2;
// }
// // "Dragonskin Boots", // 6
// if (component == 6) {
// return 3;
// }
// // "Studded Leather Boots", // 7
// if (component == 7) {
// return 1;
// }
// // "Hard Leather Boots", // 8
// if (component == 8) {
// return 1;
// }
// // "Leather Boots", // 9
// if (component == 9) {
// return 1;
// }
// // "Divine Slippers", // 10
// if (component == 10) {
// return 1;
// }
// // "Silk Slippers", // 11
// if (component == 11) {
// return 0;
// }
// // "Wool Shoes", // 12
// if (component == 12) {
// return 0;
// }
// // "Linen Shoes", // 13
// if (component == 13) {
// return 0;
// }
// // "Shoes" // 14
// if (component == 14) {
// return 1;
// }
// return 0;
// }
// function _getHandDexStat(uint256 component)
// internal
// pure
// returns (uint256)
// {
// // "Holy Gauntlets", // 0
// if (component == 0) {
// return 2;
// }
// // "Ornate Gauntlets", // 1
// if (component == 1) {
// return 1;
// }
// // "Gauntlets", // 2
// if (component == 2) {
// return 1;
// }
// // "Chain Gloves", // 3
// if (component == 3) {
// return 2;
// }
// // "Heavy Gloves", // 4
// if (component == 4) {
// return 2;
// }
// // "Demon's Hands", // 5
// if (component == 5) {
// return 3;
// }
// // "Dragonskin Gloves", // 6
// if (component == 6) {
// return 4;
// }
// // "Studded Leather Gloves", // 7
// if (component == 7) {
// return 2;
// }
// // "Hard Leather Gloves", // 8
// if (component == 8) {
// return 1;
// }
// // "Leather Gloves", // 9
// if (component == 9) {
// return 1;
// }
// // "Divine Gloves", // 10
// if (component == 10) {
// return 2;
// }
// // "Silk Gloves", // 11
// if (component == 11) {
// return 1;
// }
// // "Wool Gloves", // 12
// if (component == 12) {
// return 0;
// }
// // "Linen Gloves", // 13
// if (component == 13) {
// return 1;
// }
// // "Gloves" // 14
// if (component == 14) {
// return 1;
// }
// return 0;
// }
}
|
Item memory neckStats = _getTotalStat( neckComponents, Item(0, 0, 0, 0, 0) ); Item memory ringStats = _getTotalStat( ringComponents, Item(0, 0, 0, 0, 0) );
|
function getAccessoryStats(uint256 tokenId)
public
view
returns (Item memory)
{
ILootComponents components = ILootComponents(lootComponentsAddress);
uint256[5] memory neckComponents = components.neckComponents(tokenId);
uint256[5] memory ringComponents = components.ringComponents(tokenId);
Item memory neckStats = _getAccessoryBonusStat(neckComponents);
Item memory ringStats = _getAccessoryBonusStat(ringComponents);
return
Item(
neckStats.hp + ringStats.hp,
neckStats.armor + ringStats.armor,
neckStats.attack + ringStats.attack,
neckStats.agility + ringStats.agility,
neckStats.dexterity + ringStats.dexterity
);
}
| 12,882,696 |
// File: @openzeppelin\contracts\token\ERC20\IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.9;
pragma experimental ABIEncoderV2;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts\weth\IWETH.sol
/**
* @title IIdeaToken
* @author Alexander Schlindwein
*
* @dev Simplified interface for WETH
*/
interface IWETH {
function deposit() external payable;
function withdraw(uint wad) external;
}
// File: contracts\uniswap\IUniswapV2Factory.sol
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address);
}
// File: contracts\uniswap\IUniswapV2Router01.sol
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 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 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);
}
// File: contracts\uniswap\IUniswapV2Router02.sol
interface IUniswapV2Router02 is IUniswapV2Router01 {
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: contracts\core\interfaces\IIdeaToken.sol
/**
* @title IIdeaToken
* @author Alexander Schlindwein
*/
interface IIdeaToken is IERC20 {
function initialize(string calldata __name, address owner) external;
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
}
// File: contracts\core\nameVerifiers\IIdeaTokenNameVerifier.sol
/**
* @title IIdeaTokenNameVerifier
* @author Alexander Schlindwein
*
* Interface for token name verifiers
*/
interface IIdeaTokenNameVerifier {
function verifyTokenName(string calldata name) external pure returns (bool);
}
// File: contracts\core\interfaces\IIdeaTokenFactory.sol
/**
* @title IIdeaTokenFactory
* @author Alexander Schlindwein
*/
struct IDPair {
bool exists;
uint marketID;
uint tokenID;
}
struct TokenInfo {
bool exists;
uint id;
string name;
IIdeaToken ideaToken;
}
struct MarketDetails {
bool exists;
uint id;
string name;
IIdeaTokenNameVerifier nameVerifier;
uint numTokens;
uint baseCost;
uint priceRise;
uint hatchTokens;
uint tradingFeeRate;
uint platformFeeRate;
bool allInterestToPlatform;
}
interface IIdeaTokenFactory {
function addMarket(string calldata marketName, address nameVerifier,
uint baseCost, uint priceRise, uint hatchTokens,
uint tradingFeeRate, uint platformFeeRate, bool allInterestToPlatform) external;
function addToken(string calldata tokenName, uint marketID, address lister) external;
function isValidTokenName(string calldata tokenName, uint marketID) external view returns (bool);
function getMarketIDByName(string calldata marketName) external view returns (uint);
function getMarketDetailsByID(uint marketID) external view returns (MarketDetails memory);
function getMarketDetailsByName(string calldata marketName) external view returns (MarketDetails memory);
function getMarketDetailsByTokenAddress(address ideaToken) external view returns (MarketDetails memory);
function getNumMarkets() external view returns (uint);
function getTokenIDByName(string calldata tokenName, uint marketID) external view returns (uint);
function getTokenInfo(uint marketID, uint tokenID) external view returns (TokenInfo memory);
function getTokenIDPair(address token) external view returns (IDPair memory);
function setTradingFee(uint marketID, uint tradingFeeRate) external;
function setPlatformFee(uint marketID, uint platformFeeRate) external;
function setNameVerifier(uint marketID, address nameVerifier) external;
}
// File: contracts\core\interfaces\IIdeaTokenExchange.sol
/**
* @title IIdeaTokenExchange
* @author Alexander Schlindwein
*/
struct CostAndPriceAmounts {
uint total;
uint raw;
uint tradingFee;
uint platformFee;
}
interface IIdeaTokenExchange {
function sellTokens(address ideaToken, uint amount, uint minPrice, address recipient) external;
function getPriceForSellingTokens(address ideaToken, uint amount) external view returns (uint);
function getPricesForSellingTokens(MarketDetails memory marketDetails, uint supply, uint amount, bool feesDisabled) external pure returns (CostAndPriceAmounts memory);
function buyTokens(address ideaToken, uint amount, uint fallbackAmount, uint cost, address recipient) external;
function getCostForBuyingTokens(address ideaToken, uint amount) external view returns (uint);
function getCostsForBuyingTokens(MarketDetails memory marketDetails, uint supply, uint amount, bool feesDisabled) external pure returns (CostAndPriceAmounts memory);
function setTokenOwner(address ideaToken, address owner) external;
function setPlatformOwner(uint marketID, address owner) external;
function withdrawTradingFee() external;
function withdrawTokenInterest(address token) external;
function withdrawPlatformInterest(uint marketID) external;
function withdrawPlatformFee(uint marketID) external;
function getInterestPayable(address token) external view returns (uint);
function getPlatformInterestPayable(uint marketID) external view returns (uint);
function getPlatformFeePayable(uint marketID) external view returns (uint);
function getTradingFeePayable() external view returns (uint);
function setAuthorizer(address authorizer) external;
function isTokenFeeDisabled(address ideaToken) external view returns (bool);
function setTokenFeeKillswitch(address ideaToken, bool set) external;
}
// File: contracts\core\interfaces\IIdeaTokenVault.sol
/**
* @title IIdeaTokenVault
* @author Alexander Schlindwein
*/
struct LockedEntry {
uint lockedUntil;
uint lockedAmount;
}
interface IIdeaTokenVault {
function lock(address ideaToken, uint amount, uint duration, address recipient) external;
function withdraw(address ideaToken, uint[] calldata untils, address recipient) external;
function getLockedEntries(address ideaToken, address user, uint maxEntries) external view returns (LockedEntry[] memory);
}
// File: contracts\core\MultiAction.sol
/**
* @title MultiAction
* @author Alexander Schlindwein
*
* Allows to bundle multiple actions into one tx
*/
contract MultiAction {
// IdeaTokenExchange contract
IIdeaTokenExchange _ideaTokenExchange;
// IdeaTokenFactory contract
IIdeaTokenFactory _ideaTokenFactory;
// IdeaTokenVault contract
IIdeaTokenVault _ideaTokenVault;
// Dai contract
IERC20 public _dai;
// IUniswapV2Factory contract
IUniswapV2Factory public _uniswapV2Factory;
// IUniswapV2Router02 contract
IUniswapV2Router02 public _uniswapV2Router02;
// WETH contract
IWETH public _weth;
/**
* @param ideaTokenExchange The address of the IdeaTokenExchange contract
* @param ideaTokenFactory The address of the IdeaTokenFactory contract
* @param ideaTokenVault The address of the IdeaTokenVault contract
* @param dai The address of the Dai token
* @param uniswapV2Router02 The address of the UniswapV2Router02 contract
* @param weth The address of the WETH token
*/
constructor(address ideaTokenExchange,
address ideaTokenFactory,
address ideaTokenVault,
address dai,
address uniswapV2Router02,
address weth) public {
require(ideaTokenExchange != address(0) &&
ideaTokenFactory != address(0) &&
ideaTokenVault != address(0) &&
dai != address(0) &&
uniswapV2Router02 != address(0) &&
weth != address(0),
"invalid-params");
_ideaTokenExchange = IIdeaTokenExchange(ideaTokenExchange);
_ideaTokenFactory = IIdeaTokenFactory(ideaTokenFactory);
_ideaTokenVault = IIdeaTokenVault(ideaTokenVault);
_dai = IERC20(dai);
_uniswapV2Router02 = IUniswapV2Router02(uniswapV2Router02);
_uniswapV2Factory = IUniswapV2Factory(IUniswapV2Router02(uniswapV2Router02).factory());
_weth = IWETH(weth);
}
/**
* Converts inputCurrency to Dai on Uniswap and buys IdeaTokens
*
* @param inputCurrency The input currency
* @param ideaToken The IdeaToken to buy
* @param amount The amount of IdeaTokens to buy
* @param fallbackAmount The amount of IdeaTokens to buy if the original amount cannot be bought
* @param cost The maximum cost in input currency
* @param lockDuration The duration in seconds to lock the tokens
* @param recipient The recipient of the IdeaTokens
*/
function convertAndBuy(address inputCurrency,
address ideaToken,
uint amount,
uint fallbackAmount,
uint cost,
uint lockDuration,
address recipient) external payable {
IIdeaTokenExchange exchange = _ideaTokenExchange;
uint buyAmount = amount;
uint buyCost = exchange.getCostForBuyingTokens(ideaToken, amount);
uint requiredInput = getInputForOutputInternal(inputCurrency, address(_dai), buyCost);
if(requiredInput > cost) {
buyCost = exchange.getCostForBuyingTokens(ideaToken, fallbackAmount);
requiredInput = getInputForOutputInternal(inputCurrency, address(_dai), buyCost);
require(requiredInput <= cost, "slippage");
buyAmount = fallbackAmount;
}
convertAndBuyInternal(inputCurrency, ideaToken, requiredInput, buyAmount, buyCost, lockDuration, recipient);
}
/**
* Sells IdeaTokens and converts Dai to outputCurrency
*
* @param outputCurrency The output currency
* @param ideaToken The IdeaToken to sell
* @param amount The amount of IdeaTokens to sell
* @param minPrice The minimum price to receive for selling in outputCurrency
* @param recipient The recipient of the funds
*/
function sellAndConvert(address outputCurrency,
address ideaToken,
uint amount,
uint minPrice,
address payable recipient) external {
IIdeaTokenExchange exchange = _ideaTokenExchange;
IERC20 dai = _dai;
uint sellPrice = exchange.getPriceForSellingTokens(ideaToken, amount);
uint output = getOutputForInputInternal(address(dai), outputCurrency, sellPrice);
require(output >= minPrice, "slippage");
pullERC20Internal(ideaToken, msg.sender, amount);
exchange.sellTokens(ideaToken, amount, sellPrice, address(this));
convertInternal(address(dai), outputCurrency, sellPrice, output);
if(outputCurrency == address(0)) {
recipient.transfer(output);
} else {
require(IERC20(outputCurrency).transfer(recipient, output), "transfer");
}
}
/**
* Converts `inputCurrency` to Dai, adds a token and buys the added token
*
* @param tokenName The name for the new IdeaToken
* @param marketID The ID of the market where the new token will be added
* @param inputCurrency The input currency to use for the purchase of the added token
* @param amount The amount of IdeaTokens to buy
* @param fallbackAmount The amount of IdeaTokens to buy if the original amount cannot be bought
* @param cost The maximum cost in input currency
* @param lockDuration The duration in seconds to lock the tokens
* @param recipient The recipient of the IdeaTokens
*/
function convertAddAndBuy(string calldata tokenName,
uint marketID,
address inputCurrency,
uint amount,
uint fallbackAmount,
uint cost,
uint lockDuration,
address recipient) external payable {
IERC20 dai = _dai;
uint buyAmount = amount;
uint buyCost = getBuyCostFromZeroSupplyInternal(marketID, buyAmount);
uint requiredInput = getInputForOutputInternal(inputCurrency, address(dai), buyCost);
if(requiredInput > cost) {
buyCost = getBuyCostFromZeroSupplyInternal(marketID, fallbackAmount);
requiredInput = getInputForOutputInternal(inputCurrency, address(dai), buyCost);
require(requiredInput <= cost, "slippage");
buyAmount = fallbackAmount;
}
address ideaToken = addTokenInternal(tokenName, marketID);
convertAndBuyInternal(inputCurrency, ideaToken, requiredInput, buyAmount, buyCost, lockDuration, recipient);
}
/**
* Adds a token and buys it
*
* @param tokenName The name for the new IdeaToken
* @param marketID The ID of the market where the new token will be added
* @param amount The amount of IdeaTokens to buy
* @param lockDuration The duration in seconds to lock the tokens
* @param recipient The recipient of the IdeaTokens
*/
function addAndBuy(string calldata tokenName, uint marketID, uint amount, uint lockDuration, address recipient) external {
uint cost = getBuyCostFromZeroSupplyInternal(marketID, amount);
pullERC20Internal(address(_dai), msg.sender, cost);
address ideaToken = addTokenInternal(tokenName, marketID);
if(lockDuration > 0) {
buyAndLockInternal(ideaToken, amount, cost, lockDuration, recipient);
} else {
buyInternal(ideaToken, amount, cost, recipient);
}
}
/**
* Buys a IdeaToken and locks it in the IdeaTokenVault
*
* @param ideaToken The IdeaToken to buy
* @param amount The amount of IdeaTokens to buy
* @param fallbackAmount The amount of IdeaTokens to buy if the original amount cannot be bought
* @param cost The maximum cost in input currency
* @param recipient The recipient of the IdeaTokens
*/
function buyAndLock(address ideaToken, uint amount, uint fallbackAmount, uint cost, uint lockDuration, address recipient) external {
IIdeaTokenExchange exchange = _ideaTokenExchange;
uint buyAmount = amount;
uint buyCost = exchange.getCostForBuyingTokens(ideaToken, amount);
if(buyCost > cost) {
buyCost = exchange.getCostForBuyingTokens(ideaToken, fallbackAmount);
require(buyCost <= cost, "slippage");
buyAmount = fallbackAmount;
}
pullERC20Internal(address(_dai), msg.sender, buyCost);
buyAndLockInternal(ideaToken, buyAmount, buyCost, lockDuration, recipient);
}
/**
* Converts `inputCurrency` to Dai on Uniswap and buys an IdeaToken, optionally locking it in the IdeaTokenVault
*
* @param inputCurrency The input currency to use
* @param ideaToken The IdeaToken to buy
* @param input The amount of `inputCurrency` to sell
* @param amount The amount of IdeaTokens to buy
* @param cost The cost in Dai for purchasing `amount` IdeaTokens
* @param lockDuration The duration in seconds to lock the tokens
* @param recipient The recipient of the IdeaTokens
*/
function convertAndBuyInternal(address inputCurrency, address ideaToken, uint input, uint amount, uint cost, uint lockDuration, address recipient) internal {
if(inputCurrency != address(0)) {
pullERC20Internal(inputCurrency, msg.sender, input);
}
convertInternal(inputCurrency, address(_dai), input, cost);
if(lockDuration > 0) {
buyAndLockInternal(ideaToken, amount, cost, lockDuration, recipient);
} else {
buyInternal(ideaToken, amount, cost, recipient);
}
/*
If the user has paid with ETH and we had to fallback there will be ETH left.
Refund the remaining ETH to the user.
*/
if(address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/**
* Buys and locks an IdeaToken in the IdeaTokenVault
*
* @param ideaToken The IdeaToken to buy
* @param amount The amount of IdeaTokens to buy
* @param cost The cost in Dai for the purchase of `amount` IdeaTokens
* @param recipient The recipient of the locked IdeaTokens
*/
function buyAndLockInternal(address ideaToken, uint amount, uint cost, uint lockDuration, address recipient) internal {
IIdeaTokenVault vault = _ideaTokenVault;
buyInternal(ideaToken, amount, cost, address(this));
require(IERC20(ideaToken).approve(address(vault), amount), "approve");
vault.lock(ideaToken, amount, lockDuration, recipient);
}
/**
* Buys an IdeaToken
*
* @param ideaToken The IdeaToken to buy
* @param amount The amount of IdeaTokens to buy
* @param cost The cost in Dai for the purchase of `amount` IdeaTokens
* @param recipient The recipient of the bought IdeaTokens
*/
function buyInternal(address ideaToken, uint amount, uint cost, address recipient) internal {
IIdeaTokenExchange exchange = _ideaTokenExchange;
require(_dai.approve(address(exchange), cost), "approve");
exchange.buyTokens(ideaToken, amount, amount, cost, recipient);
}
/**
* Adds a new IdeaToken
*
* @param tokenName The name of the new token
* @param marketID The ID of the market where the new token will be added
*
* @return The address of the new IdeaToken
*/
function addTokenInternal(string memory tokenName, uint marketID) internal returns (address) {
IIdeaTokenFactory factory = _ideaTokenFactory;
factory.addToken(tokenName, marketID, msg.sender);
return address(factory.getTokenInfo(marketID, factory.getTokenIDByName(tokenName, marketID) ).ideaToken);
}
/**
* Transfers ERC20 from an address to this contract
*
* @param token The ERC20 token to transfer
* @param from The address to transfer from
* @param amount The amount of tokens to transfer
*/
function pullERC20Internal(address token, address from, uint amount) internal {
require(IERC20(token).allowance(from, address(this)) >= amount, "insufficient-allowance");
require(IERC20(token).transferFrom(from, address(this), amount), "transfer");
}
/**
* Returns the cost for buying IdeaTokens on a given market from zero supply
*
* @param marketID The ID of the market on which the IdeaToken is listed
* @param amount The amount of IdeaTokens to buy
*
* @return The cost for buying IdeaTokens on a given market from zero supply
*/
function getBuyCostFromZeroSupplyInternal(uint marketID, uint amount) internal view returns (uint) {
MarketDetails memory marketDetails = _ideaTokenFactory.getMarketDetailsByID(marketID);
require(marketDetails.exists, "invalid-market");
return _ideaTokenExchange.getCostsForBuyingTokens(marketDetails, 0, amount, false).total;
}
/**
* Returns the required input to get a given output from an Uniswap swap
*
* @param inputCurrency The input currency
* @param outputCurrency The output currency
* @param outputAmount The desired output amount
*
* @return The required input to get a `outputAmount` from an Uniswap swap
*/
function getInputForOutputInternal(address inputCurrency, address outputCurrency, uint outputAmount) internal view returns (uint) {
address[] memory path = getPathInternal(inputCurrency, outputCurrency);
return _uniswapV2Router02.getAmountsIn(outputAmount, path)[0];
}
/**
* Returns the output for a given input for an Uniswap swap
*
* @param inputCurrency The input currency
* @param outputCurrency The output currency
* @param inputAmount The desired input amount
*
* @return The output for `inputAmount` for an Uniswap swap
*/
function getOutputForInputInternal(address inputCurrency, address outputCurrency, uint inputAmount) internal view returns (uint) {
address[] memory path = getPathInternal(inputCurrency, outputCurrency);
uint[] memory amountsOut = _uniswapV2Router02.getAmountsOut(inputAmount, path);
return amountsOut[amountsOut.length - 1];
}
/**
* Returns the Uniswap path from `inputCurrency` to `outputCurrency`
*
* @param inputCurrency The input currency
* @param outputCurrency The output currency
*
* @return The Uniswap path from `inputCurrency` to `outputCurrency`
*/
function getPathInternal(address inputCurrency, address outputCurrency) internal view returns (address[] memory) {
address wethAddress = address(_weth);
address updatedInputCurrency = inputCurrency == address(0) ? wethAddress : inputCurrency;
address updatedOutputCurrency = outputCurrency == address(0) ? wethAddress : outputCurrency;
IUniswapV2Factory uniswapFactory = _uniswapV2Factory;
if(uniswapFactory.getPair(updatedInputCurrency, updatedOutputCurrency) != address(0)) {
// Direct path exists
address[] memory path = new address[](2);
path[0] = updatedInputCurrency;
path[1] = updatedOutputCurrency;
return path;
}
// Direct path does not exist
// Check for 3-hop path: input -> weth -> output
require(uniswapFactory.getPair(updatedInputCurrency, wethAddress) != address(0) &&
uniswapFactory.getPair(wethAddress, updatedOutputCurrency) != address(0),
"no-path");
// 3-hop path exists
address[] memory path = new address[](3);
path[0] = updatedInputCurrency;
path[1] = wethAddress;
path[2] = updatedOutputCurrency;
return path;
}
/**
* Converts from `inputCurrency` to `outputCurrency` using Uniswap
*
* @param inputCurrency The input currency
* @param outputCurrency The output currency
* @param inputAmount The input amount
* @param outputAmount The output amount
*/
function convertInternal(address inputCurrency, address outputCurrency, uint inputAmount, uint outputAmount) internal {
IWETH weth = _weth;
IUniswapV2Router02 router = _uniswapV2Router02;
address[] memory path = getPathInternal(inputCurrency, outputCurrency);
IERC20 inputERC20;
if(inputCurrency == address(0)) {
// If the input is ETH we convert to WETH
weth.deposit{value: inputAmount}();
inputERC20 = IERC20(address(weth));
} else {
inputERC20 = IERC20(inputCurrency);
}
require(inputERC20.approve(address(router), inputAmount), "router-approve");
router.swapExactTokensForTokensSupportingFeeOnTransferTokens(inputAmount,
outputAmount,
path,
address(this),
now + 1);
if(outputCurrency == address(0)) {
// If the output is ETH we withdraw from WETH
weth.withdraw(outputAmount);
}
}
/**
* Fallback required for WETH withdraw. Fails if sender is not WETH contract
*/
receive() external payable {
require(msg.sender == address(_weth));
}
}
|
Converts inputCurrency to Dai on Uniswap and buys IdeaTokens inputCurrency The input currency ideaToken The IdeaToken to buy amount The amount of IdeaTokens to buy fallbackAmount The amount of IdeaTokens to buy if the original amount cannot be bought cost The maximum cost in input currency lockDuration The duration in seconds to lock the tokens recipient The recipient of the IdeaTokens/
|
function convertAndBuy(address inputCurrency,
address ideaToken,
uint amount,
uint fallbackAmount,
uint cost,
uint lockDuration,
address recipient) external payable {
IIdeaTokenExchange exchange = _ideaTokenExchange;
uint buyAmount = amount;
uint buyCost = exchange.getCostForBuyingTokens(ideaToken, amount);
uint requiredInput = getInputForOutputInternal(inputCurrency, address(_dai), buyCost);
if(requiredInput > cost) {
buyCost = exchange.getCostForBuyingTokens(ideaToken, fallbackAmount);
requiredInput = getInputForOutputInternal(inputCurrency, address(_dai), buyCost);
require(requiredInput <= cost, "slippage");
buyAmount = fallbackAmount;
}
convertAndBuyInternal(inputCurrency, ideaToken, requiredInput, buyAmount, buyCost, lockDuration, recipient);
}
| 410,147 |
pragma solidity ^0.4.23;
/**xxp
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20Basic {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) internal allowed;
// store tokens
mapping(address => uint256) balances;
// uint256 public totalSupply;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
*batch transfer token for a list of specified addresses
* @param _toList The list of addresses to transfer to.
* @param _tokensList The list of amount to be transferred.
*/
function batchTransfer(address[] _toList, uint256[] _tokensList) public returns (bool) {
require(_toList.length <= 100);
require(_toList.length == _tokensList.length);
uint256 sum = 0;
for (uint32 index = 0; index < _tokensList.length; index++) {
sum = sum.add(_tokensList[index]);
}
// if the sender doenst have enough balance then stop
require (balances[msg.sender] >= sum);
for (uint32 i = 0; i < _toList.length; i++) {
transfer(_toList[i],_tokensList[i]);
}
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is StandardToken,Ownable {
using SafeMath for uint256;
event AddToVestMap(address vestcount);
event DelFromVestMap(address vestcount);
event Released(address vestcount,uint256 amount);
event Revoked(address vestcount);
struct tokenToVest{
bool exist;
uint256 start;
uint256 cliff;
uint256 duration;
uint256 torelease;
uint256 released;
}
//key is the account to vest
mapping (address=>tokenToVest) vestToMap;
/**
* @dev Add one account to the vest Map
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _torelease delc count to release
*/
function addToVestMap(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _torelease
) public onlyOwner{
require(_beneficiary != address(0));
require(_cliff <= _duration);
require(_start > block.timestamp);
require(!vestToMap[_beneficiary].exist);
vestToMap[_beneficiary] = tokenToVest(true,_start,_start.add(_cliff),_duration,
_torelease,uint256(0));
emit AddToVestMap(_beneficiary);
}
/**
* @dev del One account to the vest Map
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
*/
function delFromVestMap(
address _beneficiary
) public onlyOwner{
require(_beneficiary != address(0));
require(vestToMap[_beneficiary].exist);
delete vestToMap[_beneficiary];
emit DelFromVestMap(_beneficiary);
}
/**
* @notice Transfers vested tokens to beneficiary.
*/
function release(address _beneficiary) public {
tokenToVest storage value = vestToMap[_beneficiary];
require(value.exist);
uint256 unreleased = releasableAmount(_beneficiary);
require(unreleased > 0);
require(unreleased + value.released <= value.torelease);
vestToMap[_beneficiary].released = vestToMap[_beneficiary].released.add(unreleased);
transfer(_beneficiary, unreleased);
emit Released(_beneficiary,unreleased);
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
*/
function releasableAmount(address _beneficiary) public view returns (uint256) {
return vestedAmount(_beneficiary).sub(vestToMap[_beneficiary].released);
}
/**
* @dev Calculates the amount that has already vested.
*/
function vestedAmount(address _beneficiary) public view returns (uint256) {
tokenToVest storage value = vestToMap[_beneficiary];
//uint256 currentBalance = balanceOf(_beneficiary);
uint256 totalBalance = value.torelease;
if (block.timestamp < value.cliff) {
return 0;
} else if (block.timestamp >= value.start.add(value.duration)) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(value.start)).div(value.duration);
}
}
}
/**
* @title Pausable token
*
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is TokenVesting, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function batchTransfer(address[] _toList, uint256[] _tokensList) public whenNotPaused returns (bool) {
return super.batchTransfer(_toList, _tokensList);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function release(address _beneficiary) public whenNotPaused{
super.release(_beneficiary);
}
}
/*
* @title DELCToken
*/
contract DELCToken is BurnableToken, MintableToken, PausableToken {
// Public variables of the token
string public name;
string public symbol;
// decimals is the strongly suggested default, avoid changing it
uint8 public decimals;
constructor() public {
name = "DELC Relation Person Token";
symbol = "DELC";
decimals = 18;
totalSupply = 10000000000 * 10 ** uint256(decimals);
// Allocate initial balance to the owner
balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
// transfer balance to owner
//function withdrawEther() onlyOwner public {
// owner.transfer(this.balance);
//}
// can accept ether
//function() payable public {
//}
}
|
Calculates the amount that has already vested./uint256 currentBalance = balanceOf(_beneficiary);
|
function vestedAmount(address _beneficiary) public view returns (uint256) {
tokenToVest storage value = vestToMap[_beneficiary];
uint256 totalBalance = value.torelease;
if (block.timestamp < value.cliff) {
return 0;
return totalBalance;
return totalBalance.mul(block.timestamp.sub(value.start)).div(value.duration);
}
}
| 10,987,965 |
./partial_match/1/0x09a516356F393442BA03AC1eEBE12479c2b5819e/sources/contracts/BallsLife/BallIsLife.sol
|
Changed visibility of burn to external as per good practices
|
function burn(uint256 amount) external {
require(amount != 0);
require(amount <= balances[msg.sender]);
_totalSupply = SafeMath.sub(_totalSupply, amount);
balances[msg.sender] = SafeMath.sub(balances[msg.sender], amount);
emit Transfer(msg.sender, address(0), amount);
}
| 3,615,220 |
pragma solidity 0.5.16;
import "../../base/snx-base/interfaces/SNXRewardInterface.sol";
import "../../base/snx-base/SNXRewardStrategy.sol";
contract FloatStrategyMainnet_WBTC is SNXRewardStrategy {
address public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address public wbtc = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
address public bank = address(0x24A6A37576377F63f194Caa5F518a60f45b42921);
address public rewardPoolAddr = address(0xE41F9FAbee859C4E6D248E9442c822F09742228a);
address public constant sushiswapRouterAddress = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); //BANK LP is on sushi
constructor(
address _storage,
address _vault
)
SNXRewardStrategy(_storage, wbtc, _vault, bank, sushiswapRouterAddress)
public {
rewardPool = SNXRewardInterface(rewardPoolAddr);
liquidationPath = [bank, weth, wbtc];
}
}
pragma solidity 0.5.16;
interface SNXRewardInterface {
function withdraw(uint) external;
function getReward() external;
function stake(uint) external;
function balanceOf(address) external view returns (uint256);
function earned(address account) external view returns (uint256);
function exit() external;
}
pragma solidity 0.5.16;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/SNXRewardInterface.sol";
import "../StrategyBase.sol";
import "../interface/uniswap/IUniswapV2Router02.sol";
contract SNXRewardStrategy is StrategyBase {
using SafeMath for uint256;
using SafeERC20 for IERC20;
bool pausedInvesting = false; // When this flag is true, the strategy will not be able to invest. But users should be able to withdraw.
bool getRewardWhenExit = true;
SNXRewardInterface public rewardPool;
address public rewardToken;
address[] public liquidationPath;
// This is only used in `investAllUnderlying()`
// The user can still freely withdraw from the strategy
modifier onlyNotPausedInvesting() {
require(!pausedInvesting, "Action blocked as the strategy is in emergency state");
_;
}
constructor(
address _storage,
address _underlying,
address _vault,
address _rewardToken,
address _uniswapRouterAddress
)
StrategyBase(_storage, _underlying, _vault, _rewardToken, _uniswapRouterAddress)
public {
rewardToken = _rewardToken;
}
function depositArbCheck() public view returns(bool) {
return true;
}
/*
* In case there are some issues discovered about the pool or underlying asset
* Governance can exit the pool properly
* The function is only used for emergency to exit the pool
*/
function emergencyExit() public onlyGovernance {
if(getRewardWhenExit){
rewardPool.exit();
} else {
rewardPool.withdraw(rewardPool.balanceOf(address(this)));
}
pausedInvesting = true;
}
/*
* Resumes the ability to invest into the underlying reward pools
*/
function continueInvesting() public onlyGovernance {
pausedInvesting = false;
}
/**
* Sets the route for liquidating the reward token to the underlying token
*/
function setLiquidationPath(address[] memory _newPath) public onlyGovernance {
liquidationPath = _newPath;
}
// We assume that all the tradings can be done on Uniswap
function _liquidateReward() internal {
uint256 rewardAmount = IERC20(rewardToken).balanceOf(address(this));
if (rewardAmount > 0 // we have tokens to swap
&& liquidationPath.length > 1 // and we have a route to do the swap
) {
notifyProfitInRewardToken(rewardAmount);
rewardAmount = IERC20(rewardToken).balanceOf(address(this));
// we can accept 1 as minimum because this is called only by a trusted role
uint256 amountOutMin = 1;
IERC20(rewardToken).safeApprove(uniswapRouterV2, 0);
IERC20(rewardToken).safeApprove(uniswapRouterV2, rewardAmount);
IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens(
rewardAmount,
amountOutMin,
liquidationPath,
address(this),
block.timestamp
);
}
}
/*
* Stakes everything the strategy holds into the reward pool
*/
function investAllUnderlying() internal onlyNotPausedInvesting {
// this check is needed, because most of the SNX reward pools will revert if
// you try to stake(0).
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if(underlyingBalance > 0) {
IERC20(underlying).safeApprove(address(rewardPool), 0);
IERC20(underlying).safeApprove(address(rewardPool), underlyingBalance);
rewardPool.stake(underlyingBalance);
}
}
/*
* Withdraws all the asset to the vault
*/
function withdrawAllToVault() public restricted {
if (address(rewardPool) != address(0)) {
if (rewardPool.balanceOf(address(this)) > 0) {
rewardPool.exit();
}
}
_liquidateReward();
if (IERC20(underlying).balanceOf(address(this)) > 0) {
IERC20(underlying).safeTransfer(vault, IERC20(underlying).balanceOf(address(this)));
}
}
/*
* Withdraws all the asset to the vault
*/
function withdrawToVault(uint256 amount) public restricted {
// Typically there wouldn't be any amount here
// however, it is possible because of the emergencyExit
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if(amount > underlyingBalance){
// While we have the check above, we still using SafeMath below
// for the peace of mind (in case something gets changed in between)
uint256 needToWithdraw = amount.sub(underlyingBalance);
rewardPool.withdraw(Math.min(rewardPool.balanceOf(address(this)), needToWithdraw));
}
IERC20(underlying).safeTransfer(vault, amount);
}
/*
* Note that we currently do not have a mechanism here to include the
* amount of reward that is accrued.
*/
function investedUnderlyingBalance() external view returns (uint256) {
if (address(rewardPool) == address(0)) {
return IERC20(underlying).balanceOf(address(this));
}
// Adding the amount locked in the reward pool and the amount that is somehow in this contract
// both are in the units of "underlying"
// The second part is needed because there is the emergency exit mechanism
// which would break the assumption that all the funds are always inside of the reward pool
return rewardPool.balanceOf(address(this)).add(IERC20(underlying).balanceOf(address(this)));
}
/*
* Governance or Controller can claim coins that are somehow transferred into the contract
* Note that they cannot come in take away coins that are used and defined in the strategy itself
* Those are protected by the "unsalvagableTokens". To check, see where those are being flagged.
*/
function salvage(address recipient, address token, uint256 amount) external onlyControllerOrGovernance {
// To make sure that governance cannot come in and take away the coins
require(!unsalvagableTokens[token], "token is defined as not salvagable");
IERC20(token).safeTransfer(recipient, amount);
}
/*
* Get the reward, sell it in exchange for underlying, invest what you got.
* It's not much, but it's honest work.
*
* Note that although `onlyNotPausedInvesting` is not added here,
* calling `investAllUnderlying()` affectively blocks the usage of `doHardWork`
* when the investing is being paused by governance.
*/
function doHardWork() external onlyNotPausedInvesting restricted {
rewardPool.getReward();
_liquidateReward();
investAllUnderlying();
}
}
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.5.16;
import "hardhat/console.sol";
import "./inheritance/RewardTokenProfitNotifier.sol";
import "./interface/IStrategy.sol";
contract StrategyBase is IStrategy, RewardTokenProfitNotifier {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event ProfitsNotCollected(address);
event Liquidating(address, uint256);
address public underlying;
address public vault;
mapping (address => bool) public unsalvagableTokens;
address public uniswapRouterV2;
modifier restricted() {
require(msg.sender == vault || msg.sender == address(controller()) || msg.sender == address(governance()),
"The sender has to be the controller or vault or governance");
_;
}
constructor(
address _storage,
address _underlying,
address _vault,
address _rewardToken,
address _uniswap
) RewardTokenProfitNotifier(_storage, _rewardToken) public {
underlying = _underlying;
vault = _vault;
unsalvagableTokens[_rewardToken] = true;
unsalvagableTokens[_underlying] = true;
uniswapRouterV2 = _uniswap;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 {
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);
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;
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// 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));
}
}
pragma solidity 0.5.16;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interface/IController.sol";
import "../interface/IFeeRewardForwarderV6.sol";
import "./Controllable.sol";
contract RewardTokenProfitNotifier is Controllable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public profitSharingNumerator;
uint256 public profitSharingDenominator;
address public rewardToken;
constructor(
address _storage,
address _rewardToken
) public Controllable(_storage){
rewardToken = _rewardToken;
// persist in the state for immutability of the fee
profitSharingNumerator = 30; //IController(controller()).profitSharingNumerator();
profitSharingDenominator = 100; //IController(controller()).profitSharingDenominator();
require(profitSharingNumerator < profitSharingDenominator, "invalid profit share");
}
event ProfitLogInReward(uint256 profitAmount, uint256 feeAmount, uint256 timestamp);
event ProfitAndBuybackLog(uint256 profitAmount, uint256 feeAmount, uint256 timestamp);
function notifyProfitInRewardToken(uint256 _rewardBalance) internal {
if( _rewardBalance > 0 ){
uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator);
emit ProfitLogInReward(_rewardBalance, feeAmount, block.timestamp);
IERC20(rewardToken).safeApprove(controller(), 0);
IERC20(rewardToken).safeApprove(controller(), feeAmount);
IController(controller()).notifyFee(
rewardToken,
feeAmount
);
} else {
emit ProfitLogInReward(0, 0, block.timestamp);
}
}
function notifyProfitAndBuybackInRewardToken(uint256 _rewardBalance, address pool, uint256 _buybackRatio) internal {
if( _rewardBalance > 0 ){
uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator);
address forwarder = IController(controller()).feeRewardForwarder();
emit ProfitAndBuybackLog(_rewardBalance, feeAmount, block.timestamp);
IERC20(rewardToken).safeApprove(forwarder, 0);
IERC20(rewardToken).safeApprove(forwarder, _rewardBalance);
IFeeRewardForwarderV6(forwarder).notifyFeeAndBuybackAmounts(
rewardToken,
feeAmount,
pool,
_rewardBalance.sub(feeAmount).mul(_buybackRatio).div(10000)
);
} else {
emit ProfitAndBuybackLog(0, 0, block.timestamp);
}
}
}
pragma solidity 0.5.16;
interface IStrategy {
function unsalvagableTokens(address tokens) external view returns (bool);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function vault() external view returns (address);
function withdrawAllToVault() external;
function withdrawToVault(uint256 amount) external;
function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch()
// should only be called by controller
function salvage(address recipient, address token, uint256 amount) external;
function doHardWork() external;
function depositArbCheck() external view returns(bool);
}
pragma solidity 0.5.16;
interface IController {
// [Grey list]
// An EOA can safely interact with the system no matter what.
// If you're using Metamask, you're using an EOA.
// Only smart contracts may be affected by this grey list.
//
// This contract will not be able to ban any EOA from the system
// even if an EOA is being added to the greyList, he/she will still be able
// to interact with the whole system as if nothing happened.
// Only smart contracts will be affected by being added to the greyList.
// This grey list is only used in Vault.sol, see the code there for reference
function greyList(address _target) external view returns(bool);
function addVaultAndStrategy(address _vault, address _strategy) external;
function doHardWork(address _vault) external;
function hasVault(address _vault) external returns(bool);
function salvage(address _token, uint256 amount) external;
function salvageStrategy(address _strategy, address _token, uint256 amount) external;
function notifyFee(address _underlying, uint256 fee) external;
function profitSharingNumerator() external view returns (uint256);
function profitSharingDenominator() external view returns (uint256);
function feeRewardForwarder() external view returns(address);
function setFeeRewardForwarder(address _value) external;
}
pragma solidity 0.5.16;
interface IFeeRewardForwarderV6 {
function poolNotifyFixedTarget(address _token, uint256 _amount) external;
function notifyFeeAndBuybackAmounts(uint256 _feeAmount, address _pool, uint256 _buybackAmount) external;
function notifyFeeAndBuybackAmounts(address _token, uint256 _feeAmount, address _pool, uint256 _buybackAmount) external;
function profitSharingPool() external view returns (address);
function configureLiquidation(address[] calldata _path, bytes32[] calldata _dexes) external;
}
pragma solidity 0.5.16;
import "./Governable.sol";
contract Controllable is Governable {
constructor(address _storage) Governable(_storage) public {
}
modifier onlyController() {
require(store.isController(msg.sender), "Not a controller");
_;
}
modifier onlyControllerOrGovernance(){
require((store.isController(msg.sender) || store.isGovernance(msg.sender)),
"The caller must be controller or governance");
_;
}
function controller() public view returns (address) {
return store.controller();
}
}
pragma solidity 0.5.16;
import "./Storage.sol";
contract Governable {
Storage public store;
constructor(address _store) public {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
modifier onlyGovernance() {
require(store.isGovernance(msg.sender), "Not governance");
_;
}
function setStorage(address _store) public onlyGovernance {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
function governance() public view returns (address) {
return store.governance();
}
}
pragma solidity 0.5.16;
contract Storage {
address public governance;
address public controller;
constructor() public {
governance = msg.sender;
}
modifier onlyGovernance() {
require(isGovernance(msg.sender), "Not governance");
_;
}
function setGovernance(address _governance) public onlyGovernance {
require(_governance != address(0), "new governance shouldn't be empty");
governance = _governance;
}
function setController(address _controller) public onlyGovernance {
require(_controller != address(0), "new controller shouldn't be empty");
controller = _controller;
}
function isGovernance(address account) public view returns (bool) {
return account == governance;
}
function isController(address account) public view returns (bool) {
return account == controller;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
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);
}
|
Withdraws all the asset to the vault/
|
function withdrawAllToVault() public restricted {
if (address(rewardPool) != address(0)) {
if (rewardPool.balanceOf(address(this)) > 0) {
rewardPool.exit();
}
}
_liquidateReward();
if (IERC20(underlying).balanceOf(address(this)) > 0) {
IERC20(underlying).safeTransfer(vault, IERC20(underlying).balanceOf(address(this)));
}
}
| 11,869,753 |
pragma solidity 0.5.6;
// Copyright BigchainDB GmbH and Ocean Protocol contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import './Condition.sol';
/**
* @title Hash Lock Condition
* @author Ocean Protocol Team
*
* @dev Implementation of the Hash Lock Condition
*
* For more information, please refer the following link
* https://github.com/oceanprotocol/OEPs/issues/122
* TODO: update the OEP link
*/
contract HashLockCondition is Condition {
/**
* @notice initialize init the
* contract with the following parameters
* @dev this function is called only once during the contract
* initialization.
* @param _owner contract's owner account address
* @param _conditionStoreManagerAddress condition store manager address
*/
function initialize(
address _owner,
address _conditionStoreManagerAddress
)
external
initializer()
{
require(
_conditionStoreManagerAddress != address(0),
'Invalid address'
);
Ownable.initialize(_owner);
conditionStoreManager = ConditionStoreManager(
_conditionStoreManagerAddress
);
}
/**
* @notice hashValues generates the hash of condition inputs
* with the following parameters
* @param _preimage refers uint value of the hash pre-image.
* @return bytes32 hash of all these values
*/
function hashValues(uint256 _preimage)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_preimage));
}
/**
* @notice hashValues generates the hash of condition inputs
* with the following parameters
* @param _preimage refers string value of the hash pre-image.
* @return bytes32 hash of all these values
*/
function hashValues(string memory _preimage)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_preimage));
}
/**
* @notice hashValues generates the hash of condition inputs
* with the following parameters
* @param _preimage refers bytes32 value of the hash pre-image.
* @return bytes32 hash of all these values
*/
function hashValues(bytes32 _preimage)
public
pure
returns
(bytes32)
{
return keccak256(abi.encodePacked(_preimage));
}
/**
* @notice fulfill the condition by calling check the
* the hash and the pre-image uint value
* @param _agreementId SEA agreement identifier
* @return condition state
*/
function fulfill(
bytes32 _agreementId,
uint256 _preimage
)
external
returns (ConditionStoreLibrary.ConditionState)
{
return _fulfill(generateId(_agreementId, hashValues(_preimage)));
}
/**
* @notice fulfill the condition by calling check the
* the hash and the pre-image string value
* @param _agreementId SEA agreement identifier
* @return condition state
*/
function fulfill(
bytes32 _agreementId,
string memory _preimage
)
public
returns (ConditionStoreLibrary.ConditionState)
{
return _fulfill(generateId(_agreementId, hashValues(_preimage)));
}
/**
* @notice fulfill the condition by calling check the
* the hash and the pre-image bytes32 value
* @param _agreementId SEA agreement identifier
* @return condition state
*/
function fulfill(
bytes32 _agreementId,
bytes32 _preimage
)
external
returns (ConditionStoreLibrary.ConditionState)
{
return _fulfill(generateId(_agreementId, hashValues(_preimage)));
}
/**
* @notice _fulfill calls super fulfil method
* @param _generatedId SEA agreement identifier
* @return condition state
*/
function _fulfill(
bytes32 _generatedId
)
private
returns (ConditionStoreLibrary.ConditionState)
{
return super.fulfill(
_generatedId,
ConditionStoreLibrary.ConditionState.Fulfilled
);
}
}
|
fulfill the condition by calling check the the hash and the pre-image bytes32 value _agreementId SEA agreement identifier return condition state/
|
function fulfill(
bytes32 _agreementId,
bytes32 _preimage
)
external
returns (ConditionStoreLibrary.ConditionState)
{
return _fulfill(generateId(_agreementId, hashValues(_preimage)));
}
| 12,648,548 |
/**
*Submitted for verification at Etherscan.io on 2021-08-20
*/
// Sources flattened with hardhat v2.4.3 https://hardhat.org
// File @openzeppelin/contracts/utils/introspection/[email protected]
// 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);
}
// File contracts/IERC2981.sol
pragma solidity >=0.8.5;
///
/// @dev Interface for the NFT Royalty Standard
///
interface IERC2981 is IERC165 {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
/// _registerInterface(_INTERFACE_ID_ERC2981);
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view returns (
address receiver,
uint256 royaltyAmount
);
/// @notice Informs callers that this contract supports ERC2981
/// @dev If `_registerInterface(_INTERFACE_ID_ERC2981)` is called
/// in the initializer, this should be automatic
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @return `true` if the contract implements
/// `_INTERFACE_ID_ERC2981` and `false` otherwise
function supportsInterface(bytes4 interfaceID) external view override returns (bool);
}
// File @openzeppelin/contracts/utils/[email protected]
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/[email protected]
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 contracts/MerkleProof.sol
pragma solidity ^0.8.5;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
contract MerkleProof is Ownable {
// merkle tree root used to validate the provided address and assigned proof
bytes32 public root;
/**
* @dev Set the merkle tree root hash
* @param _root hash to save
*/
function setMerkleRoot(bytes32 _root) public onlyOwner {
require(_root.length > 0, "Root is empty");
require(root == bytes32(""), "Root was already assigned");
root = _root;
}
/**
* @dev Modifier to check if the sender can mint tokens
* @param proof hashes to validate
*/
modifier canMintEarly(bytes32[] memory proof) {
require(isProofValid(proof), "the proof for this sender is not valid");
_;
}
/**
* @dev Check if the sender can mint tokens
* @param proof hashes to validate
*/
function isProofValid(bytes32[] memory proof) public view returns (bool) {
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
return verify(leaf, proof);
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32 leaf, bytes32[] memory proof)
internal view
returns (bool)
{
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(
abi.encodePacked(computedHash, proofElement)
);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(
abi.encodePacked(proofElement, computedHash)
);
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
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/[email protected]
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/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
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/introspection/[email protected]
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/[email protected]
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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File @openzeppelin/contracts/utils/math/[email protected]
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File @openzeppelin/contracts/security/[email protected]
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/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev ERC721 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC721Pausable is ERC721, Pausable {
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Storage based implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Storage is ERC165 {
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return super.supportsInterface(interfaceId) || _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;
}
}
// File @openzeppelin/contracts/security/[email protected]
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;
}
}
// File contracts/ReaperHills.sol
pragma solidity >=0.8.5;
contract ReaperHills is
MerkleProof,
ERC165Storage,
ERC721Pausable,
ERC721Enumerable,
ReentrancyGuard
{
using SafeMath for uint256;
// struct that holds information about when a token was created/transferred
struct NFTDetails {
uint256 tokenId;
uint256 starTime;
uint256 endTime;
}
// emits BaseURIChanged event when the baseUri changes
event BaseURIChanged(
address indexed _owner,
string initialBaseURI,
string finalBaseURI
);
// interface used by marketplaces to get the royalty for a specific sell
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
// maximum number of tokens that can be minted
uint256 public constant MAX_TOKENS = 10000;
// maximum number of tokens that can be early minted in a single transaction
uint256 public constant MAX_EARLY_TOKENS_PER_PURCHASE = 25;
// maximum number of tokens that can be early minted in a single transaction first day
uint256 public constant MAX_EARLY_TOKENS_PER_PURCHASE_FIRST_DAY = 5;
// maximum number of tokens that can be minted in a single transaction
uint256 public constant MAX_TOKENS_PER_PURCHASE = 50;
// the price to mint a token
uint256 public constant MINT_PRICE = 60000000000000000; // 0.06 Ether
// Reserved tokens for Team/Giveaways/Airdrops etc
uint256 public reservedTokens = 100;
// Already minted reserved tokens
uint256 public mintedReservedTokens = 0;
uint256 public mintingStartTime;
mapping(address => uint256) public earlyMintedTokensByOwner;
// royalty got from a sell
uint256 public constant ROYALTY_SELL_PERCENT = 10; // 10% of sell price
// part of royalty that is being distributed to the team 1
uint256 public constant ROYALTY_SELL_PERCENT_TEAM_1 = 40; // 2% of sell price
// part of royalty that is being distributed to the team 2
uint256 public constant ROYALTY_SELL_PERCENT_TEAM_2 = 40; // 2% of sell price
// part of royalty that is being distributed to the team 3
uint256 public constant ROYALTY_SELL_PERCENT_TEAM_3 = 15; // 0.75% of sell price
// part of royalty that is being distributed to the team 4
uint256 public constant ROYALTY_SELL_PERCENT_TEAM_4 = 5; // 0.25% of sell price
// address team 1 to receive part of royalty
address public royaltyReceiverTeam1;
// address team 2 to receive part of royalty
address public royaltyReceiverTeam2;
// address team 3 to receive part of royalty
address public royaltyReceiverTeam3;
// address team 4 to receive part of royalty
address public royaltyReceiverTeam4;
// address team 4 to receive part of royalty
address public communityAddress;
// allow early adopters to mint tokens. Once disabled can't be enabled back
bool public earlyMinting = true;
// flag to signal if the owner can change the BaseURI
bool public canChangeBaseURI = true;
// the base uri where the NFT metadata would point to
string public baseURI = "";
// hash to proof that the images and metadata from IPFS is valid
string public provenance = "";
// mapping from owner to list of token ids
mapping(address => uint256[]) public ownerTokenList;
// mapping from token ID to token details of the owner tokens list
mapping(address => mapping(uint256 => NFTDetails))
public ownedTokensDetails;
// nonce to be used on generating the random token id
uint256 private nonce = 0;
uint256[MAX_TOKENS] private indices;
constructor(
string memory name_,
string memory symbol_,
address royaltyReceiver1_,
address royaltyReceiver2_,
address royaltyReceiver3_,
address royaltyReceiver4_,
address communityAddress_
) ERC721(name_, symbol_) {
royaltyReceiverTeam1 = royaltyReceiver1_;
royaltyReceiverTeam2 = royaltyReceiver2_;
royaltyReceiverTeam3 = royaltyReceiver3_;
royaltyReceiverTeam4 = royaltyReceiver4_;
communityAddress = communityAddress_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(type(IERC721).interfaceId);
_registerInterface(type(IERC721Metadata).interfaceId);
_registerInterface(type(IERC721Enumerable).interfaceId);
}
function firstMints() public onlyOwner {
for (uint8 id = 1; id <= 6; id++) {
indices[id - 1] = MAX_TOKENS - totalSupply() - 1;
ownerTokenList[communityAddress].push(id);
ownedTokensDetails[communityAddress][id] = NFTDetails(
id,
block.timestamp,
0
);
_safeMint(communityAddress, id);
}
}
/*
* accepts ether sent with no txData
*/
receive() external payable {}
/*
* refuses ether sent with txData that does not match any function signature in the contract
*/
fallback() external {}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function pause() public onlyOwner {
super._pause();
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function unpause() public onlyOwner {
super._unpause();
}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Pausable, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Retrieve the ETH balance of the current contract
*/
function getBalance() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, ERC165Storage, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overwritten
* in child contracts.
*/
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
/**
* @dev Set the baseURI to a given uri
* @param uri string to save
*/
function changeBaseURI(string memory uri) public onlyOwner {
require(canChangeBaseURI, "The baseURI can't be changed anymore");
require(bytes(uri).length > 0, "uri is empty");
string memory initialBaseURI = baseURI;
baseURI = uri;
emit BaseURIChanged(msg.sender, initialBaseURI, baseURI);
}
/**
* @dev Get the list of tokens for a specific owner
* @param _owner address to retrieve token ids for
*/
function tokensByOwner(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);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
/**
* @dev Set the NFT IPFS hash proof for tokens metadata
* @param hashProof string to save
*/
function setProvenance(string memory hashProof) public onlyOwner {
require(bytes(hashProof).length > 0, "hash proof is empty");
provenance = hashProof;
}
/**
* @dev Disable early minting
*/
function disableEarlyMinting() external onlyOwner {
require(earlyMinting, "Early minting already disabled");
earlyMinting = false;
}
/**
* @dev Disable changes for baseURI
*/
function disableBaseURIChanges() external onlyOwner {
require(canChangeBaseURI, "The owner can't change the baseURI anymore");
canChangeBaseURI = false;
}
/**
* Credits to LarvaLabs Meebits contract
*/
function randomIndex() internal returns (uint256) {
uint256 totalSize = MAX_TOKENS - totalSupply();
uint256 index = uint256(
keccak256(
abi.encodePacked(
nonce,
msg.sender,
block.difficulty,
block.timestamp
)
)
) % totalSize;
uint256 value = 0;
if (indices[index] != 0) {
value = indices[index];
} else {
value = index;
}
// Move last value to selected position
if (indices[totalSize - 1] == 0) {
// Array position not initialized, so use position
indices[index] = totalSize - 1;
} else {
// Array position holds a value so use that
indices[index] = indices[totalSize - 1];
}
nonce++;
// Don't allow a zero index, start counting at 1
return value + 1;
}
/**
* @dev Mint tokens early
* @param _count the number of tokens to be minted
* @param proof to validate if the sender can mint the tokens early
*/
function earlyMint(uint256 _count, bytes32[] memory proof)
public
payable
nonReentrant
canMintEarly(proof)
{
require(
earlyMinting,
"The early minting is disabled. Use the mint function."
);
require(
_count > 0 && _count <= MAX_EARLY_TOKENS_PER_PURCHASE,
"Too many early tokens to mint at once"
);
require(
_count + earlyMintedTokensByOwner[msg.sender] <=
MAX_EARLY_TOKENS_PER_PURCHASE,
"Too many early tokens to mint"
);
if (block.timestamp - mintingStartTime <= 86400) {
require(
_count <= MAX_EARLY_TOKENS_PER_PURCHASE_FIRST_DAY,
"To many tokens to be minted early in the first day"
);
}
earlyMintedTokensByOwner[msg.sender] += _count;
_mint(_count);
}
/**
* @dev Withdraw contract balance to owner
*/
function withdraw() public onlyOwner {
sendValueTo(msg.sender, address(this).balance);
}
/**
* @dev Mint tokens for community wallet
*/
function mintToCommunityWallet(uint8 _count) external onlyOwner {
require(
_count > 0 && _count <= reservedTokens,
"Too many reserved tokens to mint at once"
);
require(
_count + mintedReservedTokens <= reservedTokens,
"Too many reserved tokens to mint"
);
mintedReservedTokens += _count;
mintNTokensFor(communityAddress, _count);
}
/**
* @dev Mint new tokens
* @param _count the number of tokens to be minted
*/
function mint(uint256 _count)
public
payable
nonReentrant
{
require(
!earlyMinting,
"The early minting is enabled. Use earlyMint function."
);
_mint(_count);
}
/**
* @dev Mint new tokens
* @param _count the number of tokens to be minted
*/
function _mint(uint256 _count) internal {
require(!paused(), "The minting of new tokens is paused");
uint256 totalSupply = totalSupply();
require(
_count > 0 && _count <= MAX_TOKENS_PER_PURCHASE,
"The maximum number of tokens that can be minted was exceeded"
);
require(
totalSupply + _count <= MAX_TOKENS,
"Exceeds maximum tokens available for purchase"
);
require(
msg.value >= MINT_PRICE.mul(_count),
"Ether value sent is not correct"
);
for (uint256 i = 0; i < _count; i++) {
_mintToken(msg.sender);
}
uint256 value = msg.value;
sendValueTo(
royaltyReceiverTeam1,
(value * ROYALTY_SELL_PERCENT_TEAM_1) / 100
);
sendValueTo(
royaltyReceiverTeam2,
(value * ROYALTY_SELL_PERCENT_TEAM_2) / 100
);
sendValueTo(
royaltyReceiverTeam3,
(value * ROYALTY_SELL_PERCENT_TEAM_3) / 100
);
sendValueTo(
royaltyReceiverTeam4,
(value * ROYALTY_SELL_PERCENT_TEAM_4) / 100
);
}
/**
* @dev Mint token for an address
* @param to address to mint token for
*/
function _mintToken(address to) internal {
uint256 id = randomIndex();
ownerTokenList[to].push(id);
ownedTokensDetails[to][id] = NFTDetails(id, block.timestamp, 0);
_safeMint(to, id);
}
/**
* @dev Mint n tokens for an address
* @param to address to mint tokens for
* @param n number of tokens to mint
*/
function mintNTokensFor(address to, uint8 n) internal {
for (uint8 i = 0; i < n; i++) {
_mintToken(to);
}
}
/**
* @dev Send an amount of value to a specific address
* @param to_ address that will receive the value
* @param value to be sent to the address
*/
function sendValueTo(address to_, uint256 value) internal {
address payable to = payable(to_);
(bool success, ) = to.call{value: value}("");
require(success, "Transfer failed.");
}
/**
* @dev Get token history list of sender
*/
function getTokenList() public view returns (uint256[] memory) {
return ownerTokenList[msg.sender];
}
/**
* @dev Get token history list of owner
* @param owner_ for which to get all the tokens
*/
function getTokenListFor(address owner_)
public
view
returns (uint256[] memory)
{
return ownerTokenList[owner_];
}
/**
* @dev Get token details for sender
*/
function getTokenDetails() public view returns (NFTDetails[] memory) {
return getTokenDetailsFor(msg.sender);
}
/**
* @dev Get token details for a specific address
* @param owner_ for which to get all the token details
*/
function getTokenDetailsFor(address owner_)
public
view
returns (NFTDetails[] memory)
{
return getTokenDetailsForFromIndex(owner_, 0);
}
/**
* @dev Get token details for a specific address from an index of owner's token lsit
* @param owner_ for which to get the token details
* @param index from which to start retrieving the token details
*/
function getTokenDetailsForFromIndex(address owner_, uint256 index)
public
view
returns (NFTDetails[] memory)
{
uint256[] memory ownerList = ownerTokenList[owner_];
NFTDetails[] memory details = new NFTDetails[](
ownerList.length - index
);
uint256 counter = 0;
for (uint256 i = index; i < ownerList.length; i++) {
details[counter] = ownedTokensDetails[owner_][ownerList[i]];
counter++;
}
return details;
}
/**
* @dev Change token owner details mappings
*/
function _updateTokenOwners(
address from,
address to,
uint256 tokenId
) internal {
ownedTokensDetails[from][tokenId].endTime = block.timestamp;
ownerTokenList[to].push(tokenId);
ownedTokensDetails[to][tokenId] = NFTDetails(
tokenId,
block.timestamp,
0
);
}
/**
* @dev See {IERC721-safeTransferFrom}.
* @param from address from which to transfer the token
* @param to address to which to transfer the token
* @param tokenId to transfer
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_updateTokenOwners(from, to, tokenId);
super.safeTransferFrom(from, to, tokenId);
}
/**
* @dev See {IERC721-transferFrom}.
* @param from address from which to transfer the token
* @param to address to which to transfer the token
* @param tokenId to transfer
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_updateTokenOwners(from, to, tokenId);
super.transferFrom(from, to, tokenId);
}
}
|
Disable changes for baseURI/
|
function disableBaseURIChanges() external onlyOwner {
require(canChangeBaseURI, "The owner can't change the baseURI anymore");
canChangeBaseURI = false;
}
| 2,425,312 |
pragma solidity ^0.4.18;
/**
* @author Emil Dudnyk
*/
contract ETHPriceWatcher {
address public ethPriceProvider;
modifier onlyEthPriceProvider() {
require(msg.sender == ethPriceProvider);
_;
}
function receiveEthPrice(uint ethUsdPrice) external;
function setEthPriceProvider(address provider) external;
}
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
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.
*/
// This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
}
// </ORACLIZE_API>
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract BuildingStatus is Ownable {
/* Observer contract */
address public observer;
/* Crowdsale contract */
address public crowdsale;
enum statusEnum {
crowdsale,
refund,
preparation_works,
building_permit,
design_technical_documentation,
utilities_outsite,
construction_residential,
frame20,
frame40,
frame60,
frame80,
frame100,
stage1,
stage2,
stage3,
stage4,
stage5,
facades20,
facades40,
facades60,
facades80,
facades100,
engineering,
finishing,
construction_parking,
civil_works,
engineering_further,
commisioning_project,
completed
}
modifier notCompleted() {
require(status != statusEnum.completed);
_;
}
modifier onlyObserver() {
require(msg.sender == observer || msg.sender == owner || msg.sender == address(this));
_;
}
modifier onlyCrowdsale() {
require(msg.sender == crowdsale || msg.sender == owner || msg.sender == address(this));
_;
}
statusEnum public status;
event StatusChanged(statusEnum newStatus);
function setStatus(statusEnum newStatus) onlyCrowdsale public {
status = newStatus;
StatusChanged(newStatus);
}
function changeStage(uint8 stage) public onlyObserver {
if (stage==1) status = statusEnum.stage1;
if (stage==2) status = statusEnum.stage2;
if (stage==3) status = statusEnum.stage3;
if (stage==4) status = statusEnum.stage4;
if (stage==5) status = statusEnum.stage5;
}
}
/*
* Manager that stores permitted addresses
*/
contract PermissionManager is Ownable {
mapping (address => bool) permittedAddresses;
function addAddress(address newAddress) public onlyOwner {
permittedAddresses[newAddress] = true;
}
function removeAddress(address remAddress) public onlyOwner {
permittedAddresses[remAddress] = false;
}
function isPermitted(address pAddress) public view returns(bool) {
if (permittedAddresses[pAddress]) {
return true;
}
return false;
}
}
contract Registry is Ownable {
struct ContributorData {
bool isActive;
uint contributionETH;
uint contributionUSD;
uint tokensIssued;
uint quoteUSD;
uint contributionRNTB;
}
mapping(address => ContributorData) public contributorList;
mapping(uint => address) private contributorIndexes;
uint private nextContributorIndex;
/* Permission manager contract */
PermissionManager public permissionManager;
bool public completed;
modifier onlyPermitted() {
require(permissionManager.isPermitted(msg.sender));
_;
}
event ContributionAdded(address _contributor, uint overallEth, uint overallUSD, uint overallToken, uint quote);
event ContributionEdited(address _contributor, uint overallEth, uint overallUSD, uint overallToken, uint quote);
function Registry(address pManager) public {
permissionManager = PermissionManager(pManager);
completed = false;
}
function setPermissionManager(address _permadr) public onlyOwner {
require(_permadr != 0x0);
permissionManager = PermissionManager(_permadr);
}
function isActiveContributor(address contributor) public view returns(bool) {
return contributorList[contributor].isActive;
}
function removeContribution(address contributor) public onlyPermitted {
contributorList[contributor].isActive = false;
}
function setCompleted(bool compl) public onlyPermitted {
completed = compl;
}
function addContribution(address _contributor, uint _amount, uint _amusd, uint _tokens, uint _quote ) public onlyPermitted {
if (contributorList[_contributor].isActive == false) {
contributorList[_contributor].isActive = true;
contributorList[_contributor].contributionETH = _amount;
contributorList[_contributor].contributionUSD = _amusd;
contributorList[_contributor].tokensIssued = _tokens;
contributorList[_contributor].quoteUSD = _quote;
contributorIndexes[nextContributorIndex] = _contributor;
nextContributorIndex++;
} else {
contributorList[_contributor].contributionETH += _amount;
contributorList[_contributor].contributionUSD += _amusd;
contributorList[_contributor].tokensIssued += _tokens;
contributorList[_contributor].quoteUSD = _quote;
}
ContributionAdded(_contributor, contributorList[_contributor].contributionETH, contributorList[_contributor].contributionUSD, contributorList[_contributor].tokensIssued, contributorList[_contributor].quoteUSD);
}
function editContribution(address _contributor, uint _amount, uint _amusd, uint _tokens, uint _quote) public onlyPermitted {
if (contributorList[_contributor].isActive == true) {
contributorList[_contributor].contributionETH = _amount;
contributorList[_contributor].contributionUSD = _amusd;
contributorList[_contributor].tokensIssued = _tokens;
contributorList[_contributor].quoteUSD = _quote;
}
ContributionEdited(_contributor, contributorList[_contributor].contributionETH, contributorList[_contributor].contributionUSD, contributorList[_contributor].tokensIssued, contributorList[_contributor].quoteUSD);
}
function addContributor(address _contributor, uint _amount, uint _amusd, uint _tokens, uint _quote) public onlyPermitted {
contributorList[_contributor].isActive = true;
contributorList[_contributor].contributionETH = _amount;
contributorList[_contributor].contributionUSD = _amusd;
contributorList[_contributor].tokensIssued = _tokens;
contributorList[_contributor].quoteUSD = _quote;
contributorIndexes[nextContributorIndex] = _contributor;
nextContributorIndex++;
ContributionAdded(_contributor, contributorList[_contributor].contributionETH, contributorList[_contributor].contributionUSD, contributorList[_contributor].tokensIssued, contributorList[_contributor].quoteUSD);
}
function getContributionETH(address _contributor) public view returns (uint) {
return contributorList[_contributor].contributionETH;
}
function getContributionUSD(address _contributor) public view returns (uint) {
return contributorList[_contributor].contributionUSD;
}
function getContributionRNTB(address _contributor) public view returns (uint) {
return contributorList[_contributor].contributionRNTB;
}
function getContributionTokens(address _contributor) public view returns (uint) {
return contributorList[_contributor].tokensIssued;
}
function addRNTBContribution(address _contributor, uint _amount) public onlyPermitted {
if (contributorList[_contributor].isActive == false) {
contributorList[_contributor].isActive = true;
contributorList[_contributor].contributionRNTB = _amount;
contributorIndexes[nextContributorIndex] = _contributor;
nextContributorIndex++;
} else {
contributorList[_contributor].contributionETH += _amount;
}
}
function getContributorByIndex(uint index) public view returns (address) {
return contributorIndexes[index];
}
function getContributorAmount() public view returns(uint) {
return nextContributorIndex;
}
}
/**
* @author Emil Dudnyk
*/
contract OraclizeC is Ownable, usingOraclize {
uint public updateInterval = 300; //5 minutes by default
uint public gasLimit = 200000; // Oraclize Gas Limit
mapping (bytes32 => bool) validIds;
string public url;
enum State { New, Stopped, Active }
State public state = State.New;
event LogOraclizeQuery(string description, uint balance, uint blockTimestamp);
event LogOraclizeAddrResolverI(address oar);
modifier inActiveState() {
require(state == State.Active);
_;
}
modifier inStoppedState() {
require(state == State.Stopped);
_;
}
modifier inNewState() {
require(state == State.New);
_;
}
function setUpdateInterval(uint newInterval) external onlyOwner {
require(newInterval > 0);
updateInterval = newInterval;
}
function setUrl(string newUrl) external onlyOwner {
require(bytes(newUrl).length > 0);
url = newUrl;
}
function setGasLimit(uint _gasLimit) external onlyOwner {
require(_gasLimit > 50000);
gasLimit = _gasLimit;
}
function setGasPrice(uint gasPrice) external onlyOwner {
require(gasPrice >= 1000000000); // 1 Gwei
oraclize_setCustomGasPrice(gasPrice);
}
//local development
function setOraclizeAddrResolverI(address __oar) public onlyOwner {
require(__oar != 0x0);
OAR = OraclizeAddrResolverI(__oar);
LogOraclizeAddrResolverI(__oar);
}
//we need to get back our funds if we don't need this oracle anymore
function withdraw(address receiver) external onlyOwner inStoppedState {
require(receiver != 0x0);
receiver.transfer(this.balance);
}
}
/**
* @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 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;
}
}
/**
* @author Emil Dudnyk
*/
contract ETHPriceProvider is OraclizeC {
using SafeMath for uint;
uint public currentPrice;
ETHPriceWatcher public watcher;
event LogPriceUpdated(string getPrice, uint setPrice, uint blockTimestamp);
event LogStartUpdate(uint startingPrice, uint updateInterval, uint blockTimestamp);
function notifyWatcher() internal;
function ETHPriceProvider(string _url) payable public {
url = _url;
//update immediately first time to be sure everything is working - first oraclize request is free.
//update(0);
}
//send some funds along with the call to cover oraclize fees
function startUpdate(uint startingPrice) payable onlyOwner inNewState public {
state = State.Active;
currentPrice = startingPrice;
update(updateInterval);
notifyWatcher();
LogStartUpdate(startingPrice, updateInterval, block.timestamp);
}
function stopUpdate() external onlyOwner inActiveState {
state = State.Stopped;
}
function setWatcher(address newWatcher) external onlyOwner {
require(newWatcher != 0x0);
watcher = ETHPriceWatcher(newWatcher);
}
function __callback(bytes32 myid, string result) public {
require(msg.sender == oraclize_cbAddress() && validIds[myid]);
delete validIds[myid];
uint newPrice = parseInt(result, 2);
if (state == State.Active) {
update(updateInterval);
}
require(newPrice > 0);
currentPrice = newPrice;
notifyWatcher();
LogPriceUpdated(result,newPrice,block.timestamp);
}
function update(uint delay) private {
if (oraclize_getPrice("URL") > this.balance) {
//stop if we don't have enough funds anymore
state = State.Stopped;
LogOraclizeQuery("Oraclize query was NOT sent", this.balance,block.timestamp);
} else {
bytes32 queryId = oraclize_query(delay, "URL", url, gasLimit);
validIds[queryId] = true;
}
}
function getQuote() public constant returns (uint) {
return currentPrice;
}
}
contract ConvertQuote is ETHPriceProvider {
//Encrypted Query
function ConvertQuote(uint _currentPrice) ETHPriceProvider("BIa/Nnj1+ipZBrrLIgpTsI6ukQTlTJMd1c0iC7zvxx+nZzq9ODgBSmCLo3Zc0sYZwD8mlruAi5DblQvt2cGsfVeCyqaxu+1lWD325kgN6o0LxrOUW9OQWn2COB3TzcRL51Q+ZLBsT955S1OJbOqsfQ4gg/l2awe2EFVuO3WTprvwKhAa8tjl2iPYU/AJ83TVP9Kpz+ugTJumlz2Y6SPBGMNcvBoRq3MlnrR2h/XdqPbh3S2bxjbSTLwyZzu2DAgVtybPO1oJETY=") payable public {
currentPrice = _currentPrice;
}
function notifyWatcher() internal {
if(address(watcher) != 0x0) {
watcher.receiveEthPrice(currentPrice);
}
}
}
/**
* @title Contract that will work with ERC223 tokens.
*/
contract ERC223ReceivingContract {
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint _value, bytes _data) public pure {
TKN memory tkn;
tkn.sender = _from;
tkn.value = _value;
tkn.data = _data;
if(_data.length > 0) {
uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
tkn.sig = bytes4(u);
}
/* tkn variable is analogue of msg variable of Ether transaction
* tkn.sender is person who initiated this token transaction (analogue of msg.sender)
* tkn.value the number of tokens that were sent (analogue of msg.value)
* tkn.data is data of token transaction (analogue of msg.data)
* tkn.sig is 4 bytes signature of function
* if data of token transaction is a function execution
*/
}
}
contract ERC223Interface {
uint public totalSupply;
function balanceOf(address who) public view returns (uint);
function allowedAddressesOf(address who) public view returns (bool);
function getTotalSupply() public view returns (uint);
function transfer(address to, uint value) public returns (bool ok);
function transfer(address to, uint value, bytes data) public returns (bool ok);
function transfer(address to, uint value, bytes data, string custom_fallback) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
event TransferContract(address indexed from, address indexed to, uint value, bytes data);
}
/**
* @title Unity Token is ERC223 token.
* @author Vladimir Kovalchuk
*/
contract UnityToken is ERC223Interface {
using SafeMath for uint;
string public constant name = "Unity Token";
string public constant symbol = "UNT";
uint8 public constant decimals = 18;
/* The supply is initially 100UNT to the precision of 18 decimals */
uint public constant INITIAL_SUPPLY = 100000 * (10 ** uint(decimals));
mapping(address => uint) balances; // List of user balances.
mapping(address => bool) allowedAddresses;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function addAllowed(address newAddress) public onlyOwner {
allowedAddresses[newAddress] = true;
}
function removeAllowed(address remAddress) public onlyOwner {
allowedAddresses[remAddress] = false;
}
address public owner;
/* Constructor initializes the owner's balance and the supply */
function UnityToken() public {
owner = msg.sender;
totalSupply = INITIAL_SUPPLY;
balances[owner] = INITIAL_SUPPLY;
}
function getTotalSupply() public view returns (uint) {
return totalSupply;
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) {
if (isContract(_to)) {
require(allowedAddresses[_to]);
if (balanceOf(msg.sender) < _value)
revert();
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
TransferContract(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
if (isContract(_to)) {
return transferToContract(_to, _value, _data);
} else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value) public returns (bool success) {
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if (isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length > 0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value)
revert();
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(allowedAddresses[_to]);
if (balanceOf(msg.sender) < _value)
revert();
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
TransferContract(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
function allowedAddressesOf(address _owner) public view returns (bool allowed) {
return allowedAddresses[_owner];
}
}
/**
* @title Hold contract.
* @author Vladimir Kovalchuk
*/
contract Hold is Ownable {
uint8 stages = 5;
uint8 public percentage;
uint8 public currentStage;
uint public initialBalance;
uint public withdrawed;
address public multisig;
Registry registry;
PermissionManager public permissionManager;
uint nextContributorToTransferEth;
address public observer;
uint dateDeployed;
mapping(address => bool) private hasWithdrawedEth;
event InitialBalanceChanged(uint balance);
event EthReleased(uint ethreleased);
event EthRefunded(address contributor, uint ethrefunded);
event StageChanged(uint8 newStage);
event EthReturnedToOwner(address owner, uint balance);
modifier onlyPermitted() {
require(permissionManager.isPermitted(msg.sender) || msg.sender == owner);
_;
}
modifier onlyObserver() {
require(msg.sender == observer || msg.sender == owner);
_;
}
function Hold(address _multisig, uint cap, address pm, address registryAddress, address observerAddr) public {
percentage = 100 / stages;
currentStage = 0;
multisig = _multisig;
initialBalance = cap;
dateDeployed = now;
permissionManager = PermissionManager(pm);
registry = Registry(registryAddress);
observer = observerAddr;
}
function setPermissionManager(address _permadr) public onlyOwner {
require(_permadr != 0x0);
permissionManager = PermissionManager(_permadr);
}
function setObserver(address observerAddr) public onlyOwner {
require(observerAddr != 0x0);
observer = observerAddr;
}
function setInitialBalance(uint inBal) public {
initialBalance = inBal;
InitialBalanceChanged(inBal);
}
function releaseAllETH() onlyPermitted public {
uint balReleased = getBalanceReleased();
require(balReleased > 0);
require(this.balance >= balReleased);
multisig.transfer(balReleased);
withdrawed += balReleased;
EthReleased(balReleased);
}
function releaseETH(uint n) onlyPermitted public {
require(this.balance >= n);
require(getBalanceReleased() >= n);
multisig.transfer(n);
withdrawed += n;
EthReleased(n);
}
function getBalance() public view returns (uint) {
return this.balance;
}
function changeStageAndReleaseETH() public onlyObserver {
uint8 newStage = currentStage + 1;
require(newStage <= stages);
currentStage = newStage;
StageChanged(newStage);
releaseAllETH();
}
function changeStage() public onlyObserver {
uint8 newStage = currentStage + 1;
require(newStage <= stages);
currentStage = newStage;
StageChanged(newStage);
}
function getBalanceReleased() public view returns (uint) {
return initialBalance * percentage * currentStage / 100 - withdrawed ;
}
function returnETHByOwner() public onlyOwner {
require(now > dateDeployed + 183 days);
uint balance = getBalance();
owner.transfer(getBalance());
EthReturnedToOwner(owner, balance);
}
function refund(uint _numberOfReturns) public onlyOwner {
require(_numberOfReturns > 0);
address currentParticipantAddress;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++) {
currentParticipantAddress = registry.getContributorByIndex(nextContributorToTransferEth);
if (currentParticipantAddress == 0x0)
return;
if (!hasWithdrawedEth[currentParticipantAddress]) {
uint EthAmount = registry.getContributionETH(currentParticipantAddress);
EthAmount -= EthAmount * (percentage / 100 * currentStage);
currentParticipantAddress.transfer(EthAmount);
EthRefunded(currentParticipantAddress, EthAmount);
hasWithdrawedEth[currentParticipantAddress] = true;
}
nextContributorToTransferEth += 1;
}
}
function() public payable {
}
function getWithdrawed(address contrib) public onlyPermitted view returns (bool) {
return hasWithdrawedEth[contrib];
}
}
contract Crowdsale is Pausable, ETHPriceWatcher, ERC223ReceivingContract {
using SafeMath for uint256;
UnityToken public token;
Hold hold;
ConvertQuote convert;
Registry registry;
enum SaleState {NEW, SALE, ENDED, REFUND}
// minimum goal USD
uint public softCap;
// maximum goal USD
uint public hardCap;
// maximum goal UNT
uint public hardCapToken;
// start and end timestamps where investments are allowed
uint public startDate;
uint public endDate;
uint public ethUsdPrice; // in cents
uint public tokenUSDRate; // in cents
// total ETH collected
uint private ethRaised;
// total USD collected
uint private usdRaised;
// total token sales
uint private totalTokens;
// how many tokens sent to investors
uint public withdrawedTokens;
// minimum ETH investment amount
uint public minimalContribution;
bool releasedTokens;
BuildingStatus public statusI;
PermissionManager public permissionManager;
//minimum of tokens that must be on the contract for the start
uint private minimumTokensToStart;
SaleState public state;
uint private nextContributorToClaim;
uint private nextContributorToTransferTokens;
mapping(address => bool) private hasWithdrawedTokens; //address who got a tokens
mapping(address => bool) private hasRefunded; //address who got a tokens
/* Events */
event CrowdsaleStarted(uint blockNumber);
event CrowdsaleEnded(uint blockNumber);
event SoftCapReached(uint blockNumber);
event HardCapReached(uint blockNumber);
event ContributionAdded(address contrib, uint amount, uint amusd, uint tokens, uint ethusdrate);
event ContributionAddedManual(address contrib, uint amount, uint amusd, uint tokens, uint ethusdrate);
event ContributionEdit(address contrib, uint amount, uint amusd, uint tokens, uint ethusdrate);
event ContributionRemoved(address contrib, uint amount, uint amusd, uint tokens);
event TokensTransfered(address contributor, uint amount);
event Refunded(address ref, uint amount);
event ErrorSendingETH(address to, uint amount);
event WithdrawedEthToHold(uint amount);
event ManualChangeStartDate(uint beforeDate, uint afterDate);
event ManualChangeEndDate(uint beforeDate, uint afterDate);
event TokensTransferedToHold(address hold, uint amount);
event TokensTransferedToOwner(address hold, uint amount);
event ChangeMinAmount(uint oldMinAmount, uint minAmount);
event ChangePreSale(address preSale);
event ChangeTokenUSDRate(uint oldTokenUSDRate, uint tokenUSDRate);
event ChangeHardCapToken(uint oldHardCapToken, uint newHardCapToken);
event SoftCapChanged();
event HardCapChanged();
modifier onlyPermitted() {
require(permissionManager.isPermitted(msg.sender) || msg.sender == owner);
_;
}
function Crowdsale(
address tokenAddress,
address registryAddress,
address _permissionManager,
uint start,
uint end,
uint _softCap,
uint _hardCap,
address holdCont,
uint _ethUsdPrice) public
{
token = UnityToken(tokenAddress);
permissionManager = PermissionManager(_permissionManager);
state = SaleState.NEW;
startDate = start;
endDate = end;
minimalContribution = 0.3 * 1 ether;
tokenUSDRate = 44500; //445.00$ in cents
releasedTokens = false;
softCap = _softCap * 1 ether;
hardCap = _hardCap * 1 ether;
hardCapToken = 100000 * 1 ether;
ethUsdPrice = _ethUsdPrice;
hold = Hold(holdCont);
registry = Registry(registryAddress);
}
function setPermissionManager(address _permadr) public onlyOwner {
require(_permadr != 0x0);
permissionManager = PermissionManager(_permadr);
}
function setRegistry(address _regadr) public onlyOwner {
require(_regadr != 0x0);
registry = Registry(_regadr);
}
function setTokenUSDRate(uint _tokenUSDRate) public onlyOwner {
require(_tokenUSDRate > 0);
uint oldTokenUSDRate = tokenUSDRate;
tokenUSDRate = _tokenUSDRate;
ChangeTokenUSDRate(oldTokenUSDRate, _tokenUSDRate);
}
function getTokenUSDRate() public view returns (uint) {
return tokenUSDRate;
}
function receiveEthPrice(uint _ethUsdPrice) external onlyEthPriceProvider {
require(_ethUsdPrice > 0);
ethUsdPrice = _ethUsdPrice;
}
function setEthPriceProvider(address provider) external onlyOwner {
require(provider != 0x0);
ethPriceProvider = provider;
}
/* Setters */
function setHold(address holdCont) public onlyOwner {
require(holdCont != 0x0);
hold = Hold(holdCont);
}
function setToken(address tokCont) public onlyOwner {
require(tokCont != 0x0);
token = UnityToken(tokCont);
}
function setStatusI(address statI) public onlyOwner {
require(statI != 0x0);
statusI = BuildingStatus(statI);
}
function setStartDate(uint date) public onlyOwner {
uint oldStartDate = startDate;
startDate = date;
ManualChangeStartDate(oldStartDate, date);
}
function setEndDate(uint date) public onlyOwner {
uint oldEndDate = endDate;
endDate = date;
ManualChangeEndDate(oldEndDate, date);
}
function setSoftCap(uint _softCap) public onlyOwner {
softCap = _softCap * 1 ether;
SoftCapChanged();
}
function setHardCap(uint _hardCap) public onlyOwner {
hardCap = _hardCap * 1 ether;
HardCapChanged();
}
function setMinimalContribution(uint minimumAmount) public onlyOwner {
uint oldMinAmount = minimalContribution;
minimalContribution = minimumAmount;
ChangeMinAmount(oldMinAmount, minimalContribution);
}
function setHardCapToken(uint _hardCapToken) public onlyOwner {
require(_hardCapToken > 1 ether); // > 1 UNT
uint oldHardCapToken = _hardCapToken;
hardCapToken = _hardCapToken;
ChangeHardCapToken(oldHardCapToken, hardCapToken);
}
/* The function without name is the default function that is called whenever anyone sends funds to a contract */
function() whenNotPaused public payable {
require(state == SaleState.SALE);
require(now >= startDate);
require(msg.value >= minimalContribution);
bool ckeck = checkCrowdsaleState(msg.value);
if(ckeck) {
processTransaction(msg.sender, msg.value);
} else {
msg.sender.transfer(msg.value);
}
}
/**
* @dev Checks if the goal or time limit has been reached and ends the campaign
* @return false when contract does not accept tokens
*/
function checkCrowdsaleState(uint _amount) internal returns (bool) {
uint usd = _amount.mul(ethUsdPrice);
if (usdRaised.add(usd) >= hardCap) {
state = SaleState.ENDED;
statusI.setStatus(BuildingStatus.statusEnum.preparation_works);
HardCapReached(block.number);
CrowdsaleEnded(block.number);
return true;
}
if (now > endDate) {
if (usdRaised.add(usd) >= softCap) {
state = SaleState.ENDED;
statusI.setStatus(BuildingStatus.statusEnum.preparation_works);
CrowdsaleEnded(block.number);
return false;
} else {
state = SaleState.REFUND;
statusI.setStatus(BuildingStatus.statusEnum.refund);
CrowdsaleEnded(block.number);
return false;
}
}
return true;
}
/**
* @dev Token purchase
*/
function processTransaction(address _contributor, uint _amount) internal {
require(msg.value >= minimalContribution);
uint maxContribution = calculateMaxContributionUsd();
uint contributionAmountUsd = _amount.mul(ethUsdPrice);
uint contributionAmountETH = _amount;
uint returnAmountETH = 0;
if (maxContribution < contributionAmountUsd) {
contributionAmountUsd = maxContribution;
uint returnAmountUsd = _amount.mul(ethUsdPrice) - maxContribution;
returnAmountETH = contributionAmountETH - returnAmountUsd.div(ethUsdPrice);
contributionAmountETH = contributionAmountETH.sub(returnAmountETH);
}
if (usdRaised + contributionAmountUsd >= softCap && softCap > usdRaised) {
SoftCapReached(block.number);
}
// get tokens from eth Usd msg.value * ethUsdPrice / tokenUSDRate
// 1 ETH * 860 $ / 445 $ = 193258426966292160 wei = 1.93 UNT
uint tokens = contributionAmountUsd.div(tokenUSDRate);
if(totalTokens + tokens > hardCapToken) {
_contributor.transfer(_amount);
} else {
if (tokens > 0) {
registry.addContribution(_contributor, contributionAmountETH, contributionAmountUsd, tokens, ethUsdPrice);
ethRaised += contributionAmountETH;
totalTokens += tokens;
usdRaised += contributionAmountUsd;
ContributionAdded(_contributor, contributionAmountETH, contributionAmountUsd, tokens, ethUsdPrice);
}
}
if (returnAmountETH != 0) {
_contributor.transfer(returnAmountETH);
}
}
/**
* @dev It is necessary for a correct change of status in the event of completion of the campaign.
* @param _stateChanged if true transfer ETH back
*/
function refundTransaction(bool _stateChanged) internal {
if (_stateChanged) {
msg.sender.transfer(msg.value);
} else{
revert();
}
}
function getTokensIssued() public view returns (uint) {
return totalTokens;
}
function getTotalUSDInTokens() public view returns (uint) {
return totalTokens.mul(tokenUSDRate);
}
function getUSDRaised() public view returns (uint) {
return usdRaised;
}
function calculateMaxContributionUsd() public constant returns (uint) {
return hardCap - usdRaised;
}
function calculateMaxTokensIssued() public constant returns (uint) {
return hardCapToken - totalTokens;
}
function calculateMaxEthIssued() public constant returns (uint) {
return hardCap.mul(ethUsdPrice) - usdRaised.mul(ethUsdPrice);
}
function getEthRaised() public view returns (uint) {
return ethRaised;
}
function checkBalanceContract() internal view returns (uint) {
return token.balanceOf(this);
}
function getContributorTokens(address contrib) public view returns (uint) {
return registry.getContributionTokens(contrib);
}
function getContributorETH(address contrib) public view returns (uint) {
return registry.getContributionETH(contrib);
}
function getContributorUSD(address contrib) public view returns (uint) {
return registry.getContributionUSD(contrib);
}
function batchReturnUNT(uint _numberOfReturns) public onlyOwner whenNotPaused {
require((now > endDate && usdRaised >= softCap ) || ( usdRaised >= hardCap) );
require(state == SaleState.ENDED);
require(_numberOfReturns > 0);
address currentParticipantAddress;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++) {
currentParticipantAddress = registry.getContributorByIndex(nextContributorToTransferTokens);
if (currentParticipantAddress == 0x0)
return;
if (!hasWithdrawedTokens[currentParticipantAddress] && registry.isActiveContributor(currentParticipantAddress)) {
uint numberOfUNT = registry.getContributionTokens(currentParticipantAddress);
if(token.transfer(currentParticipantAddress, numberOfUNT)) {
TokensTransfered(currentParticipantAddress, numberOfUNT);
withdrawedTokens += numberOfUNT;
hasWithdrawedTokens[currentParticipantAddress] = true;
}
}
nextContributorToTransferTokens += 1;
}
}
function getTokens() public whenNotPaused {
require((now > endDate && usdRaised >= softCap ) || ( usdRaised >= hardCap) );
require(state == SaleState.ENDED);
require(!hasWithdrawedTokens[msg.sender] && registry.isActiveContributor(msg.sender));
require(getTokenBalance() >= registry.getContributionTokens(msg.sender));
uint numberOfUNT = registry.getContributionTokens(msg.sender);
if(token.transfer(msg.sender, numberOfUNT)) {
TokensTransfered(msg.sender, numberOfUNT);
withdrawedTokens += numberOfUNT;
hasWithdrawedTokens[msg.sender] = true;
}
}
function getOverTokens() public onlyOwner {
require(checkBalanceContract() > (totalTokens - withdrawedTokens));
uint balance = checkBalanceContract() - (totalTokens - withdrawedTokens);
if(balance > 0) {
if(token.transfer(msg.sender, balance)) {
TokensTransfered(msg.sender, balance);
}
}
}
/**
* @dev if crowdsale is unsuccessful, investors can claim refunds here
*/
function refund() public whenNotPaused {
require(state == SaleState.REFUND);
require(registry.getContributionETH(msg.sender) > 0);
require(!hasRefunded[msg.sender]);
uint ethContributed = registry.getContributionETH(msg.sender);
if (!msg.sender.send(ethContributed)) {
ErrorSendingETH(msg.sender, ethContributed);
} else {
hasRefunded[msg.sender] = true;
Refunded(msg.sender, ethContributed);
}
}
/**
* @dev transfer funds ETH to multisig wallet if reached minimum goal
*/
function withdrawEth() public onlyOwner {
require(state == SaleState.ENDED);
uint bal = this.balance;
hold.transfer(bal);
hold.setInitialBalance(bal);
WithdrawedEthToHold(bal);
}
function newCrowdsale() public onlyOwner {
state = SaleState.NEW;
}
/**
* @dev Manual start crowdsale.
*/
function startCrowdsale() public onlyOwner {
require(now > startDate && now <= endDate);
require(state == SaleState.NEW);
statusI.setStatus(BuildingStatus.statusEnum.crowdsale);
state = SaleState.SALE;
CrowdsaleStarted(block.number);
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endDate || state == SaleState.ENDED;
}
function getTokenBalance() public constant returns (uint) {
return token.balanceOf(this);
}
function getSoftCap() public view returns (uint) {
return softCap;
}
function getHardCap() public view returns (uint) {
return hardCap;
}
function getStartDate() public view returns (uint) {
return startDate;
}
function getEndDate() public view returns (uint) {
return endDate;
}
function getContributorAmount() public view returns (uint) {
return registry.getContributorAmount();
}
function getWithdrawed(address contrib) public view returns (bool) {
return hasWithdrawedTokens[contrib];
}
function getRefunded(address contrib) public view returns (bool) {
return hasRefunded[contrib];
}
function addContributor(address _contributor, uint _amount, uint _amusd, uint _tokens, uint _quote) public onlyPermitted {
registry.addContributor(_contributor, _amount, _amusd, _tokens, _quote);
ethRaised += _amount;
usdRaised += _amusd;
totalTokens += _tokens;
ContributionAddedManual(_contributor, ethRaised, usdRaised, totalTokens, _quote);
}
function editContribution(address _contributor, uint _amount, uint _amusd, uint _tokens, uint _quote) public onlyPermitted {
ethRaised -= registry.getContributionETH(_contributor);
usdRaised -= registry.getContributionUSD(_contributor);
totalTokens -= registry.getContributionTokens(_contributor);
registry.editContribution(_contributor, _amount, _amusd, _tokens, _quote);
ethRaised += _amount;
usdRaised += _amusd;
totalTokens += _tokens;
ContributionAdded(_contributor, ethRaised, usdRaised, totalTokens, _quote);
}
function removeContributor(address _contributor) public onlyPermitted {
registry.removeContribution(_contributor);
ethRaised -= registry.getContributionETH(_contributor);
usdRaised -= registry.getContributionUSD(_contributor);
totalTokens -= registry.getContributionTokens(_contributor);
ContributionRemoved(_contributor, ethRaised, usdRaised, totalTokens);
}
}
|
if crowdsale is unsuccessful, investors can claim refunds here/
|
function refund() public whenNotPaused {
require(state == SaleState.REFUND);
require(registry.getContributionETH(msg.sender) > 0);
require(!hasRefunded[msg.sender]);
uint ethContributed = registry.getContributionETH(msg.sender);
if (!msg.sender.send(ethContributed)) {
ErrorSendingETH(msg.sender, ethContributed);
hasRefunded[msg.sender] = true;
Refunded(msg.sender, ethContributed);
}
}
| 10,112,648 |
// Copyright © 2021 Treum.io, a ConsenSys AG company. All rights reserved.
// BY USING THIS SMART CONTRACT, INCLUDING TO BUY, SELL, CREATE, BURN OR USE TOKENS, YOU AGREE TO EULERBEATS’ TERMS OF SERVICE, AVAILABLE HERE: HTTPS://EULERBEATS.COM/TERMS-OF-SERVICE AND IN THE TRANSACTION DATA OF 0x56ff8befa16e6720f9cf54146c9c5e3be9a1258fd910fe55c287f19ad80b8bc1
// SHA256 of artwork generation script: 65301d8425ba637bdb6328a17dbe7440bf1c7f5032879aad4c00bfa09bddf93f
pragma solidity =0.7.6;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./RoyaltyDistributor.sol";
// EulerBeats are generative visual & audio art pieces. The recipe and instructions to re-create the visualization and music reside on Ethereum blockchain.
//
// To recreate your art, you will need to retrieve the script
//
// STEPS TO RETRIEVE THE SCRIPTS:
// - The artwork re-generation script is written in JavaScript, split into pieces, and stored on chain.
// - Query the contract for the scriptCount - this is the number of pieces of the re-genereation script. You will need all of them.
// - Run the getScriptAtIndex method in the EulerBeats smart contract starting with parameter 0, this is will return a transaction hash
// - The "Input Data" field of this transaction contains the first segment of the script. Convert this into UTF-8 format
// - Repeat these last two steps, incrementing the parameter in the getScriptAtIndex method until the number of script segments matches the scrtipCount
contract EulerBeatsV2 is Ownable, ERC1155, ReentrancyGuard, RoyaltyDistributor {
using SafeMath for uint256;
using Strings for uint256;
using Address for address payable;
/***********************************|
| Variables and Events |
|__________________________________*/
// For Mint, mintPrint, and burnPrint: locks the prices
bool public mintPrintEnabled = false;
bool public burnPrintEnabled = false;
bool public mintEnabled = false;
bool private _contractMintPrintEnabled = false;
// For metadata (scripts), when locked it is irreversible
bool private _locked = false;
// Number of script sections stored
uint256 public scriptCount = 0;
// The scripts that can be used to render the NFT (audio and visual)
mapping (uint256 => string) public scripts;
// The bit flag to distinguish prints
uint256 constant public PRINTS_FLAG_BIT = 1;
// Supply restriction on prints
uint256 constant public MAX_PRINT_SUPPLY = 160;
// Supply restriction on seeds/original NFTs
uint256 constant public MAX_SEEDS_SUPPLY = 27;
// Total supply of prints and original NFTs
mapping(uint256 => uint256) public totalSupply;
// Total number of original NFTs minted
uint256 public originalsMinted = 0;
// Funds reserved for burns
uint256 public reserve = 0;
// Contract name
string public name;
// Contract symbol
string public symbol;
// Constants for bonding curve pricing
uint256 constant public A = 12;
uint256 constant public B = 140;
uint256 constant public C = 100;
uint256 constant public SIG_DIGITS = 3;
// Base uri for overriding ERC1155's uri getter
string internal _baseURI;
/**
* @dev Emitted when an original NFT with a new seed is minted
*/
event MintOriginal(address indexed to, uint256 seed, uint256 indexed originalsMinted);
/**
* @dev Emitted when an print is minted
*/
event PrintMinted(
address indexed to,
uint256 id,
uint256 indexed seed,
uint256 pricePaid,
uint256 nextPrintPrice,
uint256 nextBurnPrice,
uint256 printsSupply,
uint256 royaltyPaid,
uint256 reserve,
address indexed royaltyRecipient
);
/**
* @dev Emitted when an print is burned
*/
event PrintBurned(
address indexed to,
uint256 id,
uint256 indexed seed,
uint256 priceReceived,
uint256 nextPrintPrice,
uint256 nextBurnPrice,
uint256 printsSupply,
uint256 reserve
);
constructor(string memory _name, string memory _symbol, string memory _uri) ERC1155("") {
name = _name;
symbol = _symbol;
_baseURI = _uri;
}
/***********************************|
| Modifiers |
|__________________________________*/
modifier onlyWhenMintEnabled() {
require(mintEnabled, "Minting originals is disabled");
_;
}
modifier onlyWhenMintPrintEnabled() {
require(mintPrintEnabled, "Minting prints is disabled");
_;
}
modifier onlyWhenBurnPrintEnabled() {
require(burnPrintEnabled, "Burning prints is disabled");
_;
}
modifier onlyUnlocked() {
require(!_locked, "Contract is locked");
_;
}
/***********************************|
| User Interactions |
|__________________________________*/
/**
* @dev Function to mint tokens. Not payable for V2, restricted to owner
*/
function mint() external onlyOwner onlyWhenMintEnabled returns (uint256) {
uint256 newOriginalsSupply = originalsMinted.add(1);
require(
newOriginalsSupply <= MAX_SEEDS_SUPPLY,
"Max supply reached"
);
// The generated seed == the original nft token id.
// Both terms are used throughout and refer to the same thing.
uint256 seed = _generateSeed(newOriginalsSupply);
// Increment the supply per original nft (max: 1)
totalSupply[seed] = totalSupply[seed].add(1);
assert(totalSupply[seed] == 1);
// Update total originals minted
originalsMinted = newOriginalsSupply;
_mint(msg.sender, seed, 1, "");
emit MintOriginal(msg.sender, seed, newOriginalsSupply);
return seed;
}
/**
* @dev Function to mint prints from an existing seed. Msg.value must be sufficient.
* @param seed The NFT id to mint print of
* @param _owner The current owner of the seed
*/
function mintPrint(uint256 seed, address payable _owner)
external
payable
onlyWhenMintPrintEnabled
nonReentrant
returns (uint256)
{
// Confirm id is a seedId and belongs to _owner
require(isSeedId(seed) == true, "Invalid seed id");
// Confirm seed belongs to _owner
require(balanceOf(_owner, seed) == 1, "Incorrect seed owner");
// Spam-prevention: restrict msg.sender to only external accounts for an initial mintPrint period
if (msg.sender != tx.origin) {
require(_contractMintPrintEnabled == true, "Contracts not allowed to mintPrint");
}
// Derive print tokenId from seed
uint256 tokenId = getPrintTokenIdFromSeed(seed);
// Increment supply to compute current print price
uint256 newSupply = totalSupply[tokenId].add(1);
// Confirm newSupply does not exceed max
require(newSupply <= MAX_PRINT_SUPPLY, "Maximum supply exceeded");
// Get price to mint the next print
uint256 printPrice = getPrintPrice(newSupply);
require(msg.value >= printPrice, "Insufficient funds");
totalSupply[tokenId] = newSupply;
// Reserve cut is amount that will go towards reserve for burn at new supply
uint256 reserveCut = getBurnPrice(newSupply);
// Update reserve balance
reserve = reserve.add(reserveCut);
// Extract % for seed owner from difference between mintPrint cost and amount held for reserve
uint256 seedOwnerRoyalty = _getSeedOwnerCut(printPrice.sub(reserveCut));
// Mint token
_mint(msg.sender, tokenId, 1, "");
// Disburse royalties
if (seedOwnerRoyalty > 0) {
_distributeRoyalty(seed, _owner, seedOwnerRoyalty);
}
// If buyer sent extra ETH as padding in case another purchase was made they are refunded
_refundSender(printPrice);
emit PrintMinted(msg.sender, tokenId, seed, printPrice, getPrintPrice(newSupply.add(1)), reserveCut, newSupply, seedOwnerRoyalty, reserve, _owner);
return tokenId;
}
/**
* @dev Function to burn a print
* @param seed The seed for the print to burn.
* @param minimumSupply The minimum token supply for burn to succeed, this is a way to set slippage.
* Set to 1 to allow burn to go through no matter what the price is.
*/
function burnPrint(uint256 seed, uint256 minimumSupply) external onlyWhenBurnPrintEnabled nonReentrant {
// Confirm is valid seed id
require(isSeedId(seed) == true, "Invalid seed id");
// Derive token Id from seed
uint256 tokenId = getPrintTokenIdFromSeed(seed);
// Supply must meet user's minimum threshold
uint256 oldSupply = totalSupply[tokenId];
require(oldSupply >= minimumSupply, 'Min supply not met');
// burnPrice is the amount of ETH returned for burning this print
uint256 burnPrice = getBurnPrice(oldSupply);
uint256 newSupply = totalSupply[tokenId].sub(1);
totalSupply[tokenId] = newSupply;
// Update reserve balances
reserve = reserve.sub(burnPrice);
_burn(msg.sender, tokenId, 1);
// Disburse funds
msg.sender.sendValue(burnPrice);
emit PrintBurned(msg.sender, tokenId, seed, burnPrice, getPrintPrice(oldSupply), getBurnPrice(newSupply), newSupply, reserve);
}
/***********************************|
| Public Getters - Pricing |
|__________________________________*/
/**
* @dev Function to get print price
* @param printNumber the print number of the print Ex. if there are 2 existing prints, and you want to get the
* next print price, then this should be 3 as you are getting the price to mint the 3rd print
*/
function getPrintPrice(uint256 printNumber) public pure returns (uint256 price) {
uint256 decimals = 10 ** SIG_DIGITS;
// For prints 0-100, exponent value is < 0.001
if (printNumber <= 100) {
price = 0;
} else if (printNumber < B) {
// 10/A ^ (B - X)
price = (10 ** ( B.sub(printNumber) )).mul(decimals).div(A ** ( B.sub(printNumber)));
} else if (printNumber == B) {
// A/10 ^ 0 == 1
price = decimals; // price = decimals * (A ^ 0)
} else {
// A/10 ^ (X - B)
price = (A ** ( printNumber.sub(B) )).mul(decimals).div(10 ** ( printNumber.sub(B) ));
}
// += C*X
price = price.add(C.mul(printNumber));
// Convert to wei
price = price.mul(1 ether).div(decimals);
}
/**
* @dev Function to return amount of funds received when burned
* @param supply the supply of prints before burning. Ex. if there are 2 existing prints, to get the funds
* receive on burn the supply should be 2
*/
function getBurnPrice(uint256 supply) public pure returns (uint256 price) {
uint256 printPrice = getPrintPrice(supply);
// 84 % of print price
price = printPrice.mul(84).div(100);
}
/**
* @dev Function to get prices by supply
* @param supply the supply of prints before burning. Ex. if there are 2 existing prints, to get the funds
* receive on burn the supply should be 2
*/
function getPricesBySupply(uint256 supply) public pure returns (uint256 printPrice, uint256 nextPrintPrice, uint256 burnPrice, uint256 nextBurnPrice) {
printPrice = getPrintPrice(supply);
nextPrintPrice = getPrintPrice(supply + 1);
burnPrice = getBurnPrice(supply);
nextBurnPrice = getBurnPrice(supply + 1);
}
/**
* @dev Function to get prices & supply by seed
* @param seed The original NFT token id
*/
function getPricesBySeed(uint256 seed) external view returns (uint256 printPrice, uint256 nextPrintPrice, uint256 burnPrice, uint256 nextBurnPrice, uint256 supply) {
supply = seedToPrintsSupply(seed);
(printPrice, nextPrintPrice, burnPrice, nextBurnPrice) = getPricesBySupply(supply);
}
/***********************************|
| Public Getters - Seed + Prints |
|__________________________________*/
/**
* @dev Get the number of prints minted for the corresponding seed
* @param seed The original NFT token id
*/
function seedToPrintsSupply(uint256 seed)
public
view
returns (uint256)
{
uint256 tokenId = getPrintTokenIdFromSeed(seed);
return totalSupply[tokenId];
}
/**
* @dev The token id for the prints contains the original NFT id
* @param seed The original NFT token id
*/
function getPrintTokenIdFromSeed(uint256 seed) public pure returns (uint256) {
return seed | PRINTS_FLAG_BIT;
}
/**
* @dev Return whether a tokenId is for an original
* @param tokenId The original NFT token id
*/
function isSeedId(uint256 tokenId) public pure returns (bool) {
return tokenId & PRINTS_FLAG_BIT != PRINTS_FLAG_BIT;
}
/***********************************|
| Public Getters - Metadata |
|__________________________________*/
/**
* @dev Return the script section for a particular index
* @param index The index of a script section
*/
function getScriptAtIndex(uint256 index) external view returns (string memory) {
require(index < scriptCount, "Index out of bounds");
return scripts[index];
}
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given token.
* @dev URIs are defined in RFC 3986.
* URIs are assumed to be deterministically generated based on token ID
* @return URI string
*/
function uri(uint256 _id) external override view returns (string memory) {
require(totalSupply[_id] > 0, "URI query for nonexistent token");
return string(abi.encodePacked(_baseURI, _id.toString(), ".json"));
}
/***********************************|
|Internal Functions - Generate Seed |
|__________________________________*/
/**
* @dev Returns a new seed
* @param uniqueValue Random input for the seed generation
*/
function _generateSeed(uint256 uniqueValue) internal view returns (uint256) {
bytes32 hash = keccak256(abi.encodePacked(block.number, blockhash(block.number.sub(1)), msg.sender, uniqueValue));
// gridLength 0-5
uint8 gridLength = uint8(hash[0]) % 15;
if (gridLength > 5) gridLength = 1;
// horizontalLever 0-58
uint8 horizontalLever = uint8(hash[1]) % 59;
// diagonalLever 0-10
uint8 diagonalLever = uint8(hash[2]) % 11;
// palette 4 0-11
uint8 palette = uint8(hash[3]) % 12;
// innerShape 0-3 with rarity
uint8 innerShape = uint8(hash[4]) % 4;
return uint256(gridLength) << 40 | uint256(horizontalLever) << 32 | uint256(diagonalLever) << 24 | uint256(palette) << 16 | uint256(innerShape) << 8;
}
/***********************************|
| Internal Functions - Prints |
|__________________________________*/
/**
* @dev Returns the part of the mintPrint fee reserved for the seed owner royalty
* @param fee Amount of ETH not added to the contract reserve
*/
function _getSeedOwnerCut(uint256 fee) internal pure returns (uint256) {
// Seed owner and Treum split royalties 50/50
return fee.div(2);
}
/**
* @dev For mintPrint only, send remaining msg.value back to sender
* @param printPrice Cost to mint current print
*/
function _refundSender(uint256 printPrice) internal {
if (msg.value.sub(printPrice) > 0) {
msg.sender.sendValue(msg.value.sub(printPrice));
}
}
/***********************************|
| Admin |
|__________________________________*/
/**
* @dev Add a new section of the script
* @param _script String value of script or pointer
*/
function addScript(string memory _script) external onlyOwner onlyUnlocked {
scripts[scriptCount] = _script;
scriptCount = scriptCount.add(1);
}
/**
* @dev Overwrite a script section at a particular index
* @param _script String value of script or pointer
* @param index Index of the script to replace
*/
function updateScript(string memory _script, uint256 index) external onlyOwner onlyUnlocked {
require(index < scriptCount, "Index out of bounds");
scripts[index] = _script;
}
/**
* @dev Reset script index to zero, caller must be owner and the contract unlocked
*/
function resetScriptCount() external onlyOwner onlyUnlocked {
scriptCount = 0;
}
/**
* @dev Withdraw earned funds from original Nft sales and print fees. Cannot withdraw the reserve funds.
*/
function withdraw() external onlyOwner nonReentrant {
uint256 withdrawableFunds = address(this).balance.sub(reserve);
msg.sender.sendValue(withdrawableFunds);
}
/**
* @dev Function to enable/disable original minting
* @param enabled The flag to turn minting on or off
*/
function setMintEnabled(bool enabled) external onlyOwner {
mintEnabled = enabled;
}
/**
* @dev Function to enable/disable print minting
* @param enabled The flag to turn minting on or off
*/
function setMintPrintEnabled(bool enabled) external onlyOwner {
mintPrintEnabled = enabled;
}
/**
* @dev Function to enable/disable print burning
* @param enabled The flag to turn minting on or off
*/
function setBurnPrintEnabled(bool enabled) external onlyOwner {
burnPrintEnabled = enabled;
}
/**
* @dev Function to enable/disable print minting via contract
* @param enabled The flag to turn contract print minting on or off
*/
function setContractMintPrintEnabled(bool enabled) external onlyOwner {
_contractMintPrintEnabled = enabled;
}
/**
* @dev Function to lock/unlock the on-chain metadata
* @param locked The flag turn locked on
*/
function setLocked(bool locked) external onlyOwner onlyUnlocked {
_locked = locked;
}
/**
* @dev Function to update the base _uri for all tokens
* @param newuri The base uri string
*/
function setURI(string memory newuri) external onlyOwner {
_baseURI = newuri;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC1155.sol";
import "./IERC1155MetadataURI.sol";
import "./IERC1155Receiver.sol";
import "../../utils/Context.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
*
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri_) public {
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// 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.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 String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/introspection/ERC165Checker.sol";
import "./IEulerBeatsRoyaltyReceiver.sol";
contract RoyaltyDistributor {
using Address for address payable;
function _distributeRoyalty(
uint256 tokenId,
address payable tokenOwner,
uint256 royalty
) internal {
require(royalty > 0, "Missing royalty");
// this logic is broken into three cases:
// case 1: tokenOwner is a contract that implements RoyaltyReciever
// case 2: tokenOwner is a contract but not a RoyaltyReceiver
// case 3: tokenOwner is not a contract
if (tokenOwner.isContract()) {
if (ERC165Checker.supportsInterface(tokenOwner, IEulerBeatsRoyaltyReceiver(tokenOwner).royaltyReceived.selector)) {
// case 1
require(address(this).balance >= royalty, "RoyaltyDistributor: insufficient balance");
try IEulerBeatsRoyaltyReceiver(tokenOwner).royaltyReceived{value: royalty}(address(this), tokenId, tokenOwner) returns (bytes4 response) {
if (response != IEulerBeatsRoyaltyReceiver(tokenOwner).royaltyReceived.selector) {
revert("IEulerBeatsRoyaltyReceiver rejected royalty");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("RoyaltyDistributor: royaltyReceived reverted");
}
} else {
// case 2
tokenOwner.sendValue(royalty);
}
} else {
// case 3
tokenOwner.sendValue(royalty);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
// success determines whether the staticcall succeeded and result determines
// whether the contract at account indicates support of _interfaceId
(bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);
return (success && result);
}
/**
* @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return success true if the STATICCALL succeeded, false otherwise
* @return result true if the STATICCALL succeeded and the contract at account
* indicates support of the interface with identifier interfaceId, false otherwise
*/
function _callERC165SupportsInterface(address account, bytes4 interfaceId)
private
view
returns (bool, bool)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return (false, false);
return (success, abi.decode(result, (bool)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/introspection/ERC165.sol";
interface IEulerBeatsRoyaltyReceiver is IERC165 {
/**
@dev Handles the receipt of a royalty payout for the given original EulerBeat.
The royalty amount is the ether in msg.value.
To accept the royalty, this must return
`bytes4(keccak256("royaltyReceived(address,uint256,address)"))`
Implementors should take care to do the bare minimum in this function as it is
called as part of the mintPrint function, and will raise the gas required for minting prints.
@param tokenAddress The token address of the EulerBeats contract that the royalty was paid from
@param tokenId The ID of token the royalty was paid for. This is always the original token id, not print token ids
@param tokenOwner The current owner of the specified token
@return `bytes4(keccak256("royaltyReceived(address,uint256,address)"))` if royalty accepted
*/
function royaltyReceived(
address tokenAddress,
uint256 tokenId,
address tokenOwner
)
external payable
returns(bytes4);
}
|
See {IERC1155-balanceOfBatch}. Requirements: - `accounts` and `ids` must have the same length./
|
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
| 20,104 |
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {IUniversalVault} from "./UniversalVault.sol";
import {IRewardPool} from "./RewardPool.sol";
import {IFactory} from "./Factory/IFactory.sol";
import {IInstanceRegistry} from "./Factory/InstanceRegistry.sol";
import {Powered} from "./PowerSwitch/Powered.sol";
interface IRageQuit {
function rageQuit() external;
}
interface IGeyser is IRageQuit {
/* admin events */
event GeyserCreated(address rewardPool, address powerSwitch);
event GeyserFunded(uint256 amount, uint256 duration);
event BonusTokenRegistered(address token);
event VaultFactoryRegistered(address factory);
event VaultFactoryRemoved(address factory);
/* user events */
event Staked(address vault, uint256 amount);
event Unstaked(address vault, uint256 amount);
event RewardClaimed(address vault, address token, uint256 amount);
/* data types */
struct GeyserData {
address stakingToken;
address rewardToken;
address rewardPool;
RewardScaling rewardScaling;
uint256 rewardSharesOutstanding;
uint256 totalStake;
uint256 totalStakeUnits;
uint256 lastUpdate;
RewardSchedule[] rewardSchedules;
}
struct RewardSchedule {
uint256 duration;
uint256 start;
uint256 shares;
}
struct VaultData {
uint256 totalStake;
StakeData[] stakes;
}
struct StakeData {
uint256 amount;
uint256 timestamp;
}
struct RewardScaling {
uint256 floor;
uint256 ceiling;
uint256 time;
}
struct RewardOutput {
uint256 lastStakeAmount;
uint256 newStakesCount;
uint256 reward;
uint256 newTotalStakeUnits;
}
/* user functions */
function stake(
address vault,
uint256 amount,
bytes calldata permission
) external;
function unstakeAndClaim(
address vault,
uint256 amount,
bytes calldata permission
) external;
/* getter functions */
function getGeyserData() external view returns (GeyserData memory geyser);
function getBonusTokenSetLength() external view returns (uint256 length);
function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken);
function getVaultFactorySetLength() external view returns (uint256 length);
function getVaultFactoryAtIndex(uint256 index) external view returns (address factory);
function getVaultData(address vault) external view returns (VaultData memory vaultData);
function isValidAddress(address target) external view returns (bool validity);
function isValidVault(address target) external view returns (bool validity);
function getCurrentUnlockedRewards() external view returns (uint256 unlockedRewards);
function getFutureUnlockedRewards(uint256 timestamp) external view returns (uint256 unlockedRewards);
function getCurrentVaultReward(address vault) external view returns (uint256 reward);
function getCurrentStakeReward(address vault, uint256 stakeAmount) external view returns (uint256 reward);
function getFutureVaultReward(address vault, uint256 timestamp) external view returns (uint256 reward);
function getFutureStakeReward(
address vault,
uint256 stakeAmount,
uint256 timestamp
) external view returns (uint256 reward);
function getCurrentVaultStakeUnits(address vault) external view returns (uint256 stakeUnits);
function getFutureVaultStakeUnits(address vault, uint256 timestamp) external view returns (uint256 stakeUnits);
function getCurrentTotalStakeUnits() external view returns (uint256 totalStakeUnits);
function getFutureTotalStakeUnits(uint256 timestamp) external view returns (uint256 totalStakeUnits);
/* pure functions */
function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp)
external
pure
returns (uint256 totalStakeUnits);
function calculateStakeUnits(
uint256 amount,
uint256 start,
uint256 end
) external pure returns (uint256 stakeUnits);
function calculateUnlockedRewards(
RewardSchedule[] memory rewardSchedules,
uint256 rewardBalance,
uint256 sharesOutstanding,
uint256 timestamp
) external pure returns (uint256 unlockedRewards);
function calculateRewardFromStakes(
StakeData[] memory stakes,
uint256 unstakeAmount,
uint256 unlockedRewards,
uint256 totalStakeUnits,
uint256 timestamp,
RewardScaling memory rewardScaling
) external pure returns (RewardOutput memory out);
function calculateReward(
uint256 unlockedRewards,
uint256 stakeAmount,
uint256 stakeDuration,
uint256 totalStakeUnits,
RewardScaling memory rewardScaling
) external pure returns (uint256 reward);
}
/// @title Geyser
/// @notice Reward distribution contract with time multiplier
/// @dev Security contact: [email protected]
/// Access Control
/// - Power controller:
/// Can power off / shutdown the geyser
/// Can withdraw rewards from reward pool once shutdown
/// - Proxy owner:
/// Can change arbitrary logic / state by upgrading the geyser
/// Is unable to operate on user funds due to UniversalVault
/// Is unable to operate on reward pool funds when reward pool is offline / shutdown
/// - Geyser admin:
/// Can add funds to the geyser, register bonus tokens, and whitelist new vault factories
/// Is a subset of proxy owner permissions
/// - User:
/// Can deposit / withdraw / ragequit
/// Geyser State Machine
/// - Online:
/// Geyser is operating normally, all functions are enabled
/// - Offline:
/// Geyser is temporarely disabled for maintenance
/// User deposits and withdrawls are disabled, ragequit remains enabled
/// Users can withdraw their stake through rageQuit() but forego their pending reward
/// Should only be used when downtime required for an upgrade
/// - Shutdown:
/// Geyser is permanently disabled
/// All functions are disabled with the exception of ragequit
/// Users can withdraw their stake through rageQuit()
/// Power controller can withdraw from the reward pool
/// Should only be used if Proxy Owner role is compromized
contract Geyser is IGeyser, Powered, OwnableUpgradeable {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/* constants */
// An upper bound on the number of active stakes per vault is required to prevent
// calls to rageQuit() from reverting.
// With 30 stakes in a vault, ragequit costs 432811 gas which is conservatively lower
// than the hardcoded limit of 500k gas on the vault.
// This limit is configurable and could be increased in a future deployment.
// Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide
// an error code that allows for reliably catching out-of-gas errors on remote calls.
uint256 public constant MAX_STAKES_PER_VAULT = 30;
uint256 public constant MAX_REWARD_TOKENS = 50;
uint256 public constant BASE_SHARES_PER_WEI = 1000000;
/* storage */
GeyserData private _geyser;
mapping(address => VaultData) private _vaults;
EnumerableSet.AddressSet private _bonusTokenSet;
EnumerableSet.AddressSet private _vaultFactorySet;
/* initializer */
function initializeLock() external initializer {}
/// @notice Initizalize geyser
/// access control: only proxy constructor
/// state machine: can only be called once
/// state scope: set initialization variables
/// token transfer: none
/// @param ownerAddress address The admin address
/// @param rewardPoolFactory address The factory to use for deploying the RewardPool
/// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch
/// @param stakingToken address The address of the staking token for this geyser
/// @param rewardToken address The address of the reward token for this geyser
/// @param rewardScaling RewardScaling The config for reward scaling floor, ceiling, and time
function initialize(
address ownerAddress,
address rewardPoolFactory,
address powerSwitchFactory,
address stakingToken,
address rewardToken,
RewardScaling calldata rewardScaling
) external initializer {
// the scaling floor must be smaller than ceiling
require(rewardScaling.floor <= rewardScaling.ceiling, "Geyser: floor above ceiling");
// setting rewardScalingTime to 0 would cause divide by zero error
// to disable reward scaling, use rewardScalingFloor == rewardScalingCeiling
require(rewardScaling.time != 0, "Geyser: scaling time cannot be zero");
// deploy power switch
address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(ownerAddress));
// deploy reward pool
address rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch));
// set internal configs
OwnableUpgradeable.__Ownable_init();
OwnableUpgradeable.transferOwnership(ownerAddress);
Powered._setPowerSwitch(powerSwitch);
// commit to storage
_geyser.stakingToken = stakingToken;
_geyser.rewardToken = rewardToken;
_geyser.rewardPool = rewardPool;
_geyser.rewardScaling = rewardScaling;
// emit event
emit GeyserCreated(rewardPool, powerSwitch);
}
/* getter functions */
function getBonusTokenSetLength() external view override returns (uint256 length) {
return _bonusTokenSet.length();
}
function getBonusTokenAtIndex(uint256 index) external view override returns (address bonusToken) {
return _bonusTokenSet.at(index);
}
function getVaultFactorySetLength() external view override returns (uint256 length) {
return _vaultFactorySet.length();
}
function getVaultFactoryAtIndex(uint256 index) external view override returns (address factory) {
return _vaultFactorySet.at(index);
}
function isValidVault(address target) public view override returns (bool validity) {
// validate target is created from whitelisted vault factory
for (uint256 index = 0; index < _vaultFactorySet.length(); index++) {
if (IInstanceRegistry(_vaultFactorySet.at(index)).isInstance(target)) {
return true;
}
}
// explicit return
return false;
}
function isValidAddress(address target) public view override returns (bool validity) {
// sanity check target for potential input errors
return
target != address(this) &&
target != address(0) &&
target != _geyser.stakingToken &&
target != _geyser.rewardToken &&
target != _geyser.rewardPool &&
!_bonusTokenSet.contains(target);
}
/* geyser getters */
function getGeyserData() external view override returns (GeyserData memory geyser) {
return _geyser;
}
function getCurrentUnlockedRewards() public view override returns (uint256 unlockedRewards) {
// calculate reward available based on state
return getFutureUnlockedRewards(block.timestamp);
}
function getFutureUnlockedRewards(uint256 timestamp) public view override returns (uint256 unlockedRewards) {
// get reward amount remaining
uint256 remainingRewards = IERC20(_geyser.rewardToken).balanceOf(_geyser.rewardPool);
// calculate reward available based on state
unlockedRewards = calculateUnlockedRewards(
_geyser.rewardSchedules,
remainingRewards,
_geyser.rewardSharesOutstanding,
timestamp
);
// explicit return
return unlockedRewards;
}
function getCurrentTotalStakeUnits() public view override returns (uint256 totalStakeUnits) {
// calculate new stake units
return getFutureTotalStakeUnits(block.timestamp);
}
function getFutureTotalStakeUnits(uint256 timestamp) public view override returns (uint256 totalStakeUnits) {
// return early if no change
if (timestamp == _geyser.lastUpdate) return _geyser.totalStakeUnits;
// calculate new stake units
uint256 newStakeUnits = calculateStakeUnits(_geyser.totalStake, _geyser.lastUpdate, timestamp);
// add to cached total
totalStakeUnits = _geyser.totalStakeUnits.add(newStakeUnits);
// explicit return
return totalStakeUnits;
}
/* vault getters */
function getVaultData(address vault) external view override returns (VaultData memory vaultData) {
return _vaults[vault];
}
function getCurrentVaultReward(address vault) external view override returns (uint256 reward) {
// calculate rewards
return
calculateRewardFromStakes(
_vaults[vault]
.stakes,
_vaults[vault]
.totalStake,
getCurrentUnlockedRewards(),
getCurrentTotalStakeUnits(),
block
.timestamp,
_geyser
.rewardScaling
)
.reward;
}
function getFutureVaultReward(address vault, uint256 timestamp) external view override returns (uint256 reward) {
// calculate rewards
return
calculateRewardFromStakes(
_vaults[vault]
.stakes,
_vaults[vault]
.totalStake,
getFutureUnlockedRewards(timestamp),
getFutureTotalStakeUnits(timestamp),
timestamp,
_geyser
.rewardScaling
)
.reward;
}
function getCurrentStakeReward(address vault, uint256 stakeAmount) external view override returns (uint256 reward) {
// calculate rewards
return
calculateRewardFromStakes(
_vaults[vault]
.stakes,
stakeAmount,
getCurrentUnlockedRewards(),
getCurrentTotalStakeUnits(),
block
.timestamp,
_geyser
.rewardScaling
)
.reward;
}
function getFutureStakeReward(
address vault,
uint256 stakeAmount,
uint256 timestamp
) external view override returns (uint256 reward) {
// calculate rewards
return
calculateRewardFromStakes(
_vaults[vault]
.stakes,
stakeAmount,
getFutureUnlockedRewards(timestamp),
getFutureTotalStakeUnits(timestamp),
timestamp,
_geyser
.rewardScaling
)
.reward;
}
function getCurrentVaultStakeUnits(address vault) public view override returns (uint256 stakeUnits) {
// calculate stake units
return getFutureVaultStakeUnits(vault, block.timestamp);
}
function getFutureVaultStakeUnits(address vault, uint256 timestamp)
public
view
override
returns (uint256 stakeUnits)
{
// calculate stake units
return calculateTotalStakeUnits(_vaults[vault].stakes, timestamp);
}
/* pure functions */
function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp)
public
pure
override
returns (uint256 totalStakeUnits)
{
for (uint256 index; index < stakes.length; index++) {
// reference stake
StakeData memory stakeData = stakes[index];
// calculate stake units
uint256 stakeUnits = calculateStakeUnits(stakeData.amount, stakeData.timestamp, timestamp);
// add to running total
totalStakeUnits = totalStakeUnits.add(stakeUnits);
}
}
function calculateStakeUnits(
uint256 amount,
uint256 start,
uint256 end
) public pure override returns (uint256 stakeUnits) {
// calculate duration
uint256 duration = end.sub(start);
// calculate stake units
stakeUnits = duration.mul(amount);
// explicit return
return stakeUnits;
}
function calculateUnlockedRewards(
RewardSchedule[] memory rewardSchedules,
uint256 rewardBalance,
uint256 sharesOutstanding,
uint256 timestamp
) public pure override returns (uint256 unlockedRewards) {
// return 0 if no registered schedules
if (rewardSchedules.length == 0) {
return 0;
}
// calculate reward shares locked across all reward schedules
uint256 sharesLocked;
for (uint256 index = 0; index < rewardSchedules.length; index++) {
// fetch reward schedule storage reference
RewardSchedule memory schedule = rewardSchedules[index];
// caculate amount of shares available on this schedule
// if (now - start) < duration
// sharesLocked = shares - (shares * (now - start) / duration)
// else
// sharesLocked = 0
uint256 currentSharesLocked = 0;
if (timestamp.sub(schedule.start) < schedule.duration) {
currentSharesLocked = schedule.shares.sub(
schedule.shares.mul(timestamp.sub(schedule.start)).div(schedule.duration)
);
}
// add to running total
sharesLocked = sharesLocked.add(currentSharesLocked);
}
// convert shares to reward
// rewardLocked = sharesLocked * rewardBalance / sharesOutstanding
uint256 rewardLocked = sharesLocked.mul(rewardBalance).div(sharesOutstanding);
// calculate amount available
// unlockedRewards = rewardBalance - rewardLocked
unlockedRewards = rewardBalance.sub(rewardLocked);
// explicit return
return unlockedRewards;
}
function calculateRewardFromStakes(
StakeData[] memory stakes,
uint256 unstakeAmount,
uint256 unlockedRewards,
uint256 totalStakeUnits,
uint256 timestamp,
RewardScaling memory rewardScaling
) public pure override returns (RewardOutput memory out) {
uint256 stakesToDrop = 0;
while (unstakeAmount > 0) {
// fetch vault stake storage reference
StakeData memory lastStake = stakes[stakes.length.sub(stakesToDrop).sub(1)];
// calculate stake duration
uint256 stakeDuration = timestamp.sub(lastStake.timestamp);
uint256 currentAmount;
if (lastStake.amount > unstakeAmount) {
// set current amount to remaining unstake amount
currentAmount = unstakeAmount;
// amount of last stake is reduced
out.lastStakeAmount = lastStake.amount.sub(unstakeAmount);
} else {
// set current amount to amount of last stake
currentAmount = lastStake.amount;
// add to stakes to drop
stakesToDrop += 1;
}
// update remaining unstakeAmount
unstakeAmount = unstakeAmount.sub(currentAmount);
// calculate reward amount
uint256 currentReward =
calculateReward(unlockedRewards, currentAmount, stakeDuration, totalStakeUnits, rewardScaling);
// update cumulative reward
out.reward = out.reward.add(currentReward);
// update cached unlockedRewards
unlockedRewards = unlockedRewards.sub(currentReward);
// calculate time weighted stake
uint256 stakeUnits = currentAmount.mul(stakeDuration);
// update cached totalStakeUnits
totalStakeUnits = totalStakeUnits.sub(stakeUnits);
}
// explicit return
return RewardOutput(out.lastStakeAmount, stakes.length.sub(stakesToDrop), out.reward, totalStakeUnits);
}
function calculateReward(
uint256 unlockedRewards,
uint256 stakeAmount,
uint256 stakeDuration,
uint256 totalStakeUnits,
RewardScaling memory rewardScaling
) public pure override returns (uint256 reward) {
// calculate time weighted stake
uint256 stakeUnits = stakeAmount.mul(stakeDuration);
// calculate base reward
// baseReward = unlockedRewards * stakeUnits / totalStakeUnits
uint256 baseReward = 0;
if (totalStakeUnits != 0) {
// scale reward according to proportional weight
baseReward = unlockedRewards.mul(stakeUnits).div(totalStakeUnits);
}
// calculate scaled reward
// if no scaling or scaling period completed
// reward = baseReward
// else
// minReward = baseReward * scalingFloor / scalingCeiling
// bonusReward = baseReward
// * (scalingCeiling - scalingFloor) / scalingCeiling
// * duration / scalingTime
// reward = minReward + bonusReward
if (stakeDuration >= rewardScaling.time || rewardScaling.floor == rewardScaling.ceiling) {
// no reward scaling applied
reward = baseReward;
} else {
// calculate minimum reward using scaling floor
uint256 minReward = baseReward.mul(rewardScaling.floor).div(rewardScaling.ceiling);
// calculate bonus reward with vested portion of scaling factor
uint256 bonusReward =
baseReward
.mul(stakeDuration)
.mul(rewardScaling.ceiling.sub(rewardScaling.floor))
.div(rewardScaling.ceiling)
.div(rewardScaling.time);
// add minimum reward and bonus reward
reward = minReward.add(bonusReward);
}
// explicit return
return reward;
}
/* admin functions */
/// @notice Add funds to the geyser
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope:
/// - increase _geyser.rewardSharesOutstanding
/// - append to _geyser.rewardSchedules
/// token transfer: transfer staking tokens from msg.sender to reward pool
/// @param amount uint256 Amount of reward tokens to deposit
/// @param duration uint256 Duration over which to linearly unlock rewards
function fundGeyser(uint256 amount, uint256 duration) external onlyOwner onlyOnline {
// validate duration
require(duration != 0, "Geyser: invalid duration");
// create new reward shares
// if existing rewards on this geyser
// mint new shares proportional to % change in rewards remaining
// newShares = remainingShares * newReward / remainingRewards
// else
// mint new shares with BASE_SHARES_PER_WEI initial conversion rate
// store as fixed point number with same of decimals as reward token
uint256 newRewardShares;
if (_geyser.rewardSharesOutstanding > 0) {
uint256 remainingRewards = IERC20(_geyser.rewardToken).balanceOf(_geyser.rewardPool);
newRewardShares = _geyser.rewardSharesOutstanding.mul(amount).div(remainingRewards);
} else {
newRewardShares = amount.mul(BASE_SHARES_PER_WEI);
}
// add reward shares to total
_geyser.rewardSharesOutstanding = _geyser.rewardSharesOutstanding.add(newRewardShares);
// store new reward schedule
_geyser.rewardSchedules.push(RewardSchedule(duration, block.timestamp, newRewardShares));
// transfer reward tokens to reward pool
TransferHelper.safeTransferFrom(_geyser.rewardToken, msg.sender, _geyser.rewardPool, amount);
// emit event
emit GeyserFunded(amount, duration);
}
/// @notice Add vault factory to whitelist
/// @dev use this function to enable stakes to vaults coming from the specified
/// factory contract
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope:
/// - append to _vaultFactorySet
/// token transfer: none
/// @param factory address The address of the vault factory
function registerVaultFactory(address factory) external onlyOwner notShutdown {
// add factory to set
require(_vaultFactorySet.add(factory), "Geyser: vault factory already registered");
// emit event
emit VaultFactoryRegistered(factory);
}
/// @notice Remove vault factory from whitelist
/// @dev use this function to disable new stakes to vaults coming from the specified
/// factory contract.
/// note: vaults with existing stakes from this factory are sill able to unstake
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope:
/// - remove from _vaultFactorySet
/// token transfer: none
/// @param factory address The address of the vault factory
function removeVaultFactory(address factory) external onlyOwner notShutdown {
// remove factory from set
require(_vaultFactorySet.remove(factory), "Geyser: vault factory not registered");
// emit event
emit VaultFactoryRemoved(factory);
}
/// @notice Register bonus token for distribution
/// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope:
/// - append to _bonusTokenSet
/// token transfer: none
/// @param bonusToken address The address of the bonus token
function registerBonusToken(address bonusToken) external onlyOwner onlyOnline {
// verify valid bonus token
_validateAddress(bonusToken);
// verify bonus token count
require(_bonusTokenSet.length() < MAX_REWARD_TOKENS, "Geyser: max bonus tokens reached ");
// add token to set
assert(_bonusTokenSet.add(bonusToken));
// emit event
emit BonusTokenRegistered(bonusToken);
}
/// @notice Rescue tokens from RewardPool
/// @dev use this function to rescue tokens from RewardPool contract
/// without distributing to stakers or triggering emergency shutdown
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope: none
/// token transfer: transfer requested token from RewardPool to recipient
/// @param token address The address of the token to rescue
/// @param recipient address The address of the recipient
/// @param amount uint256 The amount of tokens to rescue
function rescueTokensFromRewardPool(
address token,
address recipient,
uint256 amount
) external onlyOwner onlyOnline {
// verify recipient
_validateAddress(recipient);
// check not attempting to unstake reward token
require(token != _geyser.rewardToken, "Geyser: invalid address");
// check not attempting to wthdraw bonus token
require(!_bonusTokenSet.contains(token), "Geyser: invalid address");
// transfer tokens to recipient
IRewardPool(_geyser.rewardPool).sendERC20(token, recipient, amount);
}
/* user functions */
/// @notice Stake tokens
/// access control: anyone with a valid permission
/// state machine:
/// - can be called multiple times
/// - only online
/// - when vault exists on this geyser
/// state scope:
/// - append to _vaults[vault].stakes
/// - increase _vaults[vault].totalStake
/// - increase _geyser.totalStake
/// - increase _geyser.totalStakeUnits
/// - increase _geyser.lastUpdate
/// token transfer: transfer staking tokens from msg.sender to vault
/// @param vault address The address of the vault to stake from
/// @param amount uint256 The amount of staking tokens to stake
/// @param permission bytes The signed lock permission for the universal vault
function stake(
address vault,
uint256 amount,
bytes calldata permission
) external override onlyOnline {
// verify vault is valid
require(isValidVault(vault), "Geyser: vault is not registered");
// verify non-zero amount
require(amount != 0, "Geyser: no amount staked");
// fetch vault storage reference
VaultData storage vaultData = _vaults[vault];
// verify stakes boundary not reached
require(vaultData.stakes.length < MAX_STAKES_PER_VAULT, "Geyser: MAX_STAKES_PER_VAULT reached");
// update cached sum of stake units across all vaults
_updateTotalStakeUnits();
// store amount and timestamp
vaultData.stakes.push(StakeData(amount, block.timestamp));
// update cached total vault and geyser amounts
vaultData.totalStake = vaultData.totalStake.add(amount);
_geyser.totalStake = _geyser.totalStake.add(amount);
// call lock on vault
IUniversalVault(vault).lock(_geyser.stakingToken, amount, permission);
// emit event
emit Staked(vault, amount);
}
/// @notice Unstake staking tokens and claim reward
/// @dev rewards can only be claimed when unstaking, thus reseting the reward multiplier
/// access control: anyone with a valid permission
/// state machine:
/// - when vault exists on this geyser
/// - after stake from vault
/// - can be called multiple times while sufficient stake remains
/// - only online
/// state scope:
/// - decrease _geyser.rewardSharesOutstanding
/// - decrease _geyser.totalStake
/// - increase _geyser.lastUpdate
/// - modify _geyser.totalStakeUnits
/// - modify _vaults[vault].stakes
/// - decrease _vaults[vault].totalStake
/// token transfer:
/// - transfer reward tokens from reward pool to recipient
/// - transfer bonus tokens from reward pool to recipient
/// @param vault address The vault to unstake from
/// @param amount uint256 The amount of staking tokens to unstake
/// @param permission bytes The signed unlock permission for the universal vault
function unstakeAndClaim(
address vault,
uint256 amount,
bytes calldata permission
) external override onlyOnline {
// fetch vault storage reference
VaultData storage vaultData = _vaults[vault];
// verify non-zero amount
require(amount != 0, "Geyser: no amount unstaked");
// check for sufficient vault stake amount
require(vaultData.totalStake >= amount, "Geyser: insufficient vault stake");
// check for sufficient geyser stake amount
// if this check fails, there is a bug in stake accounting
assert(_geyser.totalStake >= amount);
// update cached sum of stake units across all vaults
_updateTotalStakeUnits();
// get reward amount remaining
uint256 remainingRewards = IERC20(_geyser.rewardToken).balanceOf(_geyser.rewardPool);
// calculate vested portion of reward pool
uint256 unlockedRewards =
calculateUnlockedRewards(
_geyser.rewardSchedules,
remainingRewards,
_geyser.rewardSharesOutstanding,
block.timestamp
);
// calculate vault time weighted reward with scaling
RewardOutput memory out =
calculateRewardFromStakes(
vaultData.stakes,
amount,
unlockedRewards,
_geyser.totalStakeUnits,
block.timestamp,
_geyser.rewardScaling
);
// update stake data in storage
if (out.newStakesCount == 0) {
// all stakes have been unstaked
delete vaultData.stakes;
} else {
// some stakes have been completely or partially unstaked
// delete fully unstaked stakes
while (vaultData.stakes.length > out.newStakesCount) vaultData.stakes.pop();
// only perform when lastStakeAmount is set
if (out.lastStakeAmount > 0) {
// update partially unstaked stake
vaultData.stakes[out.newStakesCount.sub(1)].amount = out.lastStakeAmount;
}
}
// update cached stake totals
vaultData.totalStake = vaultData.totalStake.sub(amount);
_geyser.totalStake = _geyser.totalStake.sub(amount);
_geyser.totalStakeUnits = out.newTotalStakeUnits;
// unlock staking tokens from vault
IUniversalVault(vault).unlock(_geyser.stakingToken, amount, permission);
// emit event
emit Unstaked(vault, amount);
// only perform on non-zero reward
if (out.reward > 0) {
// calculate shares to burn
// sharesToBurn = sharesOutstanding * reward / remainingRewards
uint256 sharesToBurn = _geyser.rewardSharesOutstanding.mul(out.reward).div(remainingRewards);
// burn claimed shares
_geyser.rewardSharesOutstanding = _geyser.rewardSharesOutstanding.sub(sharesToBurn);
// transfer bonus tokens from reward pool to recipient
if (_bonusTokenSet.length() > 0) {
for (uint256 index = 0; index < _bonusTokenSet.length(); index++) {
// fetch bonus token address reference
address bonusToken = _bonusTokenSet.at(index);
// calculate bonus token amount
// bonusAmount = bonusRemaining * reward / remainingRewards
uint256 bonusAmount =
IERC20(bonusToken).balanceOf(_geyser.rewardPool).mul(out.reward).div(remainingRewards);
// transfer if amount is non-zero
if (bonusAmount > 0) {
// transfer bonus token
IRewardPool(_geyser.rewardPool).sendERC20(bonusToken, vault, bonusAmount);
// emit event
emit RewardClaimed(vault, bonusToken, bonusAmount);
}
}
}
// transfer reward tokens from reward pool to recipient
IRewardPool(_geyser.rewardPool).sendERC20(_geyser.rewardToken, vault, out.reward);
// emit event
emit RewardClaimed(vault, _geyser.rewardToken, out.reward);
}
}
/// @notice Exit geyser without claiming reward
/// @dev This function should never revert when correctly called by the vault.
/// A max number of stakes per vault is set with MAX_STAKES_PER_VAULT to
/// place an upper bound on the for loop in calculateTotalStakeUnits().
/// access control: only callable by the vault directly
/// state machine:
/// - when vault exists on this geyser
/// - when active stake from this vault
/// - any power state
/// state scope:
/// - decrease _geyser.totalStake
/// - increase _geyser.lastUpdate
/// - modify _geyser.totalStakeUnits
/// - delete _vaults[vault]
/// token transfer: none
function rageQuit() external override {
// fetch vault storage reference
VaultData storage _vaultData = _vaults[msg.sender];
// revert if no active stakes
require(_vaultData.stakes.length != 0, "Geyser: no stake");
// update cached sum of stake units across all vaults
_updateTotalStakeUnits();
// emit event
emit Unstaked(msg.sender, _vaultData.totalStake);
// update cached totals
_geyser.totalStake = _geyser.totalStake.sub(_vaultData.totalStake);
_geyser.totalStakeUnits = _geyser.totalStakeUnits.sub(
calculateTotalStakeUnits(_vaultData.stakes, block.timestamp)
);
// delete stake data
delete _vaults[msg.sender];
}
/* convenience functions */
function _updateTotalStakeUnits() private {
// update cached totalStakeUnits
_geyser.totalStakeUnits = getCurrentTotalStakeUnits();
// update cached lastUpdate
_geyser.lastUpdate = block.timestamp;
}
function _validateAddress(address target) private view {
// sanity check target for potential input errors
require(isValidAddress(target), "Geyser: invalid address");
}
}
// 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;
/**
* @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.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
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: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {ERC1271} from "./Access/ERC1271.sol";
import {EIP712} from "./Access/EIP712.sol";
import {OwnableERC721} from "./Access/OwnableERC721.sol";
import {IRageQuit} from "./Geyser.sol";
interface IUniversalVault {
/* user events */
event Locked(address delegate, address token, uint256 amount);
event Unlocked(address delegate, address token, uint256 amount);
event RageQuit(address delegate, address token, bool notified, string reason);
/* data types */
struct LockData {
address delegate;
address token;
uint256 balance;
}
/* initialize function */
function initialize() external;
/* user functions */
function lock(
address token,
uint256 amount,
bytes calldata permission
) external;
function unlock(
address token,
uint256 amount,
bytes calldata permission
) external;
function rageQuit(address delegate, address token) external returns (bool notified, string memory error);
function transferERC20(
address token,
address to,
uint256 amount
) external;
function transferETH(address to, uint256 amount) external payable;
/* pure functions */
function calculateLockID(address delegate, address token) external pure returns (bytes32 lockID);
/* getter functions */
function getPermissionHash(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 amount,
uint256 nonce
) external view returns (bytes32 permissionHash);
function getNonce() external view returns (uint256 nonce);
function owner() external view returns (address ownerAddress);
function getLockSetCount() external view returns (uint256 count);
function getLockAt(uint256 index) external view returns (LockData memory lockData);
function getBalanceDelegated(address token, address delegate) external view returns (uint256 balance);
function getBalanceLocked(address token) external view returns (uint256 balance);
function checkBalances() external view returns (bool validity);
}
/// @title UniversalVault
/// @notice Vault for isolated storage of staking tokens
/// @dev Warning: not compatible with rebasing tokens
/// @dev Security contact: [email protected]
contract UniversalVault is IUniversalVault, EIP712("UniversalVault", "1.0.0"), ERC1271, OwnableERC721, Initializable {
using SafeMath for uint256;
using Address for address;
using Address for address payable;
using EnumerableSet for EnumerableSet.Bytes32Set;
/* constant */
// Hardcoding a gas limit for rageQuit() is required to prevent gas DOS attacks
// the gas requirement cannot be determined at runtime by querying the delegate
// as it could potentially be manipulated by a malicious delegate who could force
// the calls to revert.
// The gas limit could alternatively be set upon vault initialization or creation
// of a lock, but the gas consumption trade-offs are not favorable.
// Ultimately, to avoid a need for fixed gas limits, the EVM would need to provide
// an error code that allows for reliably catching out-of-gas errors on remote calls.
uint256 public constant RAGEQUIT_GAS = 500000;
bytes32 public constant LOCK_TYPEHASH =
keccak256("Lock(address delegate,address token,uint256 amount,uint256 nonce)");
bytes32 public constant UNLOCK_TYPEHASH =
keccak256("Unlock(address delegate,address token,uint256 amount,uint256 nonce)");
/* storage */
uint256 private _nonce;
mapping(bytes32 => LockData) private _locks;
EnumerableSet.Bytes32Set private _lockSet;
/* initialization function */
function initializeLock() external initializer {}
function initialize() external override initializer {
OwnableERC721._setNFT(msg.sender);
}
/* ether receive */
receive() external payable {}
/* internal overrides */
function _getOwner() internal view override(ERC1271) returns (address ownerAddress) {
return OwnableERC721.owner();
}
/* pure functions */
function calculateLockID(address delegate, address token) public pure override returns (bytes32 lockID) {
return keccak256(abi.encodePacked(delegate, token));
}
/* getter functions */
function getPermissionHash(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 amount,
uint256 nonce
) public view override returns (bytes32 permissionHash) {
return EIP712._hashTypedDataV4(keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce)));
}
function getNonce() external view override returns (uint256 nonce) {
return _nonce;
}
function owner() public view override(IUniversalVault, OwnableERC721) returns (address ownerAddress) {
return OwnableERC721.owner();
}
function getLockSetCount() external view override returns (uint256 count) {
return _lockSet.length();
}
function getLockAt(uint256 index) external view override returns (LockData memory lockData) {
return _locks[_lockSet.at(index)];
}
function getBalanceDelegated(address token, address delegate) external view override returns (uint256 balance) {
return _locks[calculateLockID(delegate, token)].balance;
}
function getBalanceLocked(address token) public view override returns (uint256 balance) {
uint256 count = _lockSet.length();
for (uint256 index; index < count; index++) {
LockData storage _lockData = _locks[_lockSet.at(index)];
if (_lockData.token == token && _lockData.balance > balance) balance = _lockData.balance;
}
return balance;
}
function checkBalances() external view override returns (bool validity) {
// iterate over all token locks and validate sufficient balance
uint256 count = _lockSet.length();
for (uint256 index; index < count; index++) {
// fetch storage lock reference
LockData storage _lockData = _locks[_lockSet.at(index)];
// if insufficient balance and no∏t shutdown, return false
if (IERC20(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false;
}
// if sufficient balance or shutdown, return true
return true;
}
/* user functions */
/// @notice Lock ERC20 tokens in the vault
/// access control: called by delegate with signed permission from owner
/// state machine: anytime
/// state scope:
/// - insert or update _locks
/// - increase _nonce
/// token transfer: none
/// @param token Address of token being locked
/// @param amount Amount of tokens being locked
/// @param permission Permission signature payload
function lock(
address token,
uint256 amount,
bytes calldata permission
)
external
override
onlyValidSignature(getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce), permission)
{
// get lock id
bytes32 lockID = calculateLockID(msg.sender, token);
// add lock to storage
if (_lockSet.contains(lockID)) {
// if lock already exists, increase amount
_locks[lockID].balance = _locks[lockID].balance.add(amount);
} else {
// if does not exist, create new lock
// add lock to set
assert(_lockSet.add(lockID));
// add lock data to storage
_locks[lockID] = LockData(msg.sender, token, amount);
}
// validate sufficient balance
require(
IERC20(token).balanceOf(address(this)) >= _locks[lockID].balance,
"UniversalVault: insufficient balance"
);
// increase nonce
_nonce += 1;
// emit event
emit Locked(msg.sender, token, amount);
}
/// @notice Unlock ERC20 tokens in the vault
/// access control: called by delegate with signed permission from owner
/// state machine: after valid lock from delegate
/// state scope:
/// - remove or update _locks
/// - increase _nonce
/// token transfer: none
/// @param token Address of token being unlocked
/// @param amount Amount of tokens being unlocked
/// @param permission Permission signature payload
function unlock(
address token,
uint256 amount,
bytes calldata permission
)
external
override
onlyValidSignature(getPermissionHash(UNLOCK_TYPEHASH, msg.sender, token, amount, _nonce), permission)
{
// get lock id
bytes32 lockID = calculateLockID(msg.sender, token);
// validate existing lock
require(_lockSet.contains(lockID), "UniversalVault: missing lock");
// update lock data
if (_locks[lockID].balance > amount) {
// substract amount from lock balance
_locks[lockID].balance = _locks[lockID].balance.sub(amount);
} else {
// delete lock data
delete _locks[lockID];
assert(_lockSet.remove(lockID));
}
// increase nonce
_nonce += 1;
// emit event
emit Unlocked(msg.sender, token, amount);
}
/// @notice Forcibly cancel delegate lock
/// @dev This function will attempt to notify the delegate of the rage quit using
/// a fixed amount of gas.
/// access control: only owner
/// state machine: after valid lock from delegate
/// state scope:
/// - remove item from _locks
/// token transfer: none
/// @param delegate Address of delegate
/// @param token Address of token being unlocked
function rageQuit(address delegate, address token)
external
override
onlyOwner
returns (bool notified, string memory error)
{
// get lock id
bytes32 lockID = calculateLockID(delegate, token);
// validate existing lock
require(_lockSet.contains(lockID), "UniversalVault: missing lock");
// attempt to notify delegate
if (delegate.isContract()) {
// check for sufficient gas
require(gasleft() >= RAGEQUIT_GAS, "UniversalVault: insufficient gas");
// attempt rageQuit notification
try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() {
notified = true;
} catch Error(string memory res) {
notified = false;
error = res;
} catch (bytes memory) {
notified = false;
}
}
// update lock storage
assert(_lockSet.remove(lockID));
delete _locks[lockID];
// emit event
emit RageQuit(delegate, token, notified, error);
}
/// @notice Transfer ERC20 tokens out of vault
/// access control: only owner
/// state machine: when balance >= max(lock) + amount
/// state scope: none
/// token transfer: transfer any token
/// @param token Address of token being transferred
/// @param to Address of the recipient
/// @param amount Amount of tokens to transfer
function transferERC20(
address token,
address to,
uint256 amount
) external override onlyOwner {
// check for sufficient balance
require(
IERC20(token).balanceOf(address(this)) >= getBalanceLocked(token).add(amount),
"UniversalVault: insufficient balance"
);
// perform transfer
TransferHelper.safeTransfer(token, to, amount);
}
/// @notice Transfer ERC20 tokens out of vault
/// access control: only owner
/// state machine: when balance >= amount
/// state scope: none
/// token transfer: transfer any token
/// @param to Address of the recipient
/// @param amount Amount of ETH to transfer
function transferETH(address to, uint256 amount) external payable override onlyOwner {
// perform transfer
TransferHelper.safeTransferETH(to, amount);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {Powered} from "./PowerSwitch/Powered.sol";
interface IRewardPool {
function sendERC20(
address token,
address to,
uint256 value
) external;
function rescueERC20(address[] calldata tokens, address recipient) external;
}
/// @title Reward Pool
/// @notice Vault for isolated storage of reward tokens
/// @dev Security contact: [email protected]
contract RewardPool is IRewardPool, Powered, Ownable {
/* initializer */
constructor(address powerSwitch) {
Powered._setPowerSwitch(powerSwitch);
}
/* user functions */
/// @notice Send an ERC20 token
/// access control: only owner
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope: none
/// token transfer: transfer tokens from self to recipient
/// @param token address The token to send
/// @param to address The recipient to send to
/// @param value uint256 Amount of tokens to send
function sendERC20(
address token,
address to,
uint256 value
) external override onlyOwner onlyOnline {
TransferHelper.safeTransfer(token, to, value);
}
/* emergency functions */
/// @notice Rescue multiple ERC20 tokens
/// access control: only power controller
/// state machine:
/// - can be called multiple times
/// - only shutdown
/// state scope: none
/// token transfer: transfer tokens from self to recipient
/// @param tokens address[] The tokens to rescue
/// @param recipient address The recipient to rescue to
function rescueERC20(address[] calldata tokens, address recipient) external override onlyShutdown {
// only callable by controller
require(msg.sender == Powered.getPowerController(), "RewardPool: only controller can withdraw after shutdown");
// assert recipient is defined
require(recipient != address(0), "RewardPool: recipient not defined");
// transfer tokens
for (uint256 index = 0; index < tokens.length; index++) {
// get token
address token = tokens[index];
// get balance
uint256 balance = IERC20(token).balanceOf(address(this));
// transfer token
TransferHelper.safeTransfer(token, recipient, balance);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
interface IFactory {
function create(bytes calldata args) external returns (address instance);
function create2(bytes calldata args, bytes32 salt) external returns (address instance);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
interface IInstanceRegistry {
/* events */
event InstanceAdded(address instance);
event InstanceRemoved(address instance);
/* view functions */
function isInstance(address instance) external view returns (bool validity);
function instanceCount() external view returns (uint256 count);
function instanceAt(uint256 index) external view returns (address instance);
}
/// @title InstanceRegistry
/// @dev Security contact: [email protected]
contract InstanceRegistry is IInstanceRegistry {
using EnumerableSet for EnumerableSet.AddressSet;
/* storage */
EnumerableSet.AddressSet private _instanceSet;
/* view functions */
function isInstance(address instance) external view override returns (bool validity) {
return _instanceSet.contains(instance);
}
function instanceCount() external view override returns (uint256 count) {
return _instanceSet.length();
}
function instanceAt(uint256 index) external view override returns (address instance) {
return _instanceSet.at(index);
}
/* admin functions */
function _register(address instance) internal {
require(_instanceSet.add(instance), "InstanceRegistry: already registered");
emit InstanceAdded(instance);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {IPowerSwitch} from "./PowerSwitch.sol";
interface IPowered {
function isOnline() external view returns (bool status);
function isOffline() external view returns (bool status);
function isShutdown() external view returns (bool status);
function getPowerSwitch() external view returns (address powerSwitch);
function getPowerController() external view returns (address controller);
}
/// @title Powered
/// @notice Helper for calling external PowerSwitch
/// @dev Security contact: [email protected]
contract Powered is IPowered {
/* storage */
address private _powerSwitch;
/* modifiers */
modifier onlyOnline() {
_onlyOnline();
_;
}
modifier onlyOffline() {
_onlyOffline();
_;
}
modifier notShutdown() {
_notShutdown();
_;
}
modifier onlyShutdown() {
_onlyShutdown();
_;
}
/* initializer */
function _setPowerSwitch(address powerSwitch) internal {
_powerSwitch = powerSwitch;
}
/* getter functions */
function isOnline() public view override returns (bool status) {
return IPowerSwitch(_powerSwitch).isOnline();
}
function isOffline() public view override returns (bool status) {
return IPowerSwitch(_powerSwitch).isOffline();
}
function isShutdown() public view override returns (bool status) {
return IPowerSwitch(_powerSwitch).isShutdown();
}
function getPowerSwitch() public view override returns (address powerSwitch) {
return _powerSwitch;
}
function getPowerController() public view override returns (address controller) {
return IPowerSwitch(_powerSwitch).getPowerController();
}
/* convenience functions */
function _onlyOnline() private view {
require(isOnline(), "Powered: is not online");
}
function _onlyOffline() private view {
require(isOffline(), "Powered: is not offline");
}
function _notShutdown() private view {
require(!isShutdown(), "Powered: is shutdown");
}
function _onlyShutdown() private view {
require(isShutdown(), "Powered: is not shutdown");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
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.7.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
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/Address.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 !Address.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
interface IERC1271 {
function isValidSignature(bytes32 _messageHash, bytes memory _signature) external view returns (bytes4 magicValue);
}
library SignatureChecker {
function isValidSignature(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
if (Address.isContract(signer)) {
bytes4 selector = IERC1271.isValidSignature.selector;
(bool success, bytes memory returndata) =
signer.staticcall(abi.encodeWithSelector(selector, hash, signature));
return success && abi.decode(returndata, (bytes4)) == selector;
} else {
return ECDSA.recover(hash, signature) == signer;
}
}
}
/// @title ERC1271
/// @notice Module for ERC1271 compatibility
/// @dev Security contact: [email protected]
abstract contract ERC1271 is IERC1271 {
// Valid magic value bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 internal constant VALID_SIG = IERC1271.isValidSignature.selector;
// Invalid magic value
bytes4 internal constant INVALID_SIG = bytes4(0);
modifier onlyValidSignature(bytes32 permissionHash, bytes memory signature) {
require(isValidSignature(permissionHash, signature) == VALID_SIG, "ERC1271: Invalid signature");
_;
}
function _getOwner() internal view virtual returns (address owner);
function isValidSignature(bytes32 permissionHash, bytes memory signature) public view override returns (bytes4) {
return SignatureChecker.isValidSignature(_getOwner(), permissionHash, signature) ? VALID_SIG : INVALID_SIG;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/* solhint-disable max-line-length */
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private constant _TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 name,
bytes32 version
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, name, version, _getChainId(), address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal view virtual returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal view virtual returns (bytes32) {
return _HASHED_VERSION;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/// @title OwnableERC721
/// @notice Use ERC721 ownership for access control
/// @dev Security contact: [email protected]
contract OwnableERC721 {
address private _nftAddress;
modifier onlyOwner() {
require(owner() == msg.sender, "OwnableERC721: caller is not the owner");
_;
}
function _setNFT(address nftAddress) internal {
_nftAddress = nftAddress;
}
function nft() public view virtual returns (address nftAddress) {
return _nftAddress;
}
function owner() public view virtual returns (address ownerAddress) {
return IERC721(_nftAddress).ownerOf(uint256(address(this)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.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.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: GPL-3.0-only
pragma solidity 0.7.6;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
interface IPowerSwitch {
/* admin events */
event PowerOn();
event PowerOff();
event EmergencyShutdown();
/* data types */
enum State {Online, Offline, Shutdown}
/* admin functions */
function powerOn() external;
function powerOff() external;
function emergencyShutdown() external;
/* view functions */
function isOnline() external view returns (bool status);
function isOffline() external view returns (bool status);
function isShutdown() external view returns (bool status);
function getStatus() external view returns (State status);
function getPowerController() external view returns (address controller);
}
/// @title PowerSwitch
/// @notice Standalone pausing and emergency stop functionality
/// @dev Security contact: [email protected]
contract PowerSwitch is IPowerSwitch, Ownable {
/* storage */
IPowerSwitch.State private _status;
/* initializer */
constructor(address owner) {
// sanity check owner
require(owner != address(0), "PowerSwitch: invalid owner");
// transfer ownership
Ownable.transferOwnership(owner);
}
/* admin functions */
/// @notice Turn Power On
/// access control: only admin
/// state machine: only when offline
/// state scope: only modify _status
/// token transfer: none
function powerOn() external override onlyOwner {
require(_status == IPowerSwitch.State.Offline, "PowerSwitch: cannot power on");
_status = IPowerSwitch.State.Online;
emit PowerOn();
}
/// @notice Turn Power Off
/// access control: only admin
/// state machine: only when online
/// state scope: only modify _status
/// token transfer: none
function powerOff() external override onlyOwner {
require(_status == IPowerSwitch.State.Online, "PowerSwitch: cannot power off");
_status = IPowerSwitch.State.Offline;
emit PowerOff();
}
/// @notice Shutdown Permanently
/// access control: only admin
/// state machine:
/// - when online or offline
/// - can only be called once
/// state scope: only modify _status
/// token transfer: none
function emergencyShutdown() external override onlyOwner {
require(_status != IPowerSwitch.State.Shutdown, "PowerSwitch: cannot shutdown");
_status = IPowerSwitch.State.Shutdown;
emit EmergencyShutdown();
}
/* getter functions */
function isOnline() external view override returns (bool status) {
return _status == State.Online;
}
function isOffline() external view override returns (bool status) {
return _status == State.Offline;
}
function isShutdown() external view override returns (bool status) {
return _status == State.Shutdown;
}
function getStatus() external view override returns (IPowerSwitch.State status) {
return _status;
}
function getPowerController() external view override returns (address controller) {
return Ownable.owner();
}
}
|
Lock ERC20 tokens in the vault access control: called by delegate with signed permission from owner state machine: anytime state scope: - insert or update _locks - increase _nonce token transfer: none token Address of token being locked amount Amount of tokens being locked permission Permission signature payload get lock id add lock to storage if lock already exists, increase amount if does not exist, create new lock add lock to set add lock data to storage
|
function lock(
address token,
uint256 amount,
bytes calldata permission
)
external
override
onlyValidSignature(getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce), permission)
{
bytes32 lockID = calculateLockID(msg.sender, token);
if (_lockSet.contains(lockID)) {
_locks[lockID].balance = _locks[lockID].balance.add(amount);
assert(_lockSet.add(lockID));
_locks[lockID] = LockData(msg.sender, token, amount);
}
IERC20(token).balanceOf(address(this)) >= _locks[lockID].balance,
"UniversalVault: insufficient balance"
);
}
| 6,862,012 |
./partial_match/1/0x7d1bA2c18CbDE0D790Cc1d626F0c70b3c13C9eec/sources/src/Curve.sol
|
approves a user to spend curve tokens on their behalf _spender the account to allow to spend from msg.sender _amount the amount to specify the spender can spend return success_ the success bool of this call
|
function approve(address _spender, uint256 _amount)
public
nonReentrant
noDelegateCall
returns (bool success_)
{
success_ = Curves.approve(curve, _spender, _amount);
}
| 4,158,774 |
./full_match/1/0x6C0ABAfC02A031c6240462F8707C0913A930091E/sources/Bios.sol
|
mint new Bios tokens to provided address Requirements: - private sale should be active - sender should have private sale minting slots - sender should pay BIOS price for each token numberOfTokens is an amount of tokens to mint/
|
function mintPrivate(uint8 numberOfTokens) public payable {
require(_privateSale, "Private sale is not active!");
require(numberOfTokens > 0, "Number of tokens must be more than 0!");
require(totalSupply() + numberOfTokens <= maxTotalSupply, "Total supply limit have reached!");
require(numberOfTokens <= _allowList[msg.sender], "Not enough presale slots to mint tokens!");
require(BIOS_PRICE * numberOfTokens == msg.value, "Ether value sent is not correct!");
_allowList[msg.sender] = uint8(_allowList[msg.sender] - numberOfTokens);
_mintTokens(msg.sender, numberOfTokens);
payable(_withdrawAddress).transfer(msg.value);
emit addressPrivateSlotsChange(msg.sender, _allowList[msg.sender]);
}
| 16,605,470 |
/**
*Submitted for verification at Etherscan.io on 2021-05-17
*/
// File: contracts/interface/ICoFiXV2VaultForTrader.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
interface ICoFiXV2VaultForTrader {
event RouterAllowed(address router);
event RouterDisallowed(address router);
event ClearPendingRewardOfCNode(uint256 pendingAmount);
event ClearPendingRewardOfLP(uint256 pendingAmount);
function setGovernance(address gov) external;
function setCofiRate(uint256 cofiRate) external;
function allowRouter(address router) external;
function disallowRouter(address router) external;
function calcMiningRate(address pair, uint256 neededETHAmount) external view returns (uint256);
function calcNeededETHAmountForAdjustment(address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount) external view returns (uint256);
function actualMiningAmount(address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 amount, uint256 totalAccruedAmount, uint256 neededETHAmount);
function distributeReward(address pair, uint256 ethAmount, uint256 erc20Amount, address rewardTo) external;
function clearPendingRewardOfCNode() external;
function clearPendingRewardOfLP(address pair) external;
function getPendingRewardOfCNode() external view returns (uint256);
function getPendingRewardOfLP(address pair) external view returns (uint256);
}
// File: contracts/interface/ICoFiXStakingRewards.sol
pragma solidity 0.6.12;
interface ICoFiXStakingRewards {
// Views
/// @dev The rewards vault contract address set in factory contract
/// @return Returns the vault address
function rewardsVault() external view returns (address);
/// @dev The lastBlock reward applicable
/// @return Returns the latest block.number on-chain
function lastBlockRewardApplicable() external view returns (uint256);
/// @dev Reward amount represents by per staking token
function rewardPerToken() external view returns (uint256);
/// @dev How many reward tokens a user has earned but not claimed at present
/// @param account The target account
/// @return The amount of reward tokens a user earned
function earned(address account) external view returns (uint256);
/// @dev How many reward tokens accrued recently
/// @return The amount of reward tokens accrued recently
function accrued() external view returns (uint256);
/// @dev Get the latest reward rate of this mining pool (tokens amount per block)
/// @return The latest reward rate
function rewardRate() external view returns (uint256);
/// @dev How many stakingToken (XToken) deposited into to this reward pool (mining pool)
/// @return The total amount of XTokens deposited in this mining pool
function totalSupply() external view returns (uint256);
/// @dev How many stakingToken (XToken) deposited by the target account
/// @param account The target account
/// @return The total amount of XToken deposited in this mining pool
function balanceOf(address account) external view returns (uint256);
/// @dev Get the address of token for staking in this mining pool
/// @return The staking token address
function stakingToken() external view returns (address);
/// @dev Get the address of token for rewards in this mining pool
/// @return The rewards token address
function rewardsToken() external view returns (address);
// Mutative
/// @dev Stake/Deposit into the reward pool (mining pool)
/// @param amount The target amount
function stake(uint256 amount) external;
/// @dev Stake/Deposit into the reward pool (mining pool) for other account
/// @param other The target account
/// @param amount The target amount
function stakeForOther(address other, uint256 amount) external;
/// @dev Withdraw from the reward pool (mining pool), get the original tokens back
/// @param amount The target amount
function withdraw(uint256 amount) external;
/// @dev Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw() external;
/// @dev Claim the reward the user earned
function getReward() external;
function getRewardAndStake() external;
/// @dev User exit the reward pool, it's actually withdraw and getReward
function exit() external;
/// @dev Add reward to the mining pool
function addReward(uint256 amount) external;
// Events
event RewardAdded(address sender, uint256 reward);
event Staked(address indexed user, uint256 amount);
event StakedForOther(address indexed user, address indexed other, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
}
// File: contracts/interface/ICoFiXVaultForLP.sol
pragma solidity 0.6.12;
interface ICoFiXVaultForLP {
enum POOL_STATE {INVALID, ENABLED, DISABLED}
event NewPoolAdded(address pool, uint256 index);
event PoolEnabled(address pool);
event PoolDisabled(address pool);
function setGovernance(address _new) external;
function setInitCoFiRate(uint256 _new) external;
function setDecayPeriod(uint256 _new) external;
function setDecayRate(uint256 _new) external;
function addPool(address pool) external;
function enablePool(address pool) external;
function disablePool(address pool) external;
function setPoolWeight(address pool, uint256 weight) external;
function batchSetPoolWeight(address[] memory pools, uint256[] memory weights) external;
function distributeReward(address to, uint256 amount) external;
function getPendingRewardOfLP(address pair) external view returns (uint256);
function currentPeriod() external view returns (uint256);
function currentCoFiRate() external view returns (uint256);
function currentPoolRate(address pool) external view returns (uint256 poolRate);
function currentPoolRateByPair(address pair) external view returns (uint256 poolRate);
/// @dev Get the award staking pool address of pair (XToken)
/// @param pair The address of XToken(pair) contract
/// @return pool The pool address
function stakingPoolForPair(address pair) external view returns (address pool);
function getPoolInfo(address pool) external view returns (POOL_STATE state, uint256 weight);
function getPoolInfoByPair(address pair) external view returns (POOL_STATE state, uint256 weight);
function getEnabledPoolCnt() external view returns (uint256);
function getCoFiStakingPool() external view returns (address pool);
}
// File: contracts/interface/ICoFiXERC20.sol
pragma solidity 0.6.12;
interface ICoFiXERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
// function name() external pure returns (string memory);
// function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// File: contracts/interface/ICoFiXV2Pair.sol
pragma solidity 0.6.12;
interface ICoFiXV2Pair is ICoFiXERC20 {
struct OraclePrice {
uint256 ethAmount;
uint256 erc20Amount;
uint256 blockNum;
uint256 K;
uint256 theta;
}
// All pairs: {ETH <-> ERC20 Token}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, address outToken, uint outAmount, address indexed to);
event Swap(
address indexed sender,
uint amountIn,
uint amountOut,
address outToken,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1);
function mint(address to, uint amountETH, uint amountToken) external payable returns (uint liquidity, uint oracleFeeChange);
function burn(address tokenTo, address ethTo) external payable returns (uint amountTokenOut, uint amountETHOut, uint oracleFeeChange);
function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[5] memory tradeInfo);
// function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function skim(address to) external;
function sync() external;
function initialize(address, address, string memory, string memory, uint256, uint256) external;
/// @dev get Net Asset Value Per Share
/// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token}
/// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token}
/// @return navps The Net Asset Value Per Share (liquidity) represents
function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps);
/// @dev get initial asset ratio
/// @return _initToken0Amount Token0(ETH) side of initial asset ratio {ETH <-> ERC20 Token}
/// @return _initToken1Amount Token1(ERC20) side of initial asset ratio {ETH <-> ERC20 Token}
function getInitialAssetRatio() external view returns (uint256 _initToken0Amount, uint256 _initToken1Amount);
}
// File: contracts/interface/IWETH.sol
pragma solidity 0.6.12;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
function balanceOf(address account) external view returns (uint);
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/interface/ICoFiXV2Router.sol
pragma solidity 0.6.12;
interface ICoFiXV2Router {
function factory() external pure returns (address);
function WETH() external pure returns (address);
enum DEX_TYPE { COFIX, UNISWAP }
// All pairs: {ETH <-> ERC20 Token}
/// @dev Maker add liquidity to pool, get pool token (mint XToken to maker) (notice: msg.value = amountETH + oracle fee)
/// @param token The address of ERC20 Token
/// @param amountETH The amount of ETH added to pool
/// @param amountToken The amount of Token added to pool
/// @param liquidityMin The minimum liquidity maker wanted
/// @param to The target address receiving the liquidity pool (XToken)
/// @param deadline The dealine of this request
/// @return liquidity The real liquidity or XToken minted from pool
function addLiquidity(
address token,
uint amountETH,
uint amountToken,
uint liquidityMin,
address to,
uint deadline
) external payable returns (uint liquidity);
/// @dev Maker add liquidity to pool, get pool token (mint XToken) and stake automatically (notice: msg.value = amountETH + oracle fee)
/// @param token The address of ERC20 Token
/// @param amountETH The amount of ETH added to pool
/// @param amountToken The amount of Token added to pool
/// @param liquidityMin The minimum liquidity maker wanted
/// @param to The target address receiving the liquidity pool (XToken)
/// @param deadline The dealine of this request
/// @return liquidity The real liquidity or XToken minted from pool
function addLiquidityAndStake(
address token,
uint amountETH,
uint amountToken,
uint liquidityMin,
address to,
uint deadline
) external payable returns (uint liquidity);
/// @dev Maker remove liquidity from pool to get ERC20 Token and ETH back (maker burn XToken) (notice: msg.value = oracle fee)
/// @param token The address of ERC20 Token
/// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove
/// @param amountETHMin The minimum amount of ETH wanted to get from pool
/// @param to The target address receiving the Token
/// @param deadline The dealine of this request
/// @return amountToken The real amount of Token transferred from the pool
/// @return amountETH The real amount of ETH transferred from the pool
function removeLiquidityGetTokenAndETH(
address token,
uint liquidity,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH);
/// @dev Trader swap exact amount of ETH for ERC20 Tokens (notice: msg.value = amountIn + oracle fee)
/// @param token The address of ERC20 Token
/// @param amountIn The exact amount of ETH a trader want to swap into pool
/// @param amountOutMin The minimum amount of Token a trader want to swap out of pool
/// @param to The target address receiving the Token
/// @param rewardTo The target address receiving the CoFi Token as rewards
/// @param deadline The dealine of this request
/// @return _amountIn The real amount of ETH transferred into pool
/// @return _amountOut The real amount of Token transferred out of pool
function swapExactETHForTokens(
address token,
uint amountIn,
uint amountOutMin,
address to,
address rewardTo,
uint deadline
) external payable returns (uint _amountIn, uint _amountOut);
/// @dev Trader swap exact amount of ERC20 Tokens for ETH (notice: msg.value = oracle fee)
/// @param token The address of ERC20 Token
/// @param amountIn The exact amount of Token a trader want to swap into pool
/// @param amountOutMin The mininum amount of ETH a trader want to swap out of pool
/// @param to The target address receiving the ETH
/// @param rewardTo The target address receiving the CoFi Token as rewards
/// @param deadline The dealine of this request
/// @return _amountIn The real amount of Token transferred into pool
/// @return _amountOut The real amount of ETH transferred out of pool
function swapExactTokensForETH(
address token,
uint amountIn,
uint amountOutMin,
address to,
address rewardTo,
uint deadline
) external payable returns (uint _amountIn, uint _amountOut);
/// @dev Trader swap exact amount of ERC20 Tokens for other ERC20 Tokens (notice: msg.value = oracle fee)
/// @param tokenIn The address of ERC20 Token a trader want to swap into pool
/// @param tokenOut The address of ERC20 Token a trader want to swap out of pool
/// @param amountIn The exact amount of Token a trader want to swap into pool
/// @param amountOutMin The mininum amount of ETH a trader want to swap out of pool
/// @param to The target address receiving the Token
/// @param rewardTo The target address receiving the CoFi Token as rewards
/// @param deadline The dealine of this request
/// @return _amountIn The real amount of Token transferred into pool
/// @return _amountOut The real amount of Token transferred out of pool
function swapExactTokensForTokens(
address tokenIn,
address tokenOut,
uint amountIn,
uint amountOutMin,
address to,
address rewardTo,
uint deadline
) external payable returns (uint _amountIn, uint _amountOut);
/// @dev Swaps an exact amount of input tokens for as many output tokens as possible, along the route determined by the path. The first element of path is the input token, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist). `msg.sender` should have already given the router an allowance of at least amountIn on the input token. The swap execution can be done via cofix or uniswap. That's why it's called hybrid.
/// @param amountIn The amount of input tokens to send.
/// @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.
/// @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.
/// @param dexes An array of dex type values, specifying the exchanges to be used, e.g. CoFiX, Uniswap.
/// @param to Recipient of the output tokens.
/// @param rewardTo The target address receiving the CoFi Token as rewards.
/// @param deadline Unix timestamp after which the transaction will revert.
/// @return amounts The input token amount and all subsequent output token amounts.
function hybridSwapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
DEX_TYPE[] calldata dexes,
address to,
address rewardTo,
uint deadline
) external payable returns (uint[] memory amounts);
/// @dev Swaps an exact amount of ETH for as many output tokens as possible, along the route determined by the path. The first element of path must be WETH, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).
/// @param amountIn The amount of input tokens to send.
/// @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.
/// @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.
/// @param dexes An array of dex type values, specifying the exchanges to be used, e.g. CoFiX, Uniswap.
/// @param to Recipient of the output tokens.
/// @param rewardTo The target address receiving the CoFi Token as rewards.
/// @param deadline Unix timestamp after which the transaction will revert.
/// @return amounts The input token amount and all subsequent output token amounts.
function hybridSwapExactETHForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
DEX_TYPE[] calldata dexes,
address to,
address rewardTo,
uint deadline
) external payable returns (uint[] memory amounts);
/// @dev Swaps an exact amount of tokens for as much ETH as possible, along the route determined by the path. The first element of path is the input token, the last must be WETH, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist). If the to address is a smart contract, it must have the ability to receive ETH.
/// @param amountIn The amount of input tokens to send.
/// @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.
/// @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.
/// @param dexes An array of dex type values, specifying the exchanges to be used, e.g. CoFiX, Uniswap.
/// @param to Recipient of the output tokens.
/// @param rewardTo The target address receiving the CoFi Token as rewards.
/// @param deadline Unix timestamp after which the transaction will revert.
/// @return amounts The input token amount and all subsequent output token amounts.
function hybridSwapExactTokensForETH(
uint amountIn,
uint amountOutMin,
address[] calldata path,
DEX_TYPE[] calldata dexes,
address to,
address rewardTo,
uint deadline
) external payable returns (uint[] memory amounts);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: contracts/lib/UniswapV2Library.sol
pragma solidity 0.6.12;
interface IUniswapV2Pair {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) 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, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// File: contracts/lib/TransferHelper.sol
pragma solidity 0.6.12;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: contracts/interface/ICoFiXV2Factory.sol
pragma solidity 0.6.12;
interface ICoFiXV2Factory {
// All pairs: {ETH <-> ERC20 Token}
event PairCreated(address indexed token, address pair, uint256);
event NewGovernance(address _new);
event NewController(address _new);
event NewFeeReceiver(address _new);
event NewFeeVaultForLP(address token, address feeVault);
event NewVaultForLP(address _new);
event NewVaultForTrader(address _new);
event NewVaultForCNode(address _new);
event NewDAO(address _new);
/// @dev Create a new token pair for trading
/// @param token the address of token to trade
/// @param initToken0Amount the initial asset ratio (initToken0Amount:initToken1Amount)
/// @param initToken1Amount the initial asset ratio (initToken0Amount:initToken1Amount)
/// @return pair the address of new token pair
function createPair(
address token,
uint256 initToken0Amount,
uint256 initToken1Amount
)
external
returns (address pair);
function getPair(address token) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function getTradeMiningStatus(address token) external view returns (bool status);
function setTradeMiningStatus(address token, bool status) external;
function getFeeVaultForLP(address token) external view returns (address feeVault); // for LPs
function setFeeVaultForLP(address token, address feeVault) external;
function setGovernance(address _new) external;
function setController(address _new) external;
function setFeeReceiver(address _new) external;
function setVaultForLP(address _new) external;
function setVaultForTrader(address _new) external;
function setVaultForCNode(address _new) external;
function setDAO(address _new) external;
function getController() external view returns (address controller);
function getFeeReceiver() external view returns (address feeReceiver); // For CoFi Holders
function getVaultForLP() external view returns (address vaultForLP);
function getVaultForTrader() external view returns (address vaultForTrader);
function getVaultForCNode() external view returns (address vaultForCNode);
function getDAO() external view returns (address dao);
}
// File: contracts/CoFiXV2Router.sol
pragma solidity 0.6.12;
// Router contract to interact with each CoFiXPair, no owner or governance
contract CoFiXV2Router is ICoFiXV2Router {
using SafeMath for uint;
address public immutable override factory;
address public immutable uniFactory;
address public immutable override WETH;
uint256 internal constant NEST_ORACLE_FEE = 0.01 ether;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'CRouter: EXPIRED');
_;
}
constructor(address _factory, address _uniFactory, address _WETH) public {
factory = _factory;
uniFactory = _uniFactory;
WETH = _WETH;
}
receive() external payable {}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address _factory, address token) internal view returns (address pair) {
// pair = address(uint(keccak256(abi.encodePacked(
// hex'ff',
// _factory,
// keccak256(abi.encodePacked(token)),
// hex'fb0c5470b7fbfce7f512b5035b5c35707fd5c7bd43c8d81959891b0296030118' // init code hash
// )))); // calc the real init code hash, not suitable for us now, could use this in the future
return ICoFiXV2Factory(_factory).getPair(token);
}
// msg.value = amountETH + oracle fee
function addLiquidity(
address token,
uint amountETH,
uint amountToken,
uint liquidityMin,
address to,
uint deadline
) external override payable ensure(deadline) returns (uint liquidity)
{
require(msg.value > amountETH, "CRouter: insufficient msg.value");
uint256 _oracleFee = msg.value.sub(amountETH);
address pair = pairFor(factory, token);
if (amountToken > 0 ) { // support for tokens which do not allow to transfer zero values
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
}
if (amountETH > 0) {
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
}
uint256 oracleFeeChange;
(liquidity, oracleFeeChange) = ICoFiXV2Pair(pair).mint{value: _oracleFee}(to, amountETH, amountToken);
require(liquidity >= liquidityMin, "CRouter: less liquidity than expected");
// refund oracle fee to msg.sender, if any
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
}
// msg.value = amountETH + oracle fee
function addLiquidityAndStake(
address token,
uint amountETH,
uint amountToken,
uint liquidityMin,
address to,
uint deadline
) external override payable ensure(deadline) returns (uint liquidity)
{
// must create a pair before using this function
require(msg.value > amountETH, "CRouter: insufficient msg.value");
uint256 _oracleFee = msg.value.sub(amountETH);
address pair = pairFor(factory, token);
require(pair != address(0), "CRouter: invalid pair");
if (amountToken > 0 ) { // support for tokens which do not allow to transfer zero values
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
}
if (amountETH > 0) {
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
}
uint256 oracleFeeChange;
(liquidity, oracleFeeChange) = ICoFiXV2Pair(pair).mint{value: _oracleFee}(address(this), amountETH, amountToken);
require(liquidity >= liquidityMin, "CRouter: less liquidity than expected");
// find the staking rewards pool contract for the liquidity token (pair)
address pool = ICoFiXVaultForLP(ICoFiXV2Factory(factory).getVaultForLP()).stakingPoolForPair(pair);
require(pool != address(0), "CRouter: invalid staking pool");
// approve to staking pool
ICoFiXV2Pair(pair).approve(pool, liquidity);
ICoFiXStakingRewards(pool).stakeForOther(to, liquidity);
ICoFiXV2Pair(pair).approve(pool, 0); // ensure
// refund oracle fee to msg.sender, if any
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
}
// msg.value = oracle fee
function removeLiquidityGetTokenAndETH(
address token,
uint liquidity,
uint amountETHMin,
address to,
uint deadline
) external override payable ensure(deadline) returns (uint amountToken, uint amountETH)
{
require(msg.value > 0, "CRouter: insufficient msg.value");
address pair = pairFor(factory, token);
ICoFiXV2Pair(pair).transferFrom(msg.sender, pair, liquidity);
uint oracleFeeChange;
(amountToken, amountETH, oracleFeeChange) = ICoFiXV2Pair(pair).burn{value: msg.value}(to, address(this));
require(amountETH >= amountETHMin, "CRouter: got less than expected");
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
// refund oracle fee to msg.sender, if any
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
}
// msg.value = amountIn + oracle fee
function swapExactETHForTokens(
address token,
uint amountIn,
uint amountOutMin,
address to,
address rewardTo,
uint deadline
) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut)
{
require(msg.value > amountIn, "CRouter: insufficient msg.value");
IWETH(WETH).deposit{value: amountIn}();
address pair = pairFor(factory, token);
assert(IWETH(WETH).transfer(pair, amountIn));
uint oracleFeeChange;
uint256[5] memory tradeInfo;
(_amountIn, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXV2Pair(pair).swapWithExact{
value: msg.value.sub(amountIn)}(token, to);
require(_amountOut >= amountOutMin, "CRouter: got less than expected");
// distribute trading rewards - CoFi!
address vaultForTrader = ICoFiXV2Factory(factory).getVaultForTrader();
if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) {
ICoFiXV2VaultForTrader(vaultForTrader).distributeReward(pair, tradeInfo[1], tradeInfo[2], rewardTo);
}
// refund oracle fee to msg.sender, if any
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
}
// msg.value = oracle fee
function swapExactTokensForTokens(
address tokenIn,
address tokenOut,
uint amountIn,
uint amountOutMin,
address to,
address rewardTo,
uint deadline
) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut) {
require(msg.value > 0, "CRouter: insufficient msg.value");
address[2] memory pairs; // [pairIn, pairOut]
// swapExactTokensForETH
pairs[0] = pairFor(factory, tokenIn);
TransferHelper.safeTransferFrom(tokenIn, msg.sender, pairs[0], amountIn);
uint oracleFeeChange;
uint256[5] memory tradeInfo;
(_amountIn, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXV2Pair(pairs[0]).swapWithExact{value: msg.value}(WETH, address(this));
// distribute trading rewards - CoFi!
address vaultForTrader = ICoFiXV2Factory(factory).getVaultForTrader();
if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) {
ICoFiXV2VaultForTrader(vaultForTrader).distributeReward(pairs[0], tradeInfo[1], tradeInfo[2], rewardTo);
}
// swapExactETHForTokens
pairs[1] = pairFor(factory, tokenOut);
assert(IWETH(WETH).transfer(pairs[1], _amountOut)); // swap with all amountOut in last swap
(, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXV2Pair(pairs[1]).swapWithExact{value: oracleFeeChange}(tokenOut, to);
require(_amountOut >= amountOutMin, "CRouter: got less than expected");
// distribute trading rewards - CoFi!
if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) {
ICoFiXV2VaultForTrader(vaultForTrader).distributeReward(pairs[1], tradeInfo[1], tradeInfo[2], rewardTo);
}
// refund oracle fee to msg.sender, if any
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
}
// msg.value = oracle fee
function swapExactTokensForETH(
address token,
uint amountIn,
uint amountOutMin,
address to,
address rewardTo,
uint deadline
) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut)
{
require(msg.value > 0, "CRouter: insufficient msg.value");
address pair = pairFor(factory, token);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountIn);
uint oracleFeeChange;
uint256[5] memory tradeInfo;
(_amountIn, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXV2Pair(pair).swapWithExact{value: msg.value}(WETH, address(this));
require(_amountOut >= amountOutMin, "CRouter: got less than expected");
IWETH(WETH).withdraw(_amountOut);
TransferHelper.safeTransferETH(to, _amountOut);
// distribute trading rewards - CoFi!
address vaultForTrader = ICoFiXV2Factory(factory).getVaultForTrader();
if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) {
ICoFiXV2VaultForTrader(vaultForTrader).distributeReward(pair, tradeInfo[1], tradeInfo[2], rewardTo);
}
// refund oracle fee to msg.sender, if any
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
}
function hybridSwapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
DEX_TYPE[] calldata dexes,
address to,
address rewardTo,
uint deadline
) external override payable ensure(deadline) returns (uint[] memory amounts) {
// fast check
require(path.length >= 2, "CRouter: invalid path");
require(dexes.length == path.length - 1, "CRouter: invalid dexes");
_checkOracleFee(dexes, msg.value);
// send amountIn to the first pair
TransferHelper.safeTransferFrom(
path[0], msg.sender, getPairForDEX(path[0], path[1], dexes[0]), amountIn
);
// exec hybridSwap
amounts = new uint[](path.length);
amounts[0] = amountIn;
_hybridSwap(path, dexes, amounts, to, rewardTo);
// check amountOutMin in the last
require(amounts[amounts.length - 1] >= amountOutMin, "CRouter: insufficient output amount ");
}
function hybridSwapExactETHForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
DEX_TYPE[] calldata dexes,
address to,
address rewardTo,
uint deadline
) external override payable ensure(deadline) returns (uint[] memory amounts) {
// fast check
require(path.length >= 2 && path[0] == WETH, "CRouter: invalid path");
require(dexes.length == path.length - 1, "CRouter: invalid dexes");
_checkOracleFee(dexes, msg.value.sub(amountIn)); // would revert if msg.value is less than amountIn
// convert ETH and send amountIn to the first pair
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(getPairForDEX(path[0], path[1], dexes[0]), amountIn));
// exec hybridSwap
amounts = new uint[](path.length);
amounts[0] = amountIn;
_hybridSwap(path, dexes, amounts, to, rewardTo);
// check amountOutMin in the last
require(amounts[amounts.length - 1] >= amountOutMin, "CRouter: insufficient output amount ");
}
function hybridSwapExactTokensForETH(
uint amountIn,
uint amountOutMin,
address[] calldata path,
DEX_TYPE[] calldata dexes,
address to,
address rewardTo,
uint deadline
) external override payable ensure(deadline) returns (uint[] memory amounts) {
// fast check
require(path.length >= 2 && path[path.length - 1] == WETH, "CRouter: invalid path");
require(dexes.length == path.length - 1, "CRouter: invalid dexes");
_checkOracleFee(dexes, msg.value);
// send amountIn to the first pair
TransferHelper.safeTransferFrom(
path[0], msg.sender, getPairForDEX(path[0], path[1], dexes[0]), amountIn
);
// exec hybridSwap
amounts = new uint[](path.length);
amounts[0] = amountIn;
_hybridSwap(path, dexes, amounts, address(this), rewardTo);
// check amountOutMin in the last
require(amounts[amounts.length - 1] >= amountOutMin, "CRouter: insufficient output amount ");
// convert WETH
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function _checkOracleFee(DEX_TYPE[] memory dexes, uint256 oracleFee) internal pure {
uint cofixCnt;
for (uint i; i < dexes.length; i++) {
if (dexes[i] == DEX_TYPE.COFIX) {
cofixCnt++;
}
}
// strict check here
// to simplify the verify logic for oracle fee and prevent user from locking oracle fee by mistake
// if NEST_ORACLE_FEE value changed, this router would not work as expected
// TODO: refund the oracle fee?
require(oracleFee == NEST_ORACLE_FEE.mul(cofixCnt), "CRouter: wrong oracle fee");
}
function _hybridSwap(address[] memory path, DEX_TYPE[] memory dexes, uint[] memory amounts, address _to, address rewardTo) internal {
for (uint i; i < path.length - 1; i++) {
if (dexes[i] == DEX_TYPE.COFIX) {
_swapOnCoFiX(i, path, dexes, amounts, _to, rewardTo);
} else if (dexes[i] == DEX_TYPE.UNISWAP) {
_swapOnUniswap(i, path, dexes, amounts, _to);
} else {
revert("CRouter: unknown dex");
}
}
}
function _swapOnUniswap(uint i, address[] memory path, DEX_TYPE[] memory dexes, uint[] memory amounts, address _to) internal {
address pair = getPairForDEX(path[i], path[i + 1], DEX_TYPE.UNISWAP);
(address token0,) = UniswapV2Library.sortTokens(path[i], path[i + 1]);
{
(uint reserveIn, uint reserveOut) = UniswapV2Library.getReserves(uniFactory, path[i], path[i + 1]);
amounts[i + 1] = UniswapV2Library.getAmountOut(amounts[i], reserveIn, reserveOut);
}
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = path[i] == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to;
{
if (i < path.length - 2) {
to = getPairForDEX(path[i + 1], path[i + 2], dexes[i + 1]);
} else {
to = _to;
}
}
IUniswapV2Pair(pair).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
function _swapOnCoFiX(uint i, address[] memory path, DEX_TYPE[] memory dexes, uint[] memory amounts, address _to, address rewardTo) internal {
address pair = getPairForDEX(path[i], path[i + 1], DEX_TYPE.COFIX);
address to;
if (i < path.length - 2) {
to = getPairForDEX(path[i + 1], path[i + 2], dexes[i + 1]);
} else {
to = _to;
}
// TODO: dynamic oracle fee
{
uint256[5] memory tradeInfo;
(,amounts[i+1],,tradeInfo) = ICoFiXV2Pair(pair).swapWithExact{value: NEST_ORACLE_FEE}(path[i + 1], to);
// distribute trading rewards - CoFi!
address vaultForTrader = ICoFiXV2Factory(factory).getVaultForTrader();
if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) {
ICoFiXV2VaultForTrader(vaultForTrader).distributeReward(pair, tradeInfo[1], tradeInfo[2], rewardTo);
}
}
}
function isCoFiXNativeSupported(address input, address output) public view returns (bool supported, address pair) {
// NO WETH included
if (input != WETH && output != WETH)
return (false, pair);
if (input != WETH) {
pair = pairFor(factory, input);
} else if (output != WETH) {
pair = pairFor(factory, output);
}
// if tokenIn & tokenOut are both WETH, then the pair is zero
if (pair != address(0)) // TODO: add check for reserves
supported = true;
return (supported, pair);
}
function getPairForDEX(address input, address output, DEX_TYPE dex) public view returns (address pair) {
if (dex == DEX_TYPE.COFIX) {
bool supported;
(supported, pair) = isCoFiXNativeSupported(input, output);
if (!supported) {
revert("CRouter: not available on CoFiX");
}
} else if (dex == DEX_TYPE.UNISWAP) {
pair = UniswapV2Library.pairFor(uniFactory, input, output);
} else {
revert("CRouter: unknown dex");
}
}
// TODO: not used currently
function hybridPair(address input, address output) public view returns (bool useCoFiX, address pair) {
(useCoFiX, pair) = isCoFiXNativeSupported(input, output);
if (useCoFiX) {
return (useCoFiX, pair);
}
return (false, UniswapV2Library.pairFor(uniFactory, input, output));
}
}
|
msg.value = amountIn + oracle fee
|
{
require(msg.value > amountIn, "CRouter: insufficient msg.value");
address pair = pairFor(factory, token);
assert(IWETH(WETH).transfer(pair, amountIn));
uint oracleFeeChange;
uint256[5] memory tradeInfo;
IWETH(WETH).deposit{value: amountIn}();
function addLiquidityAndStake(
address token,
uint amountETH,
uint amountToken,
uint liquidityMin,
address to,
uint deadline
) external override payable ensure(deadline) returns (uint liquidity)
}
}
uint256 oracleFeeChange;
require(liquidity >= liquidityMin, "CRouter: less liquidity than expected");
address pool = ICoFiXVaultForLP(ICoFiXV2Factory(factory).getVaultForLP()).stakingPoolForPair(pair);
require(pool != address(0), "CRouter: invalid staking pool");
ICoFiXV2Pair(pair).approve(pool, liquidity);
ICoFiXStakingRewards(pool).stakeForOther(to, liquidity);
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
}
function removeLiquidityGetTokenAndETH(
address token,
uint liquidity,
uint amountETHMin,
address to,
uint deadline
) external override payable ensure(deadline) returns (uint amountToken, uint amountETH)
}
function swapExactETHForTokens(
address token,
uint amountIn,
uint amountOutMin,
address to,
address rewardTo,
uint deadline
) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut)
(_amountIn, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXV2Pair(pair).swapWithExact{
value: msg.value.sub(amountIn)}(token, to);
require(_amountOut >= amountOutMin, "CRouter: got less than expected");
address vaultForTrader = ICoFiXV2Factory(factory).getVaultForTrader();
if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) {
ICoFiXV2VaultForTrader(vaultForTrader).distributeReward(pair, tradeInfo[1], tradeInfo[2], rewardTo);
}
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
}
| 6,573,594 |
./partial_match/1/0x21114F10332585C5223963FFa384E112C88459EB/sources/@gearbox-protocol/integrations-v2/contracts/adapters/curve/CurveV1_3.sol
|
Sends an order to remove liquidity from a Curve pool in exact token amounts amounts Amounts of coins to withdraw `max_burn_amount` is ignored since the calldata is routed directly to the target Internal implementation details in CurveV1Base
|
function remove_liquidity_imbalance(
uint256[N_COINS] calldata amounts,
uint256
) external virtual override nonReentrant {
_remove_liquidity_imbalance(
amounts[0] > 1,
amounts[1] > 1,
amounts[2] > 1,
false
}
| 4,213,725 |
pragma solidity ^0.4.22;
import "./IDaoBase.sol";
import "./DaoBase.sol";
import "./ImpersonationCaller.sol";
import "./utils/UtilsLib.sol";
/**
* @title DaoBaseImpersonated
* @dev This contract is a helper that will call the action is not allowed directly (by the current user) on behalf of the other user.
* It is calling it really without any 'delegatecall' so msg.sender will be DaoBaseImpersonated, not the original user!
*
* WARNING: As long as this contract is just an ordinary DaoBase client -> you should give permissions to it
* just like to any other account/contract. So you should give 'manageGroups', 'issueTokens', etc to the DaoBaseImpersonated!
* Please see 'tests' folder for example.
*/
contract DaoBaseImpersonated is ImpersonationCaller {
constructor(IDaoBase _daoBase)public
ImpersonationCaller(_daoBase)
{
}
/**
* @param _hash hash of the message which account sign
* @param _sig signature of the account which have rights for action needed
* @param _token address of token
* @param _to address which will get all issued tokens
* @param _amount amount of tokens which will be issued
* @dev this function allow any account issue tokens on behalf by account which have needed rights by signing specified message
*/
function issueTokensImp(bytes32 _hash, bytes _sig, address _token, address _to, uint _amount) public {
bytes32[] memory params = new bytes32[](3);
params[0] = bytes32(_token);
params[1] = bytes32(_to);
params[2] = bytes32(_amount);
doActionOnBehalfOf(
_hash,
_sig,
DaoBase(daoBase).ISSUE_TOKENS(),
"issueTokensGeneric(bytes32[])",
params
);
}
/**
* @param _hash hash of the message which account sign
* @param _sig signature of the account which have rights for action needed
* @param _newMc new DaoBase instance (address)
* @dev this function allow any account upgrade DAO contract on behalf by account which have needed rights by signing specified message
*/
function upgradeDaoContractImp(bytes32 _hash, bytes _sig, address _newMc) public {
bytes32[] memory params = new bytes32[](1);
params[0] = bytes32(_newMc);
doActionOnBehalfOf(
_hash,
_sig,
DaoBase(daoBase).UPGRADE_DAO_CONTRACT(),
"upgradeDaoContractGeneric(bytes32[])",
params
);
}
/**
* @param _hash hash of the message which account sign
* @param _sig signature of the account which have rights for action needed
* @param _group name of the group in storage
* @param _a address which will be added to the group with name _group
* @dev this function allow any account add group member on behalf by account which have needed rights by signing specified message
*/
function addGroupMemberImp(bytes32 _hash, bytes _sig, string _group, address _a) public {
bytes32[] memory params = new bytes32[](2);
params[0] = UtilsLib.stringToBytes32(_group);
params[1] = bytes32(_a);
doActionOnBehalfOf(
_hash,
_sig,
DaoBase(daoBase).MANAGE_GROUPS(),
"addGroupMemberGeneric(bytes32[])",
params
);
}
/**
* @param _hash hash of the message which account sign
* @param _sig signature of the account which have rights for action needed
* @param _groupName name of the group in storage
* @param _a address which will be removed from the group with name _groupName
* @dev this function allow any account remove group member on behalf by account which have needed rights by signing specified message
*/
function removeGroupMemberImp(bytes32 _hash, bytes _sig, string _groupName, address _a) public {
bytes32[] memory params = new bytes32[](2);
params[0] = UtilsLib.stringToBytes32(_groupName);
params[1] = bytes32(_a);
doActionOnBehalfOf(
_hash,
_sig,
DaoBase(daoBase).REMOVE_GROUP_MEMBER(),
"removeGroupMemberGeneric(bytes32[])",
params
);
}
/**
* @param _hash hash of the message which account sign
* @param _sig signature of the account which have rights for action needed
* @param _what permission name in hash
* @param _tokenAddress address of the token
* @dev this function allow any account allow action by shareholder on behalf by account which have needed rights by signing specified message
*/
function allowActionByShareholderImp(bytes32 _hash, bytes _sig, bytes32 _what, address _tokenAddress) public {
bytes32[] memory params = new bytes32[](2);
params[0] = _what;
params[1] = bytes32(_tokenAddress);
doActionOnBehalfOf(
_hash,
_sig,
DaoBase(daoBase).ALLOW_ACTION_BY_SHAREHOLDER(),
"allowActionByShareholderGeneric(bytes32[])",
params
);
}
/**
* @param _hash hash of the message which account sign
* @param _sig signature of the account which have rights for action needed
* @param _what permission name in hash
* @param _tokenAddress address of the token
* @dev this function allow any account allow action by voting on behalf by account which have needed rights by signing specified message
*/
function allowActionByVotingImp(bytes32 _hash, bytes _sig, bytes32 _what, address _tokenAddress) public {
bytes32[] memory params = new bytes32[](2);
params[0] = _what;
params[1] = bytes32(_tokenAddress);
doActionOnBehalfOf(
_hash,
_sig,
DaoBase(daoBase).ALLOW_ACTION_BY_VOTING(),
"allowActionByVotingGeneric(bytes32[])",
params
);
}
/**
* @param _hash hash of the message which account sign
* @param _sig signature of the account which have rights for action needed
* @param _what permission name in hash
* @param _a address
* @dev this function allow any account allow action by address on behalf by account which have needed rights by signing specified message
*/
function allowActionByAddressImp(bytes32 _hash, bytes _sig, bytes32 _what, address _a) public {
bytes32[] memory params = new bytes32[](2);
params[0] = _what;
params[1] = bytes32(_a);
doActionOnBehalfOf(
_hash,
_sig,
DaoBase(daoBase).ALLOW_ACTION_BY_ADDRESS(),
"allowActionByAddressGeneric(bytes32[])",
params
);
}
/**
* @param _hash hash of the message which account sign
* @param _sig signature of the account which have rights for action needed
* @param _what permission name in hash
* @param _groupName name of the group in storage
* @dev this function allow any account allow action by any member of group on behalf by account which have needed rights by signing specified message
*/
function allowActionByAnyMemberOfGroupImp(bytes32 _hash, bytes _sig, bytes32 _what, string _groupName) public {
bytes32[] memory params = new bytes32[](2);
params[0] = _what;
params[1] = UtilsLib.stringToBytes32(_groupName);
doActionOnBehalfOf(
_hash,
_sig,
DaoBase(daoBase).ALLOW_ACTION_BY_ANY_MEMBER_OF_GROUP(),
"allowActionByAnyMemberOfGroupGeneric(bytes32[])",
params
);
}
}
|
_hash hash of the message which account sign _sig signature of the account which have rights for action needed _newMc new DaoBase instance (address) this function allow any account upgrade DAO contract on behalf by account which have needed rights by signing specified message/
|
function upgradeDaoContractImp(bytes32 _hash, bytes _sig, address _newMc) public {
bytes32[] memory params = new bytes32[](1);
params[0] = bytes32(_newMc);
doActionOnBehalfOf(
_hash,
_sig,
DaoBase(daoBase).UPGRADE_DAO_CONTRACT(),
"upgradeDaoContractGeneric(bytes32[])",
params
);
}
| 12,672,342 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.6;
import "./lib/@defiat-crypto/interfaces/IDeFiatPoints.sol";
import "./interfaces/IAnyStake.sol";
import "./interfaces/IAnyStakeMigrator.sol";
import "./interfaces/IAnyStakeVault.sol";
import "./utils/AnyStakeUtils.sol";
contract AnyStake is IAnyStake, AnyStakeUtils {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// EVENTS
event Initialized(address indexed user, address vault);
event Claim(address indexed user, uint256 indexed pid, uint256 amount);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Migrate(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event PoolAdded(address indexed user, uint256 indexed pid, address indexed stakedToken, address lpToken, uint256 allocPoints);
event MigratorUpdated(address indexed user, address migrator);
event VaultUpdated(address indexed user, address vault);
event PoolAllocPointsUpdated(address indexed user, uint256 indexed pid, uint256 allocPoints);
event PoolVipAmountUpdated(address indexed user, uint256 indexed pid, uint256 vipAmount);
event PoolStakingFeeUpdated(address indexed user, uint256 indexed pid, uint256 stakingFee);
event PointStipendUpdated(address indexed user, uint256 stipend);
// STRUCTS
// UserInfo - User metrics, pending reward = (user.amount * pool.DFTPerShare) - user.rewardDebt
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Token rewards paid out to user
uint256 lastRewardBlock; // last pool interaction
}
// PoolInfo - Pool metrics
struct PoolInfo {
address stakedToken; // Address of staked token contract.
address lpToken; // uniswap LP token corresponding to the trading pair needed for price calculation
uint256 totalStaked; // total tokens staked
uint256 allocPoint; // How many allocation points assigned to this pool. DFTs to distribute per block. (ETH = 2.3M blocks per year)
uint256 rewardsPerShare; // Accumulated DFTs per share, times 1e18. See below.
uint256 lastRewardBlock; // last pool update
uint256 vipAmount; // amount of DFT tokens that must be staked to access the pool
uint256 stakingFee; // the % withdrawal fee charged. base 1000, 50 = 5%
}
address public migrator; // contract where we may migrate too
address public vault; // where rewards are stored for distribution
bool public initialized;
PoolInfo[] public poolInfo; // array of AnyStake pools
mapping(uint256 => mapping(address => UserInfo)) public userInfo; // mapping of (pid => (userAddress => userInfo))
mapping(address => uint256) public pids; // quick mapping for pool ids (staked_token => pid)
uint256 public lastRewardBlock; // last block the pool was updated
uint256 public pendingRewards; // pending DFT rewards awaiting anyone to be distro'd to pools
uint256 public pointStipend; // amount of DFTP awarded per deposit
uint256 public totalAllocPoint; // Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalBlockDelta; // Total blocks since last update
uint256 public totalEligiblePools; // Amount of pools eligible for rewards
modifier NoReentrant(uint256 pid, address user) {
require(
block.number > userInfo[pid][user].lastRewardBlock,
"AnyStake: Must wait 1 block"
);
_;
}
modifier onlyVault() {
require(msg.sender == vault, "AnyStake: Only Vault allowed");
_;
}
modifier activated() {
require(initialized, "AnyStake: Not initialized yet");
_;
}
constructor(address _router, address _gov, address _points, address _token)
public
AnyStakeUtils(_router, _gov, _points, _token)
{
pointStipend = 1e18;
}
// Initialize pools/rewards after the Vault has been setup
function initialize(address _vault) public onlyGovernor {
require(_vault != address(0), "Initalize: Must pass in Vault");
require(!initialized, "Initialize: AnyStake already initialized");
vault = _vault;
initialized = true;
emit Initialized(msg.sender, _vault);
}
// Pool - Get any incoming rewards, called during Vault.distributeRewards()
function addReward(uint256 amount) external override onlyVault {
if (amount == 0) {
return;
}
pendingRewards = pendingRewards.add(amount);
}
// Pool - Updates the reward variables of the given pool
function updatePool(uint256 pid) external {
_updatePool(pid);
}
// Pool - Update internal
function _updatePool(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
if (pool.totalStaked == 0 || pool.lastRewardBlock >= block.number || pool.allocPoint == 0) {
return;
}
// calculate total reward blocks since last update call
if (lastRewardBlock < block.number) {
totalBlockDelta = totalBlockDelta.add(block.number.sub(lastRewardBlock).mul(totalEligiblePools));
lastRewardBlock = block.number;
}
// calculate rewards, returns if already done this block
IAnyStakeVault(vault).calculateRewards();
// Calculate pool's share of pending rewards, using blocks since last reward and alloc points
uint256 poolBlockDelta = block.number.sub(pool.lastRewardBlock);
uint256 poolRewards = pendingRewards
.mul(poolBlockDelta)
.div(totalBlockDelta)
.mul(pool.allocPoint)
.div(totalAllocPoint);
// update reward variables
totalBlockDelta = poolBlockDelta > totalBlockDelta ? 0 : totalBlockDelta.sub(poolBlockDelta);
pendingRewards = poolRewards > pendingRewards ? 0 : pendingRewards.sub(poolRewards);
// update pool variables
pool.rewardsPerShare = pool.rewardsPerShare.add(poolRewards.mul(1e18).div(pool.totalStaked));
pool.lastRewardBlock = block.number;
}
// Pool - Claim rewards
function claim(uint256 pid) external override NoReentrant(pid, msg.sender) {
_updatePool(pid);
_claim(pid, msg.sender);
}
// Pool - Claim internal, called during deposit() and withdraw()
function _claim(uint256 _pid, address _user) internal {
UserInfo storage user = userInfo[_pid][_user];
uint256 rewards = pending(_pid, _user);
if (rewards == 0) {
return;
}
// update pool / user metrics
user.rewardDebt = user.amount.mul(poolInfo[_pid].rewardsPerShare).div(1e18);
user.lastRewardBlock = block.number;
// transfer DFT rewards
IAnyStakeVault(vault).distributeRewards(_user, rewards);
emit Claim(_user, _pid, rewards);
}
// Pool - Deposit Tokens
function deposit(uint256 pid, uint256 amount) external override NoReentrant(pid, msg.sender) {
_deposit(msg.sender, pid, amount);
}
// Pool - Deposit internal
function _deposit(address _user, uint256 _pid, uint256 _amount) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
require(_amount > 0, "Deposit: Cannot deposit zero tokens");
require(pool.allocPoint > 0, "Deposit: Pool is not active");
require(pool.vipAmount <= userInfo[0][_user].amount, "Deposit: VIP Only");
// add pool to reward calculation if previously no tokens staked
if (pool.totalStaked == 0) {
totalEligiblePools = totalEligiblePools.add(1);
pool.lastRewardBlock = block.number; // reset reward block
// begin computing rewards from this block if the first
if (lastRewardBlock == 0) {
lastRewardBlock = block.number;
}
}
// Update and claim rewards
_updatePool(_pid);
_claim(_pid, _user);
// Get tokens from user, balance check to support Fee-On-Transfer tokens
uint256 amount = IERC20(pool.stakedToken).balanceOf(address(this));
IERC20(pool.stakedToken).safeTransferFrom(_user, address(this), _amount);
amount = IERC20(pool.stakedToken).balanceOf(address(this)).sub(amount);
// Finalize, update user metrics
pool.totalStaked = pool.totalStaked.add(amount);
user.amount = user.amount.add(amount);
user.rewardDebt = user.amount.mul(pool.rewardsPerShare).div(1e18);
// reward user
IDeFiatPoints(DeFiatPoints).addPoints(_user, IDeFiatPoints(DeFiatPoints).viewTxThreshold(), pointStipend);
// Transfer the total amounts from user and update pool user.amount into the AnyStake contract
emit Deposit(_user, _pid, amount);
}
// Pool - Withdraw staked tokens
function withdraw(uint256 pid, uint256 amount) external override NoReentrant(pid, msg.sender) {
_withdraw(msg.sender, pid, amount);
}
// Pool - Withdraw Internal
function _withdraw(
address _user,
uint256 _pid,
uint256 _amount
) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
require(_amount > 0, "Withdraw: amount must be greater than zero");
require(user.amount >= _amount, "Withdraw: user amount insufficient");
require(pool.vipAmount <= userInfo[0][_user].amount, "Withdraw: VIP Only");
// claim rewards
_updatePool(_pid);
_claim(_pid, _user);
// update pool / user metrics
pool.totalStaked = pool.totalStaked.sub(_amount);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.rewardsPerShare).div(1e18);
// reduce eligible pools only if done by user actions
if (pool.totalStaked == 0 && pool.allocPoint > 0) {
totalEligiblePools = totalEligiblePools.sub(1);
}
// PID = 0 : DFT-LP
// PID = 1 : DFTP-LP
// PID = 2 : weth (price = 1e18)
// PID > 2 : all other tokens
// No fee on DFT-ETH, DFTP-ETH pools
uint256 stakingFeeAmount = _amount.mul(pool.stakingFee).div(1000);
uint256 remainingUserAmount = _amount.sub(stakingFeeAmount);
if(stakingFeeAmount > 0){
// Send Fee to Vault and buy DFT, balance check to support Fee-On-Transfer tokens
uint256 balance = IERC20(pool.stakedToken).balanceOf(vault);
safeTokenTransfer(vault, pool.stakedToken, stakingFeeAmount);
balance = IERC20(pool.stakedToken).balanceOf(vault);
IAnyStakeVault(vault).buyDeFiatWithTokens(pool.stakedToken, balance);
}
// withdraw user tokens
safeTokenTransfer(_user, pool.stakedToken, remainingUserAmount);
emit Withdraw(_user, _pid, remainingUserAmount);
}
// Pool - migrate stake to a new contract, should only be called after
function migrate(uint256 pid) external NoReentrant(pid, msg.sender) {
_migrate(msg.sender, pid);
}
// Pool - migrate internal
function _migrate(address _user, uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 balance = user.amount;
require(migrator != address(0), "Migrate: No migrator set");
require(balance > 0, "Migrate: No tokens to migrate");
require(pool.allocPoint == 0, "Migrate: Pool is still active");
_claim(_pid, _user);
IERC20(pool.stakedToken).safeApprove(migrator, balance);
IAnyStakeMigrator(migrator).migrateTo(_user, pool.stakedToken, balance);
emit Migrate(_user, _pid, balance);
}
// Pool - withdraw all stake and forfeit rewards, skips pool update
function emergencyWithdraw(uint256 pid) external NoReentrant(pid, msg.sender) {
PoolInfo storage pool = poolInfo[pid];
UserInfo storage user = userInfo[pid][msg.sender];
require(user.amount > 0, "EmergencyWithdraw: user amount insufficient");
uint256 stakingFeeAmount = user.amount.mul(pool.stakingFee).div(1000);
uint256 remainingUserAmount = user.amount.sub(stakingFeeAmount);
pool.totalStaked = pool.totalStaked.sub(user.amount);
user.amount = 0;
user.rewardDebt = 0;
user.lastRewardBlock = block.number;
if (pool.totalStaked == 0) {
totalEligiblePools = totalEligiblePools.sub(1);
}
safeTokenTransfer(vault, pool.stakedToken, stakingFeeAmount);
safeTokenTransfer(msg.sender, pool.stakedToken, remainingUserAmount);
emit EmergencyWithdraw(msg.sender, pid, remainingUserAmount);
}
// View - gets stakedToken price from the Vault
function getPrice(uint256 pid) external view returns (uint256) {
address token = poolInfo[pid].stakedToken;
address lpToken = poolInfo[pid].lpToken;
return IAnyStakeVault(vault).getTokenPrice(token, lpToken);
}
// View - Pending DFT Rewards for user in pool
function pending(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
// not sure if this will work with tokens non-1e18 decimals
return user.amount.mul(pool.rewardsPerShare).div(1e18).sub(user.rewardDebt);
}
// View - View Pool Length
function poolLength() external view returns (uint256) {
return poolInfo.length; // number of pools (pids)
}
// Governance - Add Multiple Token Pools
function addPoolBatch(
address[] calldata tokens,
address[] calldata lpTokens,
uint256[] calldata allocPoints,
uint256[] calldata vipAmounts,
uint256[] calldata stakingFees
) external onlyGovernor {
for (uint i = 0; i < tokens.length; i++) {
_addPool(tokens[i], lpTokens[i], allocPoints[i], vipAmounts[i], stakingFees[i]);
}
}
// Governance - Add Single Token Pool
function addPool(
address token,
address lpToken,
uint256 allocPoint,
uint256 vipAmount,
uint256 stakingFee
) external onlyGovernor {
_addPool(token, lpToken, allocPoint, vipAmount, stakingFee);
}
// Governance - Add Token Pool Internal
function _addPool(
address stakedToken,
address lpToken,
uint256 allocPoint,
uint256 vipAmount,
uint256 stakingFee
) internal {
require(pids[stakedToken] == 0, "AddPool: Token pool already added");
pids[stakedToken] = poolInfo.length;
_blacklistedAdminWithdraw[stakedToken] = true; // stakedToken now non-withrawable by admins
totalAllocPoint = totalAllocPoint.add(allocPoint);
// Add new pool
poolInfo.push(
PoolInfo({
stakedToken: stakedToken,
lpToken: lpToken,
allocPoint: allocPoint,
lastRewardBlock: block.number,
totalStaked: 0,
rewardsPerShare: 0,
vipAmount: vipAmount,
stakingFee: stakingFee
})
);
emit PoolAdded(msg.sender, pids[stakedToken], stakedToken, lpToken, allocPoint);
}
// Governance - Set Migrator
function setMigrator(address _migrator) external onlyGovernor {
require(_migrator != address(0), "SetMigrator: No migrator change");
migrator = _migrator;
emit MigratorUpdated(msg.sender, _migrator);
}
// Governance - Set Vault
function setVault(address _vault) external onlyGovernor {
require(_vault != address(0), "SetVault: No migrator change");
vault = _vault;
emit VaultUpdated(msg.sender, vault);
}
// Governance - Set Pool Allocation Points
function setPoolAllocPoints(uint256 _pid, uint256 _allocPoint) external onlyGovernor {
require(poolInfo[_pid].allocPoint != _allocPoint, "SetAllocPoints: No points change");
if (_allocPoint == 0) {
totalEligiblePools = totalEligiblePools.sub(1);
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
emit PoolAllocPointsUpdated(msg.sender, _pid, _allocPoint);
}
// Governance - Set Pool Charge Fee
function setPoolVipAmount(uint256 _pid, uint256 _vipAmount) external onlyGovernor {
require(poolInfo[_pid].vipAmount != _vipAmount, "SetVipAmount: No amount change");
poolInfo[_pid].vipAmount = _vipAmount;
emit PoolVipAmountUpdated(msg.sender, _pid, _vipAmount);
}
// Governance - Set Pool Charge Fee
function setPoolChargeFee(uint256 _pid, uint256 _stakingFee) external onlyGovernor {
require(poolInfo[_pid].stakingFee != _stakingFee, "SetStakingFee: No fee change");
poolInfo[_pid].stakingFee = _stakingFee;
emit PoolStakingFeeUpdated(msg.sender, _pid, _stakingFee);
}
// Governance - Set Pool Allocation Points
function setPointStipend(uint256 _pointStipend) external onlyGovernor {
require(_pointStipend != pointStipend, "SetStipend: No stipend change");
pointStipend = _pointStipend;
emit PointStipendUpdated(msg.sender, pointStipend);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.6;
interface IAnyStake {
function addReward(uint256 amount) external;
function claim(uint256 pid) external;
function deposit(uint256 pid, uint256 amount) external;
function withdraw(uint256 pid, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.6;
interface IAnyStakeMigrator {
function migrateTo(address user, address token, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.6;
interface IAnyStakeVault {
function buyDeFiatWithTokens(address token, uint256 amount) external;
function buyPointsWithTokens(address token, uint256 amount) external;
function calculateRewards() external;
function distributeRewards(address recipient, uint256 amount) external;
function getTokenPrice(address token, address lpToken) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.6;
interface IDeFiatGov {
function mastermind() external view returns (address);
function viewActorLevelOf(address _address) external view returns (uint256);
function viewFeeDestination() external view returns (address);
function viewTxThreshold() external view returns (uint256);
function viewBurnRate() external view returns (uint256);
function viewFeeRate() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.6;
interface IDeFiatPoints {
function viewDiscountOf(address _address) external view returns (uint256);
function viewEligibilityOf(address _address) external view returns (uint256 tranche);
function discountPointsNeeded(uint256 _tranche) external view returns (uint256 pointsNeeded);
function viewTxThreshold() external view returns (uint256);
function viewRedirection(address _address) external view returns (bool);
function overrideLoyaltyPoints(address _address, uint256 _points) external;
function addPoints(address _address, uint256 _txSize, uint256 _points) external;
function burn(uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.6;
import "./DeFiatUtils.sol";
import "../interfaces/IDeFiatGov.sol";
abstract contract DeFiatGovernedUtils is DeFiatUtils {
event GovernanceUpdated(address indexed user, address governance);
address public governance;
modifier onlyMastermind {
require(
msg.sender == IDeFiatGov(governance).mastermind() || msg.sender == owner(),
"Gov: Only Mastermind"
);
_;
}
modifier onlyGovernor {
require(
IDeFiatGov(governance).viewActorLevelOf(msg.sender) >= 2 || msg.sender == owner(),
"Gov: Only Governors"
);
_;
}
modifier onlyPartner {
require(
IDeFiatGov(governance).viewActorLevelOf(msg.sender) >= 1 || msg.sender == owner(),
"Gov: Only Partners"
);
_;
}
function _setGovernance(address _governance) internal {
require(_governance != governance, "SetGovernance: No governance change");
governance = _governance;
emit GovernanceUpdated(msg.sender, governance);
}
function setGovernance(address _governance) external onlyGovernor {
_setGovernance(_governance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.6;
import "../../@openzeppelin/token/ERC20/IERC20.sol";
import "../../@openzeppelin/access/Ownable.sol";
abstract contract DeFiatUtils is Ownable {
event TokenSweep(address indexed user, address indexed token, uint256 amount);
// Sweep any tokens/ETH accidentally sent or airdropped to the contract
function sweep(address token) public virtual onlyOwner {
uint256 amount = IERC20(token).balanceOf(address(this));
require(amount > 0, "Sweep: No token balance");
IERC20(token).transfer(msg.sender, amount); // use of the ERC20 traditional transfer
if (address(this).balance > 0) {
payable(msg.sender).transfer(address(this).balance);
}
emit TokenSweep(msg.sender, token, amount);
}
// Self-Destruct contract to free space on-chain, sweep any ETH to owner
function kill() external onlyOwner {
selfdestruct(payable(msg.sender));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
interface IERC20 {
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
// Standard
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.6;
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.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// SPDX-License-Identifier: MIT
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);
}
// SPDX-License-Identifier: MIT
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.6.6;
import "../lib/@defiat-crypto/utils/DeFiatUtils.sol";
import "../lib/@defiat-crypto/utils/DeFiatGovernedUtils.sol";
import "../lib/@openzeppelin/token/ERC20/SafeERC20.sol";
import "../lib/@uniswap/interfaces/IUniswapV2Factory.sol";
import "../lib/@uniswap/interfaces/IUniswapV2Router02.sol";
abstract contract AnyStakeUtils is DeFiatGovernedUtils {
using SafeERC20 for IERC20;
event PointsUpdated(address indexed user, address points);
event TokenUpdated(address indexed user, address token);
event UniswapUpdated(address indexed user, address router, address weth, address factory);
address public router;
address public factory;
address public weth;
address public DeFiatToken;
address public DeFiatPoints;
address public DeFiatTokenLp;
address public DeFiatPointsLp;
mapping (address => bool) internal _blacklistedAdminWithdraw;
constructor(address _router, address _gov, address _points, address _token) public {
_setGovernance(_gov);
router = _router;
DeFiatPoints = _points;
DeFiatToken = _token;
weth = IUniswapV2Router02(router).WETH();
factory = IUniswapV2Router02(router).factory();
DeFiatTokenLp = IUniswapV2Factory(factory).getPair(_token, weth);
DeFiatPointsLp = IUniswapV2Factory(factory).getPair(_points, weth);
}
function sweep(address _token) public override onlyOwner {
require(!_blacklistedAdminWithdraw[_token], "Sweep: Cannot withdraw blacklisted token");
DeFiatUtils.sweep(_token);
}
function isBlacklistedAdminWithdraw(address _token)
external
view
returns (bool)
{
return _blacklistedAdminWithdraw[_token];
}
// Method to avoid underflow on token transfers
function safeTokenTransfer(address user, address token, uint256 amount) internal {
if (amount == 0) {
return;
}
uint256 tokenBalance = IERC20(token).balanceOf(address(this));
if (amount > tokenBalance) {
IERC20(token).safeTransfer(user, tokenBalance);
} else {
IERC20(token).safeTransfer(user, amount);
}
}
function setToken(address _token) external onlyGovernor {
require(_token != DeFiatToken, "SetToken: No token change");
require(_token != address(0), "SetToken: Must set token value");
DeFiatToken = _token;
DeFiatTokenLp = IUniswapV2Factory(factory).getPair(_token, weth);
emit TokenUpdated(msg.sender, DeFiatToken);
}
function setPoints(address _points) external onlyGovernor {
require(_points != DeFiatPoints, "SetPoints: No points change");
require(_points != address(0), "SetPoints: Must set points value");
DeFiatPoints = _points;
DeFiatPointsLp = IUniswapV2Factory(factory).getPair(_points, weth);
emit PointsUpdated(msg.sender, DeFiatPoints);
}
function setUniswap(address _router) external onlyGovernor {
require(_router != router, "SetUniswap: No uniswap change");
require(_router != address(0), "SetUniswap: Must set uniswap value");
router = _router;
weth = IUniswapV2Router02(router).WETH();
factory = IUniswapV2Router02(router).factory();
emit UniswapUpdated(msg.sender, router, weth, factory);
}
}
|
Governance - Set Pool Charge Fee
|
function setPoolVipAmount(uint256 _pid, uint256 _vipAmount) external onlyGovernor {
require(poolInfo[_pid].vipAmount != _vipAmount, "SetVipAmount: No amount change");
poolInfo[_pid].vipAmount = _vipAmount;
emit PoolVipAmountUpdated(msg.sender, _pid, _vipAmount);
}
| 13,947,632 |
/*
* This file was generated by MyWish Platform (https://mywish.io/)
* The complete code could be found at https://github.com/MyWishPlatform/
* Copyright (C) 2018 MyWish
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.21;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
}
contract FreezableToken is StandardToken {
// freezing chains
mapping (bytes32 => uint64) internal chains;
// freezing amounts for each chain
mapping (bytes32 => uint) internal freezings;
// total freezing balance per address
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
/**
* @dev Gets the balance of the specified address include freezing tokens.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
/**
* @dev Gets the balance of the specified address without freezing tokens.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
/**
* @dev gets freezing count
* @param _addr Address of freeze tokens owner.
*/
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count ++;
release = chains[toKey(_addr, release)];
}
}
/**
* @dev gets freezing end date and freezing balance for the freezing portion specified by index.
* @param _addr Address of freeze tokens owner.
* @param _index Freezing portion index. It ordered by release date descending.
*/
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i ++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
/**
* @dev freeze your tokens to the specified address.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to freeze.
* @param _until Release date, must be in future.
*/
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
/**
* @dev release first available freezing tokens.
*/
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
}
else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
/**
* @dev release all available for release freezing tokens. Gas usage is not deterministic!
* @return how many tokens was released
*/
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
// WISH masc to increase entropy
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
/**
* @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();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
/**
* @dev Mint the specified amount of token to the specified address and freeze it until the specified date.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to mint and freeze.
* @param _until Release date, must be in future.
* @return A boolean that indicates if the operation was successful.
*/
function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint constant TOKEN_DECIMALS = 18;
uint8 constant TOKEN_DECIMALS_UINT8 = 18;
uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string constant TOKEN_NAME = "MAKEAFOLIO";
string constant TOKEN_SYMBOL = "MAF";
bool constant PAUSED = true;
address constant TARGET_USER = 0x8De57367b1Bb53afc74f5efAbAebC3A971FA69A9;
uint constant START_TIME = 1530417600;
bool constant CONTINUE_MINTING = false;
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
function name() pure public returns (string _name) {
return TOKEN_NAME;
}
function symbol() pure public returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() pure public returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
}
/**
* @title CappedCrowdsale
* @dev Extension of Crowdsale with a max amount of funds raised
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
function CappedCrowdsale(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
// overriding Crowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
function validPurchase() internal view returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= cap;
return super.validPurchase() && withinCap;
}
// overriding Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
bool capReached = weiRaised >= cap;
return super.hasEnded() || capReached;
}
}
contract MainCrowdsale is Consts, FinalizableCrowdsale {
function hasStarted() public constant returns (bool) {
return now >= startTime;
}
function finalization() internal {
super.finalization();
if (PAUSED) {
MainToken(token).unpause();
}
if (!CONTINUE_MINTING) {
token.finishMinting();
}
token.transferOwnership(TARGET_USER);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate).div(1 ether);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
}
contract BonusableCrowdsale is Consts, Crowdsale {
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 bonusRate = getBonusRate(weiAmount);
uint256 tokens = weiAmount.mul(bonusRate).div(1 ether);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function getBonusRate(uint256 weiAmount) internal view returns (uint256) {
uint256 bonusRate = rate;
// apply bonus for time & weiRaised
uint[5] memory weiRaisedStartsBoundaries = [uint(0),uint(4583333333333333333333),uint(8333333333333333333333),uint(16666666666666666666667),uint(25000000000000000000000)];
uint[5] memory weiRaisedEndsBoundaries = [uint(4583333333333333333333),uint(8333333333333333333333),uint(16666666666666666666667),uint(25000000000000000000000),uint(33333333333333333333333)];
uint64[5] memory timeStartsBoundaries = [uint64(1530417600),uint64(1530417600),uint64(1530417600),uint64(1530417600),uint64(1530417600)];
uint64[5] memory timeEndsBoundaries = [uint64(1543640395),uint64(1543640395),uint64(1543640395),uint64(1543640395),uint64(1543640395)];
uint[5] memory weiRaisedAndTimeRates = [uint(300),uint(200),uint(150),uint(100),uint(50)];
for (uint i = 0; i < 5; i++) {
bool weiRaisedInBound = (weiRaisedStartsBoundaries[i] <= weiRaised) && (weiRaised < weiRaisedEndsBoundaries[i]);
bool timeInBound = (timeStartsBoundaries[i] <= now) && (now < timeEndsBoundaries[i]);
if (weiRaisedInBound && timeInBound) {
bonusRate += bonusRate * weiRaisedAndTimeRates[i] / 1000;
}
}
return bonusRate;
}
}
contract WhitelistedCrowdsale is Crowdsale, Ownable {
mapping (address => bool) private whitelist;
event WhitelistedAddressAdded(address indexed _address);
event WhitelistedAddressRemoved(address indexed _address);
/**
* @dev throws if buyer is not whitelisted.
* @param _buyer address
*/
modifier onlyIfWhitelisted(address _buyer) {
require(whitelist[_buyer]);
_;
}
/**
* @dev getter to determine if address is in whitelist
*/
function isWhitelisted(address _address) public view returns (bool) {
return whitelist[_address];
}
/**
* @dev override purchase validation to add extra value logic.
* @return true if sender is whitelisted
*/
function validPurchase() internal view onlyIfWhitelisted(msg.sender) returns (bool) {
return super.validPurchase();
}
/**
* @dev add single address to whitelist
*/
function addAddressToWhitelist(address _address) external onlyOwner {
whitelist[_address] = true;
emit WhitelistedAddressAdded(_address);
}
/**
* @dev add addresses to whitelist
*/
function addAddressesToWhitelist(address[] _addresses) external onlyOwner {
for (uint i = 0; i < _addresses.length; i++) {
whitelist[_addresses[i]] = true;
emit WhitelistedAddressAdded(_addresses[i]);
}
}
/**
* @dev remove single address from whitelist
*/
function removeAddressFromWhitelist(address _address) external onlyOwner {
delete whitelist[_address];
emit WhitelistedAddressRemoved(_address);
}
/**
* @dev remove addresses from whitelist
*/
function removeAddressesFromWhitelist(address[] _addresses) external onlyOwner {
for (uint i = 0; i < _addresses.length; i++) {
delete whitelist[_addresses[i]];
emit WhitelistedAddressRemoved(_addresses[i]);
}
}
}
contract TemplateCrowdsale is Consts, MainCrowdsale
, BonusableCrowdsale
, CappedCrowdsale
, WhitelistedCrowdsale
{
event Initialized();
event TimesChanged(uint startTime, uint endTime, uint oldStartTime, uint oldEndTime);
bool public initialized = false;
function TemplateCrowdsale(MintableToken _token) public
Crowdsale(START_TIME > now ? START_TIME : now, 1543640400, 1200 * TOKEN_DECIMAL_MULTIPLIER, 0x8BcC12F71e4C0C5f73C0dF9afbB3ed1de66DdD79)
CappedCrowdsale(50000000000000000000000)
{
token = _token;
}
function init() public onlyOwner {
require(!initialized);
initialized = true;
if (PAUSED) {
MainToken(token).pause();
}
address[3] memory addresses = [address(0xbbc01d55a41a9eadd12027fe8088ed84768c3f0d),address(0x6cfd2db944e2b28a61a4f3f2cfb1973f0758cc3b),address(0x221be49cd399b8aaf0ade2485d6535e10518700d)];
uint[3] memory amounts = [uint(12500000000000000000000000),uint(7500000000000000000000000),uint(20000000000000000000000000)];
uint64[3] memory freezes = [uint64(0),uint64(0),uint64(1561953604)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
MainToken(token).mint(addresses[i], amounts[i]);
} else {
MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
transferOwnership(TARGET_USER);
emit Initialized();
}
/**
* @dev override token creation to set token address in constructor.
*/
function createTokenContract() internal returns (MintableToken) {
return MintableToken(0);
}
/**
* @dev override purchase validation to add extra value logic.
* @return true if sended more than minimal value
*/
function validPurchase() internal view returns (bool) {
bool minValue = msg.value >= 100000000000000000;
bool maxValue = msg.value <= 1000000000000000000000;
return
minValue &&
maxValue &&
super.validPurchase();
}
/**
* @dev override hasEnded to add minimal value logic
* @return true if remained to achieve less than minimal
*/
function hasEnded() public view returns (bool) {
bool remainValue = cap.sub(weiRaised) < 100000000000000000;
return super.hasEnded() || remainValue;
}
function setEndTime(uint _endTime) public onlyOwner {
// only if CS was not ended
require(now < endTime);
// only if new end time in future
require(now < _endTime);
require(_endTime > startTime);
emit TimesChanged(startTime, _endTime, startTime, endTime);
endTime = _endTime;
}
}
|
override hasEnded to add minimal value logic return true if remained to achieve less than minimal/
|
function hasEnded() public view returns (bool) {
bool remainValue = cap.sub(weiRaised) < 100000000000000000;
return super.hasEnded() || remainValue;
}
| 1,681,173 |
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.12;
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./MToken.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/ExponentialNoError.sol";
import "./Utils/AssetHelpers.sol";
import "./Moartroller.sol";
import "./SimplePriceOracle.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract LiquidityMathModelV1 is LiquidityMathModelInterface, LiquidityMathModelErrorReporter, ExponentialNoError, Ownable, AssetHelpers {
/**
* @notice get the maximum asset value that can be still optimized.
* @notice if protectionId is supplied, the maxOptimizableValue is increased by the protection lock value'
* which is helpful to recalculate how much of this protection can be optimized again
*/
function getMaxOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) external override view returns (uint){
uint returnValue;
uint hypotheticalOptimizableValue = getHypotheticalOptimizableValue(arguments);
uint totalProtectionLockedValue;
(totalProtectionLockedValue, ) = getTotalProtectionLockedValue(arguments);
if(hypotheticalOptimizableValue <= totalProtectionLockedValue){
returnValue = 0;
}
else{
returnValue = sub_(hypotheticalOptimizableValue, totalProtectionLockedValue);
}
return returnValue;
}
/**
* @notice get the maximum value of an asset that can be optimized by protection for the given user
* @dev optimizable = asset value * MPC
* @return the hypothetical optimizable value
* TODO: replace hardcoded 1e18 values
*/
function getHypotheticalOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint) {
uint assetValue = div_(
mul_(
div_(
mul_(
arguments.asset.balanceOf(arguments.account),
arguments.asset.exchangeRateStored()
),
1e18
),
arguments.oracle.getUnderlyingPrice(arguments.asset)
),
getAssetDecimalsMantissa(arguments.asset.getUnderlying())
);
uint256 hypotheticalOptimizableValue = div_(
mul_(
assetValue,
arguments.asset.maxProtectionComposition()
),
arguments.asset.maxProtectionCompositionMantissa()
);
return hypotheticalOptimizableValue;
}
/**
* @dev gets all locked protections values with mark to market value. Used by Moartroller.
*/
function getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint, uint) {
uint _lockedValue = 0;
uint _markToMarket = 0;
uint _protectionCount = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(arguments.account, arguments.asset.underlying());
for (uint j = 0; j < _protectionCount; j++) {
uint protectionId = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrency(arguments.account, arguments.asset.underlying(), j);
bool protectionIsAlive = arguments.cprotection.isProtectionAlive(protectionId);
if(protectionIsAlive){
_lockedValue = add_(_lockedValue, arguments.cprotection.getUnderlyingProtectionLockedValue(protectionId));
uint assetSpotPrice = arguments.oracle.getUnderlyingPrice(arguments.asset);
uint protectionStrikePrice = arguments.cprotection.getUnderlyingStrikePrice(protectionId);
if( assetSpotPrice > protectionStrikePrice) {
_markToMarket = _markToMarket + div_(
mul_(
div_(
mul_(
assetSpotPrice - protectionStrikePrice,
arguments.cprotection.getUnderlyingProtectionLockedAmount(protectionId)
),
getAssetDecimalsMantissa(arguments.asset.underlying())
),
arguments.collateralFactorMantissa
),
1e18
);
}
}
}
return (_lockedValue , _markToMarket);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.12;
import "../MToken.sol";
import "../MProtection.sol";
import "../Interfaces/PriceOracle.sol";
interface LiquidityMathModelInterface {
struct LiquidityMathArgumentsSet {
MToken asset;
address account;
uint collateralFactorMantissa;
MProtection cprotection;
PriceOracle oracle;
}
function getMaxOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns (uint);
function getHypotheticalOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint);
function getTotalProtectionLockedValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint, uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Utils/ErrorReporter.sol";
import "./Utils/Exponential.sol";
import "./Interfaces/EIP20Interface.sol";
import "./MTokenStorage.sol";
import "./Interfaces/MTokenInterface.sol";
import "./Interfaces/MProxyInterface.sol";
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
/**
* @title MOAR's MToken Contract
* @notice Abstract base for MTokens
* @author MOAR
*/
abstract contract MToken is MTokenInterface, Exponential, TokenErrorReporter, MTokenStorage {
/**
* @notice Indicator that this is a MToken contract (for inspection)
*/
bool public constant isMToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address MTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when moartroller is changed
*/
event NewMoartroller(Moartroller oldMoartroller, Moartroller newMoartroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModelInterface oldInterestRateModel, InterestRateModelInterface newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/**
* @notice Max protection composition value updated event
*/
event MpcUpdated(uint newValue);
/**
* @notice Initialize the money market
* @param moartroller_ The address of the Moartroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function init(Moartroller moartroller_,
AbstractInterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "not_admin");
require(accrualBlockNumber == 0 && borrowIndex == 0, "already_init");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "too_low");
// Set the moartroller
uint err = _setMoartroller(moartroller_);
require(err == uint(Error.NO_ERROR), "setting moartroller failed");
// Initialize block number and borrow index (block number mocks depend on moartroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting IRM failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
maxProtectionComposition = 5000;
maxProtectionCompositionMantissa = 1e4;
reserveFactorMaxMantissa = 1e18;
borrowRateMaxMantissa = 0.0005e16;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = moartroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.TRANSFER_MOARTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srmTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srmTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srmTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// moartroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @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
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external virtual override nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @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
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external virtual override nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @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 (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external virtual override returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @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 The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external virtual override view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external virtual override view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external virtual override returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance_calculation_failed");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by moartroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external virtual override view returns (uint, uint, uint, uint) {
uint mTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), mTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this mToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external virtual override view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this mToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external virtual override view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external virtual override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external virtual override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public virtual view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public virtual nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the MToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public virtual view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the MToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this mToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external virtual override view returns (uint) {
return getCashPrior();
}
function getRealBorrowIndex() public view returns (uint) {
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high");
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calc block delta");
Exp memory simpleInterestFactor;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
require(mathErr == MathError.NO_ERROR, "could not calc simpleInterestFactor");
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
require(mathErr == MathError.NO_ERROR, "could not calc borrowIndex");
return borrowIndexNew;
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public virtual returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calc block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
AccrueInterestTempStorage memory temp;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.totalBorrowsNew) = addUInt(temp.interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.reservesAdded) = mulScalarTruncate(Exp({mantissa: reserveFactorMantissa}), temp.interestAccumulated);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.splitedReserves_2) = mulScalarTruncate(Exp({mantissa: reserveSplitFactorMantissa}), temp.reservesAdded);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.splitedReserves_1) = subUInt(temp.reservesAdded, temp.splitedReserves_2);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.totalReservesNew) = addUInt(temp.splitedReserves_1, reservesPrior);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = temp.borrowIndexNew;
totalBorrows = temp.totalBorrowsNew;
totalReserves = temp.totalReservesNew;
if(temp.splitedReserves_2 > 0){
address mProxy = moartroller.mProxy();
EIP20Interface(underlying).approve(mProxy, temp.splitedReserves_2);
MProxyInterface(mProxy).proxySplitReserves(underlying, temp.splitedReserves_2);
}
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, temp.interestAccumulated, temp.borrowIndexNew, temp.totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives mTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives mTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = moartroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.MINT_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the mToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of mTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
/*
* We calculate the new total supply of mTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
// unused function
// moartroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems mTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of mTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems mTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming mTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems mTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of mTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming mTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeemFresh_missing_zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = moartroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REDEEM_MOARTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/* Fail if user tries to redeem more than he has locked with c-op*/
// TODO: update error codes
uint newTokensAmount = div_(mul_(vars.accountTokensNew, vars.exchangeRateMantissa), 1e18);
if (newTokensAmount < moartroller.getUserLockedAmount(this, redeemer)) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
moartroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
function borrowForInternal(address payable borrower, uint borrowAmount) internal nonReentrant returns (uint) {
require(moartroller.isPrivilegedAddress(msg.sender), "permission_missing");
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(borrower, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = moartroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.BORROW_MOARTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
//unused function
// moartroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = moartroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REPAY_BORROW_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
/* If the borrow is repaid by another user -1 cannot be used to prevent borrow front-running */
if (repayAmount == uint(-1)) {
require(tx.origin == borrower, "specify a precise amount");
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// moartroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, MToken mTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = mTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, mTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, MToken mTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = moartroller.liquidateBorrowAllowed(address(this), address(mTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify mTokenCollateral market's block number equals current block number */
if (mTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = moartroller.liquidateCalculateSeizeUserTokens(address(this), address(mTokenCollateral), actualRepayAmount, borrower);
require(amountSeizeError == uint(Error.NO_ERROR), "CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(mTokenCollateral.balanceOf(borrower) >= seizeTokens, "TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(mTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = mTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(mTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// moartroller.liquidateBorrowVerify(address(this), address(mTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another mToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of mTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external virtual override nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another MToken.
* Its absolutely critical to use msg.sender as the seizer mToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed mToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of mTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = moartroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
// unused function
// moartroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external virtual override returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external virtual override returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new moartroller for the market
* @dev Admin function to set a new moartroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setMoartroller(Moartroller newMoartroller) public virtual returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MOARTROLLER_OWNER_CHECK);
}
Moartroller oldMoartroller = moartroller;
// Ensure invoke moartroller.isMoartroller() returns true
require(newMoartroller.isMoartroller(), "not_moartroller");
// Set market's moartroller to newMoartroller
moartroller = newMoartroller;
// Emit NewMoartroller(oldMoartroller, newMoartroller)
emit NewMoartroller(oldMoartroller, newMoartroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external virtual override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
function _setReserveSplitFactor(uint newReserveSplitFactorMantissa) external nonReentrant returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
reserveSplitFactorMantissa = newReserveSplitFactorMantissa;
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external virtual override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(AbstractInterestRateModel newInterestRateModel) public virtual returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(AbstractInterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModelInterface oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "not_interest_model");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets new value for max protection composition parameter
* @param newMPC New value of MPC
* @return uint 0=success, otherwise a failure
*/
function _setMaxProtectionComposition(uint256 newMPC) external returns(uint){
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
maxProtectionComposition = newMPC;
emit MpcUpdated(newMPC);
return uint(Error.NO_ERROR);
}
/**
* @notice Returns address of underlying token
* @return address of underlying token
*/
function getUnderlying() external override view returns(address){
return underlying;
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal virtual view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal virtual returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal virtual;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
contract MoartrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
MOARTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SUPPORT_PROTECTION_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
MOARTROLLER_REJECTION,
MOARTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_MOARTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_MOARTROLLER_REJECTION,
LIQUIDATE_MOARTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_MOARTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_MOARTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_MOARTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_MOARTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_MOARTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_MOARTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract LiquidityMathModelErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
PRICE_ERROR,
SNAPSHOT_ERROR
}
enum FailureInfo {
ORACLE_PRICE_CHECK_FAILED
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @title Exponential module for storing fixed-precision decimals
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
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 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 Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @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 safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
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;
}
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 fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "../Interfaces/EIP20Interface.sol";
contract AssetHelpers {
/**
* @dev return asset decimals mantissa. Returns 1e18 if ETH
*/
function getAssetDecimalsMantissa(address assetAddress) public view returns (uint256){
uint assetDecimals = 1e18;
if (assetAddress != address(0)) {
EIP20Interface token = EIP20Interface(assetAddress);
assetDecimals = 10 ** uint256(token.decimals());
}
return assetDecimals;
}
}
// SPDX-License-Identifier: BSD-3-Clause
// Thanks to Compound for their foundational work in DeFi and open-sourcing their code from which we build upon.
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
// import "hardhat/console.sol";
import "./MToken.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/ExponentialNoError.sol";
import "./Interfaces/PriceOracle.sol";
import "./Interfaces/MoartrollerInterface.sol";
import "./Interfaces/Versionable.sol";
import "./Interfaces/MProxyInterface.sol";
import "./MoartrollerStorage.sol";
import "./Governance/UnionGovernanceToken.sol";
import "./MProtection.sol";
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./LiquidityMathModelV1.sol";
import "./Utils/SafeEIP20.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Interfaces/LiquidationModelInterface.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title MOAR's Moartroller Contract
* @author MOAR
*/
contract Moartroller is MoartrollerV6Storage, MoartrollerInterface, MoartrollerErrorReporter, ExponentialNoError, Versionable, Initializable {
using SafeEIP20 for EIP20Interface;
/// @notice Indicator that this is a Moartroller contract (for inspection)
bool public constant isMoartroller = true;
/// @notice Emitted when an admin supports a market
event MarketListed(MToken mToken);
/// @notice Emitted when an account enters a market
event MarketEntered(MToken mToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(MToken mToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when protection is changed
event NewCProtection(MProtection oldCProtection, MProtection newCProtection);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPausedMToken(MToken mToken, string action, bool pauseState);
/// @notice Emitted when a new MOAR speed is calculated for a market
event MoarSpeedUpdated(MToken indexed mToken, uint newSpeed);
/// @notice Emitted when a new MOAR speed is set for a contributor
event ContributorMoarSpeedUpdated(address indexed contributor, uint newSpeed);
/// @notice Emitted when MOAR is distributed to a supplier
event DistributedSupplierMoar(MToken indexed mToken, address indexed supplier, uint moarDelta, uint moarSupplyIndex);
/// @notice Emitted when MOAR is distributed to a borrower
event DistributedBorrowerMoar(MToken indexed mToken, address indexed borrower, uint moarDelta, uint moarBorrowIndex);
/// @notice Emitted when borrow cap for a mToken is changed
event NewBorrowCap(MToken indexed mToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when MOAR is granted by admin
event MoarGranted(address recipient, uint amount);
event NewLiquidityMathModel(address oldLiquidityMathModel, address newLiquidityMathModel);
event NewLiquidationModel(address oldLiquidationModel, address newLiquidationModel);
/// @notice The initial MOAR index for a market
uint224 public constant moarInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// Custom initializer
function initialize(LiquidityMathModelInterface mathModel, LiquidationModelInterface lqdModel) public initializer {
admin = msg.sender;
liquidityMathModel = mathModel;
liquidationModel = lqdModel;
rewardClaimEnabled = false;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (MToken[] memory) {
MToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param mToken The mToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, MToken mToken) external view returns (bool) {
return markets[address(mToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param mTokens The list of addresses of the mToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory mTokens) public override returns (uint[] memory) {
uint len = mTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
MToken mToken = MToken(mTokens[i]);
results[i] = uint(addToMarketInternal(mToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param mToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(mToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(mToken);
emit MarketEntered(mToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param mTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address mTokenAddress) external override returns (uint) {
MToken mToken = MToken(mTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the mToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(mToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set mToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete mToken from the account’s list of assets */
// load into memory for faster iteration
MToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == mToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
MToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(mToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param mToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address mToken, address minter, uint mintAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[mToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param mToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of mTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external override returns (uint) {
uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[mToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param mToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external override {
// Shh - currently unused
mToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param mToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[mToken], "borrow is paused");
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[mToken].accountMembership[borrower]) {
// only mTokens may call borrowAllowed if borrower not in market
require(msg.sender == mToken, "sender must be mToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(MToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[mToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[mToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = MToken(mToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()});
updateMoarBorrowIndex(mToken, borrowIndex);
distributeBorrowerMoar(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param mToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()});
updateMoarBorrowIndex(mToken, borrowIndex);
distributeBorrowerMoar(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower);
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (MToken(mTokenCollateral).moartroller() != MToken(mTokenBorrowed).moartroller()) {
return uint(Error.MOARTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateMoarSupplyIndex(mTokenCollateral);
distributeSupplierMoar(mTokenCollateral, borrower);
distributeSupplierMoar(mTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param mToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of mTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(mToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, src);
distributeSupplierMoar(mToken, dst);
return uint(Error.NO_ERROR);
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address mTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
MToken mTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
MToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
MToken asset = assets[i];
address _account = account;
// Read the balances and exchange rate from the mToken
(oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(_account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = mul_(Exp({mantissa: vars.oraclePriceMantissa}), 10**uint256(18 - EIP20Interface(asset.getUnderlying()).decimals()));
// Pre-compute a conversion factor from tokens -> dai (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * mTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral);
// Protection value calculation sumCollateral += protectionValueLocked
// Mark to market value calculation sumCollateral += markToMarketValue
uint protectionValueLocked;
uint markToMarketValue;
(protectionValueLocked, markToMarketValue) = liquidityMathModel.getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet(asset, _account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle));
if (vars.sumCollateral < mul_( protectionValueLocked, vars.collateralFactor)) {
vars.sumCollateral = 0;
} else {
vars.sumCollateral = sub_(vars.sumCollateral, mul_( protectionValueLocked, vars.collateralFactor));
}
vars.sumCollateral = add_(vars.sumCollateral, protectionValueLocked);
vars.sumCollateral = add_(vars.sumCollateral, markToMarketValue);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with mTokenModify
if (asset == mTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
_account = account;
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Returns the value of possible optimization left for asset
* @param asset The MToken address
* @param account The owner of asset
* @return The value of possible optimization
*/
function getMaxOptimizableValue(MToken asset, address account) public view returns(uint){
return liquidityMathModel.getMaxOptimizableValue(
LiquidityMathModelInterface.LiquidityMathArgumentsSet(
asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle
)
);
}
/**
* @notice Returns the value of hypothetical optimization (ignoring existing optimization used) for asset
* @param asset The MToken address
* @param account The owner of asset
* @return The amount of hypothetical optimization
*/
function getHypotheticalOptimizableValue(MToken asset, address account) public view returns(uint){
return liquidityMathModel.getHypotheticalOptimizableValue(
LiquidityMathModelInterface.LiquidityMathArgumentsSet(
asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle
)
);
}
function liquidateCalculateSeizeUserTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount, address account) external override view returns (uint, uint) {
return LiquidationModelInterface(liquidationModel).liquidateCalculateSeizeUserTokens(
LiquidationModelInterface.LiquidateCalculateSeizeUserTokensArgumentsSet(
oracle,
this,
mTokenBorrowed,
mTokenCollateral,
actualRepayAmount,
account,
liquidationIncentiveMantissa
)
);
}
/**
* @notice Returns the amount of a specific asset that is locked under all c-ops
* @param asset The MToken address
* @param account The owner of asset
* @return The amount of asset locked under c-ops
*/
function getUserLockedAmount(MToken asset, address account) public override view returns(uint) {
uint protectionLockedAmount;
address currency = asset.underlying();
uint256 numOfProtections = cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(account, currency);
for (uint i = 0; i < numOfProtections; i++) {
uint cProtectionId = cprotection.getUserUnderlyingProtectionTokenIdByCurrency(account, currency, i);
if(cprotection.isProtectionAlive(cProtectionId)){
protectionLockedAmount = protectionLockedAmount + cprotection.getUnderlyingProtectionLockedAmount(cProtectionId);
}
}
return protectionLockedAmount;
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the moartroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the moartroller
PriceOracle oldOracle = oracle;
// Set moartroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new CProtection that is allowed to use as a collateral optimisation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setProtection(address newCProtection) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
MProtection oldCProtection = cprotection;
cprotection = MProtection(newCProtection);
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewCProtection(oldCProtection, cprotection);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param mToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(mToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
// TODO: this check is temporary switched off. we can make exception for UNN later
// Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
//
//
// Check collateral factor <= 0.9
// Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
// if (lessThanExp(highLimit, newCollateralFactorExp)) {
// return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
// }
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
function _setRewardClaimEnabled(bool status) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
rewardClaimEnabled = status;
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param mToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(MToken mToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(mToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
mToken.isMToken(); // Sanity check to make sure its really a MToken
// Note that isMoared is not in active use anymore
markets[address(mToken)] = Market({isListed: true, isMoared: false, collateralFactorMantissa: 0});
tokenAddressToMToken[address(mToken.underlying())] = mToken;
_addMarketInternal(address(mToken));
emit MarketListed(mToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address mToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != MToken(mToken), "market already added");
}
allMarkets.push(MToken(mToken));
}
/**
* @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param mTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = mTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(mTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(mTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(MToken mToken, bool state) public returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(mToken)] = state;
emit ActionPausedMToken(mToken, "Mint", state);
return state;
}
function _setBorrowPaused(MToken mToken, bool state) public returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(mToken)] = state;
emit ActionPausedMToken(mToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == moartrollerImplementation;
}
/*** MOAR Distribution ***/
/**
* @notice Set MOAR speed for a single market
* @param mToken The market whose MOAR speed to update
* @param moarSpeed New MOAR speed for market
*/
function setMoarSpeedInternal(MToken mToken, uint moarSpeed) internal {
uint currentMoarSpeed = moarSpeeds[address(mToken)];
if (currentMoarSpeed != 0) {
// note that MOAR speed could be set to 0 to halt liquidity rewards for a market
Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()});
updateMoarSupplyIndex(address(mToken));
updateMoarBorrowIndex(address(mToken), borrowIndex);
} else if (moarSpeed != 0) {
// Add the MOAR market
Market storage market = markets[address(mToken)];
require(market.isListed == true, "MOAR market is not listed");
if (moarSupplyState[address(mToken)].index == 0 && moarSupplyState[address(mToken)].block == 0) {
moarSupplyState[address(mToken)] = MoarMarketState({
index: moarInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (moarBorrowState[address(mToken)].index == 0 && moarBorrowState[address(mToken)].block == 0) {
moarBorrowState[address(mToken)] = MoarMarketState({
index: moarInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
if (currentMoarSpeed != moarSpeed) {
moarSpeeds[address(mToken)] = moarSpeed;
emit MoarSpeedUpdated(mToken, moarSpeed);
}
}
/**
* @notice Accrue MOAR to the market by updating the supply index
* @param mToken The market whose supply index to update
*/
function updateMoarSupplyIndex(address mToken) internal {
MoarMarketState storage supplyState = moarSupplyState[mToken];
uint supplySpeed = moarSpeeds[mToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = MToken(mToken).totalSupply();
uint moarAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(moarAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
moarSupplyState[mToken] = MoarMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue MOAR to the market by updating the borrow index
* @param mToken The market whose borrow index to update
*/
function updateMoarBorrowIndex(address mToken, Exp memory marketBorrowIndex) internal {
MoarMarketState storage borrowState = moarBorrowState[mToken];
uint borrowSpeed = moarSpeeds[mToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(MToken(mToken).totalBorrows(), marketBorrowIndex);
uint moarAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(moarAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
moarBorrowState[mToken] = MoarMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate MOAR accrued by a supplier and possibly transfer it to them
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute MOAR to
*/
function distributeSupplierMoar(address mToken, address supplier) internal {
MoarMarketState storage supplyState = moarSupplyState[mToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: moarSupplierIndex[mToken][supplier]});
moarSupplierIndex[mToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = moarInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = MToken(mToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(moarAccrued[supplier], supplierDelta);
moarAccrued[supplier] = supplierAccrued;
emit DistributedSupplierMoar(MToken(mToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate MOAR accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute MOAR to
*/
function distributeBorrowerMoar(address mToken, address borrower, Exp memory marketBorrowIndex) internal {
MoarMarketState storage borrowState = moarBorrowState[mToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: moarBorrowerIndex[mToken][borrower]});
moarBorrowerIndex[mToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(MToken(mToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(moarAccrued[borrower], borrowerDelta);
moarAccrued[borrower] = borrowerAccrued;
emit DistributedBorrowerMoar(MToken(mToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Calculate additional accrued MOAR for a contributor since last accrual
* @param contributor The address to calculate contributor rewards for
*/
function updateContributorRewards(address contributor) public {
uint moarSpeed = moarContributorSpeeds[contributor];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]);
if (deltaBlocks > 0 && moarSpeed > 0) {
uint newAccrued = mul_(deltaBlocks, moarSpeed);
uint contributorAccrued = add_(moarAccrued[contributor], newAccrued);
moarAccrued[contributor] = contributorAccrued;
lastContributorBlock[contributor] = blockNumber;
}
}
/**
* @notice Claim all the MOAR accrued by holder in all markets
* @param holder The address to claim MOAR for
*/
function claimMoarReward(address holder) public {
return claimMoar(holder, allMarkets);
}
/**
* @notice Claim all the MOAR accrued by holder in the specified markets
* @param holder The address to claim MOAR for
* @param mTokens The list of markets to claim MOAR in
*/
function claimMoar(address holder, MToken[] memory mTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimMoar(holders, mTokens, true, true);
}
/**
* @notice Claim all MOAR accrued by the holders
* @param holders The addresses to claim MOAR for
* @param mTokens The list of markets to claim MOAR in
* @param borrowers Whether or not to claim MOAR earned by borrowing
* @param suppliers Whether or not to claim MOAR earned by supplying
*/
function claimMoar(address[] memory holders, MToken[] memory mTokens, bool borrowers, bool suppliers) public {
require(rewardClaimEnabled, "reward claim is disabled");
for (uint i = 0; i < mTokens.length; i++) {
MToken mToken = mTokens[i];
require(markets[address(mToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()});
updateMoarBorrowIndex(address(mToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerMoar(address(mToken), holders[j], borrowIndex);
moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]);
}
}
if (suppliers == true) {
updateMoarSupplyIndex(address(mToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierMoar(address(mToken), holders[j]);
moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]);
}
}
}
}
/**
* @notice Transfer MOAR to the user
* @dev Note: If there is not enough MOAR, we do not perform the transfer all.
* @param user The address of the user to transfer MOAR to
* @param amount The amount of MOAR to (possibly) transfer
* @return The amount of MOAR which was NOT transferred to the user
*/
function grantMoarInternal(address user, uint amount) internal returns (uint) {
EIP20Interface moar = EIP20Interface(getMoarAddress());
uint moarRemaining = moar.balanceOf(address(this));
if (amount > 0 && amount <= moarRemaining) {
moar.approve(mProxy, amount);
MProxyInterface(mProxy).proxyClaimReward(getMoarAddress(), user, amount);
return 0;
}
return amount;
}
/*** MOAR Distribution Admin ***/
/**
* @notice Transfer MOAR to the recipient
* @dev Note: If there is not enough MOAR, we do not perform the transfer all.
* @param recipient The address of the recipient to transfer MOAR to
* @param amount The amount of MOAR to (possibly) transfer
*/
function _grantMoar(address recipient, uint amount) public {
require(adminOrInitializing(), "only admin can grant MOAR");
uint amountLeft = grantMoarInternal(recipient, amount);
require(amountLeft == 0, "insufficient MOAR for grant");
emit MoarGranted(recipient, amount);
}
/**
* @notice Set MOAR speed for a single market
* @param mToken The market whose MOAR speed to update
* @param moarSpeed New MOAR speed for market
*/
function _setMoarSpeed(MToken mToken, uint moarSpeed) public {
require(adminOrInitializing(), "only admin can set MOAR speed");
setMoarSpeedInternal(mToken, moarSpeed);
}
/**
* @notice Set MOAR speed for a single contributor
* @param contributor The contributor whose MOAR speed to update
* @param moarSpeed New MOAR speed for contributor
*/
function _setContributorMoarSpeed(address contributor, uint moarSpeed) public {
require(adminOrInitializing(), "only admin can set MOAR speed");
// note that MOAR speed could be set to 0 to halt liquidity rewards for a contributor
updateContributorRewards(contributor);
if (moarSpeed == 0) {
// release storage
delete lastContributorBlock[contributor];
} else {
lastContributorBlock[contributor] = getBlockNumber();
}
moarContributorSpeeds[contributor] = moarSpeed;
emit ContributorMoarSpeedUpdated(contributor, moarSpeed);
}
/**
* @notice Set liquidity math model implementation
* @param mathModel the math model implementation
*/
function _setLiquidityMathModel(LiquidityMathModelInterface mathModel) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
LiquidityMathModelInterface oldLiquidityMathModel = liquidityMathModel;
liquidityMathModel = mathModel;
emit NewLiquidityMathModel(address(oldLiquidityMathModel), address(liquidityMathModel));
}
/**
* @notice Set liquidation model implementation
* @param newLiquidationModel the liquidation model implementation
*/
function _setLiquidationModel(LiquidationModelInterface newLiquidationModel) public {
require(msg.sender == admin, "only admin can set liquidation model implementation");
LiquidationModelInterface oldLiquidationModel = liquidationModel;
liquidationModel = newLiquidationModel;
emit NewLiquidationModel(address(oldLiquidationModel), address(liquidationModel));
}
function _setMoarToken(address moarTokenAddress) public {
require(msg.sender == admin, "only admin can set MOAR token address");
moarToken = moarTokenAddress;
}
function _setMProxy(address mProxyAddress) public {
require(msg.sender == admin, "only admin can set MProxy address");
mProxy = mProxyAddress;
}
/**
* @notice Add new privileged address
* @param privilegedAddress address to add
*/
function _addPrivilegedAddress(address privilegedAddress) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
privilegedAddresses[privilegedAddress] = 1;
}
/**
* @notice Remove privileged address
* @param privilegedAddress address to remove
*/
function _removePrivilegedAddress(address privilegedAddress) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
delete privilegedAddresses[privilegedAddress];
}
/**
* @notice Check if address if privileged
* @param privilegedAddress address to check
*/
function isPrivilegedAddress(address privilegedAddress) public view returns (bool) {
return privilegedAddresses[privilegedAddress] == 1;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (MToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the MOAR token
* @return The address of MOAR
*/
function getMoarAddress() public view returns (address) {
return moarToken;
}
function getContractVersion() external override pure returns(string memory){
return "V1";
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Interfaces/PriceOracle.sol";
import "./CErc20.sol";
/**
* Temporary simple price feed
*/
contract SimplePriceOracle is PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
mapping(address => uint) prices;
event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa);
function getUnderlyingPrice(MToken mToken) public override view returns (uint) {
if (compareStrings(mToken.symbol(), "mDAI")) {
return 1e18;
} else {
return prices[address(MErc20(address(mToken)).underlying())];
}
}
function setUnderlyingPrice(MToken mToken, uint underlyingPriceMantissa) public {
address asset = address(MErc20(address(mToken)).underlying());
emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);
prices[asset] = underlyingPriceMantissa;
}
function setDirectPrice(address asset, uint price) public {
emit PricePosted(asset, prices[asset], price, price);
prices[asset] = price;
}
// v1 price oracle interface for use as backing of proxy
function assetPrices(address asset) external view returns (uint) {
return prices[asset];
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./Interfaces/CopMappingInterface.sol";
import "./Interfaces/Versionable.sol";
import "./Moartroller.sol";
import "./Utils/ExponentialNoError.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/AssetHelpers.sol";
import "./MToken.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Utils/SafeEIP20.sol";
/**
* @title MOAR's MProtection Contract
* @notice Collateral optimization ERC-721 wrapper
* @author MOAR
*/
contract MProtection is ERC721Upgradeable, OwnableUpgradeable, ExponentialNoError, AssetHelpers, Versionable {
using Counters for Counters.Counter;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @notice Event emitted when new MProtection token is minted
*/
event Mint(address minter, uint tokenId, uint underlyingTokenId, address asset, uint amount, uint strikePrice, uint expirationTime);
/**
* @notice Event emitted when MProtection token is redeemed
*/
event Redeem(address redeemer, uint tokenId, uint underlyingTokenId);
/**
* @notice Event emitted when MProtection token changes its locked value
*/
event LockValue(uint tokenId, uint underlyingTokenId, uint optimizationValue);
/**
* @notice Event emitted when maturity window parameter is changed
*/
event MaturityWindowUpdated(uint newMaturityWindow);
Counters.Counter private _tokenIds;
address private _copMappingAddress;
address private _moartrollerAddress;
mapping (uint256 => uint256) private _underlyingProtectionTokensMapping;
mapping (uint256 => uint256) private _underlyingProtectionLockedValue;
mapping (address => mapping (address => EnumerableSet.UintSet)) private _protectionCurrencyMapping;
uint256 public _maturityWindow;
struct ProtectionMappedData{
address pool;
address underlyingAsset;
uint256 amount;
uint256 strike;
uint256 premium;
uint256 lockedValue;
uint256 totalValue;
uint issueTime;
uint expirationTime;
bool isProtectionAlive;
}
/**
* @notice Constructor for MProtection contract
* @param copMappingAddress The address of data mapper for C-OP
* @param moartrollerAddress The address of the Moartroller
*/
function initialize(address copMappingAddress, address moartrollerAddress) public initializer {
__Ownable_init();
__ERC721_init("c-uUNN OC-Protection", "c-uUNN");
_copMappingAddress = copMappingAddress;
_moartrollerAddress = moartrollerAddress;
_setMaturityWindow(10800); // 3 hours default
}
/**
* @notice Returns C-OP mapping contract
*/
function copMapping() private view returns (CopMappingInterface){
return CopMappingInterface(_copMappingAddress);
}
/**
* @notice Mint new MProtection token
* @param underlyingTokenId Id of C-OP token that will be deposited
* @return ID of minted MProtection token
*/
function mint(uint256 underlyingTokenId) public returns (uint256)
{
return mintFor(underlyingTokenId, msg.sender);
}
/**
* @notice Mint new MProtection token for specified address
* @param underlyingTokenId Id of C-OP token that will be deposited
* @param receiver Address that will receive minted Mprotection token
* @return ID of minted MProtection token
*/
function mintFor(uint256 underlyingTokenId, address receiver) public returns (uint256)
{
CopMappingInterface copMappingInstance = copMapping();
ERC721Upgradeable(copMappingInstance.getTokenAddress()).transferFrom(msg.sender, address(this), underlyingTokenId);
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(receiver, newItemId);
addUProtectionIndexes(receiver, newItemId, underlyingTokenId);
emit Mint(
receiver,
newItemId,
underlyingTokenId,
copMappingInstance.getUnderlyingAsset(underlyingTokenId),
copMappingInstance.getUnderlyingAmount(underlyingTokenId),
copMappingInstance.getUnderlyingStrikePrice(underlyingTokenId),
copMappingInstance.getUnderlyingDeadline(underlyingTokenId)
);
return newItemId;
}
/**
* @notice Redeem C-OP token
* @param tokenId Id of MProtection token that will be withdrawn
* @return ID of redeemed C-OP token
*/
function redeem(uint256 tokenId) external returns (uint256) {
require(_isApprovedOrOwner(_msgSender(), tokenId), "cuUNN: caller is not owner nor approved");
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
ERC721Upgradeable(copMapping().getTokenAddress()).transferFrom(address(this), msg.sender, underlyingTokenId);
removeProtectionIndexes(tokenId);
_burn(tokenId);
emit Redeem(msg.sender, tokenId, underlyingTokenId);
return underlyingTokenId;
}
/**
* @notice Returns set of C-OP data
* @param tokenId Id of MProtection token
* @return ProtectionMappedData struct filled with C-OP data
*/
function getMappedProtectionData(uint256 tokenId) public view returns (ProtectionMappedData memory){
ProtectionMappedData memory data;
(address pool, uint256 amount, uint256 strike, uint256 premium, uint issueTime , uint expirationTime) = getProtectionData(tokenId);
data = ProtectionMappedData(pool, getUnderlyingAsset(tokenId), amount, strike, premium, getUnderlyingProtectionLockedValue(tokenId), getUnderlyingProtectionTotalValue(tokenId), issueTime, expirationTime, isProtectionAlive(tokenId));
return data;
}
/**
* @notice Returns underlying token ID
* @param tokenId Id of MProtection token
*/
function getUnderlyingProtectionTokenId(uint256 tokenId) public view returns (uint256){
return _underlyingProtectionTokensMapping[tokenId];
}
/**
* @notice Returns size of C-OPs filtered by asset address
* @param owner Address of wallet holding C-OPs
* @param currency Address of asset used to filter C-OPs
*/
function getUserUnderlyingProtectionTokenIdByCurrencySize(address owner, address currency) public view returns (uint256){
return _protectionCurrencyMapping[owner][currency].length();
}
/**
* @notice Returns list of C-OP IDs filtered by asset address
* @param owner Address of wallet holding C-OPs
* @param currency Address of asset used to filter C-OPs
*/
function getUserUnderlyingProtectionTokenIdByCurrency(address owner, address currency, uint256 index) public view returns (uint256){
return _protectionCurrencyMapping[owner][currency].at(index);
}
/**
* @notice Checks if address is owner of MProtection
* @param owner Address of potential owner to check
* @param tokenId ID of MProtection to check
*/
function isUserProtection(address owner, uint256 tokenId) public view returns(bool) {
if(Moartroller(_moartrollerAddress).isPrivilegedAddress(msg.sender)){
return true;
}
return owner == ownerOf(tokenId);
}
/**
* @notice Checks if MProtection is stil alive
* @param tokenId ID of MProtection to check
*/
function isProtectionAlive(uint256 tokenId) public view returns(bool) {
uint256 deadline = getUnderlyingDeadline(tokenId);
return (deadline - _maturityWindow) > now;
}
/**
* @notice Creates appropriate indexes for C-OP
* @param owner C-OP owner address
* @param tokenId ID of MProtection
* @param underlyingTokenId ID of C-OP
*/
function addUProtectionIndexes(address owner, uint256 tokenId, uint256 underlyingTokenId) private{
address currency = copMapping().getUnderlyingAsset(underlyingTokenId);
_underlyingProtectionTokensMapping[tokenId] = underlyingTokenId;
_protectionCurrencyMapping[owner][currency].add(tokenId);
}
/**
* @notice Remove indexes for C-OP
* @param tokenId ID of MProtection
*/
function removeProtectionIndexes(uint256 tokenId) private{
address owner = ownerOf(tokenId);
address currency = getUnderlyingAsset(tokenId);
_underlyingProtectionTokensMapping[tokenId] = 0;
_protectionCurrencyMapping[owner][currency].remove(tokenId);
}
/**
* @notice Returns C-OP total value
* @param tokenId ID of MProtection
*/
function getUnderlyingProtectionTotalValue(uint256 tokenId) public view returns(uint256){
address underlyingAsset = getUnderlyingAsset(tokenId);
uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset);
return div_(
mul_(
getUnderlyingStrikePrice(tokenId),
getUnderlyingAmount(tokenId)
),
assetDecimalsMantissa
);
}
/**
* @notice Returns C-OP locked value
* @param tokenId ID of MProtection
*/
function getUnderlyingProtectionLockedValue(uint256 tokenId) public view returns(uint256){
return _underlyingProtectionLockedValue[tokenId];
}
/**
* @notice get the amount of underlying asset that is locked
* @param tokenId CProtection tokenId
* @return amount locked
*/
function getUnderlyingProtectionLockedAmount(uint256 tokenId) public view returns(uint256){
address underlyingAsset = getUnderlyingAsset(tokenId);
uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset);
// calculates total protection value
uint256 protectionValue = div_(
mul_(
getUnderlyingAmount(tokenId),
getUnderlyingStrikePrice(tokenId)
),
assetDecimalsMantissa
);
// return value is lockedValue / totalValue * amount
return div_(
mul_(
getUnderlyingAmount(tokenId),
div_(
mul_(
_underlyingProtectionLockedValue[tokenId],
1e18
),
protectionValue
)
),
1e18
);
}
/**
* @notice Locks the given protection value as collateral optimization
* @param tokenId The MProtection token id
* @param value The value in stablecoin of protection to be locked as collateral optimization. 0 = max available optimization
* @return locked protection value
* TODO: convert semantic errors to standarized error codes
*/
function lockProtectionValue(uint256 tokenId, uint value) external returns(uint) {
//check if the protection belongs to the caller
require(isUserProtection(msg.sender, tokenId), "ERROR: CALLER IS NOT THE OWNER OF PROTECTION");
address currency = getUnderlyingAsset(tokenId);
Moartroller moartroller = Moartroller(_moartrollerAddress);
MToken mToken = moartroller.tokenAddressToMToken(currency);
require(moartroller.oracle().getUnderlyingPrice(mToken) <= getUnderlyingStrikePrice(tokenId), "ERROR: C-OP STRIKE PRICE IS LOWER THAN ASSET SPOT PRICE");
uint protectionTotalValue = getUnderlyingProtectionTotalValue(tokenId);
uint maxOptimizableValue = moartroller.getMaxOptimizableValue(mToken, ownerOf(tokenId));
// add protection locked value if any
uint protectionLockedValue = getUnderlyingProtectionLockedValue(tokenId);
if ( protectionLockedValue > 0) {
maxOptimizableValue = add_(maxOptimizableValue, protectionLockedValue);
}
uint valueToLock;
if (value != 0) {
// check if lock value is at most max optimizable value
require(value <= maxOptimizableValue, "ERROR: VALUE TO BE LOCKED EXCEEDS ALLOWED OPTIMIZATION VALUE");
// check if lock value is at most protection total value
require( value <= protectionTotalValue, "ERROR: VALUE TO BE LOCKED EXCEEDS PROTECTION TOTAL VALUE");
valueToLock = value;
} else {
// if we want to lock maximum protection value let's lock the value that is at most max optimizable value
if (protectionTotalValue > maxOptimizableValue) {
valueToLock = maxOptimizableValue;
} else {
valueToLock = protectionTotalValue;
}
}
_underlyingProtectionLockedValue[tokenId] = valueToLock;
emit LockValue(tokenId, getUnderlyingProtectionTokenId(tokenId), valueToLock);
return valueToLock;
}
function _setCopMapping(address newMapping) public onlyOwner {
_copMappingAddress = newMapping;
}
function _setMoartroller(address newMoartroller) public onlyOwner {
_moartrollerAddress = newMoartroller;
}
function _setMaturityWindow(uint256 maturityWindow) public onlyOwner {
emit MaturityWindowUpdated(maturityWindow);
_maturityWindow = maturityWindow;
}
// MAPPINGS
function getProtectionData(uint256 tokenId) public view returns (address, uint256, uint256, uint256, uint, uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getProtectionData(underlyingTokenId);
}
function getUnderlyingAsset(uint256 tokenId) public view returns (address){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingAsset(underlyingTokenId);
}
function getUnderlyingAmount(uint256 tokenId) public view returns (uint256){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingAmount(underlyingTokenId);
}
function getUnderlyingStrikePrice(uint256 tokenId) public view returns (uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingStrikePrice(underlyingTokenId);
}
function getUnderlyingDeadline(uint256 tokenId) public view returns (uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingDeadline(underlyingTokenId);
}
function getContractVersion() external override pure returns(string memory){
return "V1";
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
interface PriceOracle {
/**
* @notice Get the underlying price of a mToken asset
* @param mToken The mToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(MToken mToken) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @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);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @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 The balance
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @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
* @return success Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool);
/**
* @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
* @return success Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool);
/**
* @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 (-1 means infinite)
* @return success Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @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 (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256);
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.6.12;
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
abstract contract MTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @dev EIP-20 token name for this token
*/
string public name;
/**
* @dev EIP-20 token symbol for this token
*/
string public symbol;
/**
* @dev EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Underlying asset for this MToken
*/
address public underlying;
/**
* @dev Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal borrowRateMaxMantissa;
/**
* @dev Maximum fraction of interest that can be set aside for reserves
*/
uint internal reserveFactorMaxMantissa;
/**
* @dev Administrator for this contract
*/
address payable public admin;
/**
* @dev Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @dev Contract which oversees inter-mToken operations
*/
Moartroller public moartroller;
/**
* @dev Model which tells what the current interest rate should be
*/
AbstractInterestRateModel public interestRateModel;
/**
* @dev Initial exchange rate used when minting the first MTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @dev Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @dev Fraction of reserves currently set aside for other usage
*/
uint public reserveSplitFactorMantissa;
/**
* @dev Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @dev Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @dev Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @dev Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @dev Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @dev The Maximum Protection Moarosition (MPC) factor for collateral optimisation, default: 50% = 5000
*/
uint public maxProtectionComposition;
/**
* @dev The Maximum Protection Moarosition (MPC) mantissa, default: 1e5
*/
uint public maxProtectionCompositionMantissa;
/**
* @dev Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @dev Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
struct ProtectionUsage {
uint256 protectionValueUsed;
}
/**
* @dev Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
mapping (uint256 => ProtectionUsage) protectionsUsed;
}
struct AccrueInterestTempStorage{
uint interestAccumulated;
uint reservesAdded;
uint splitedReserves_1;
uint splitedReserves_2;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
}
/**
* @dev Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) public accountBorrows;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./EIP20Interface.sol";
interface MTokenInterface {
/*** User contract ***/
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(address src, address dst, uint256 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 getCash() external view returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
function getUnderlying() external view returns(address);
function sweepToken(EIP20Interface token) external;
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
interface MProxyInterface {
function proxyClaimReward(address asset, address recipient, uint amount) external;
function proxySplitReserves(address asset, uint amount) external;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Interfaces/InterestRateModelInterface.sol";
abstract contract AbstractInterestRateModel is InterestRateModelInterface {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @title Careful Math
* @author MOAR
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
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);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
import "../Utils/ExponentialNoError.sol";
interface MoartrollerInterface {
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `mTokenBalance` is the number of mTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint mTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
ExponentialNoError.Exp collateralFactor;
ExponentialNoError.Exp exchangeRate;
ExponentialNoError.Exp oraclePrice;
ExponentialNoError.Exp tokensToDenom;
}
/*** Assets You Are In ***/
function enterMarkets(address[] calldata mTokens) external returns (uint[] memory);
function exitMarket(address mToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint);
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint);
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint);
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeUserTokens(
address mTokenBorrowed,
address mTokenCollateral,
uint repayAmount,
address account) external view returns (uint, uint);
function getUserLockedAmount(MToken asset, address account) external view returns(uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
interface Versionable {
function getContractVersion() external pure returns (string memory);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./MToken.sol";
import "./Interfaces/PriceOracle.sol";
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./Interfaces/LiquidationModelInterface.sol";
import "./MProtection.sol";
abstract contract UnitrollerAdminStorage {
/**
* @dev Administrator for this contract
*/
address public admin;
/**
* @dev Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @dev Active brains of Unitroller
*/
address public moartrollerImplementation;
/**
* @dev Pending brains of Unitroller
*/
address public pendingMoartrollerImplementation;
}
contract MoartrollerV1Storage is UnitrollerAdminStorage {
/**
* @dev Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @dev Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @dev Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @dev Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @dev Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => MToken[]) public accountAssets;
}
contract MoartrollerV2Storage is MoartrollerV1Storage {
struct Market {
// Whether or not this market is listed
bool isListed;
// Multiplier representing the most one can borrow against their collateral in this market.
// For instance, 0.9 to allow borrowing 90% of collateral value.
// Must be between 0 and 1, and stored as a mantissa.
uint collateralFactorMantissa;
// Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
// Whether or not this market receives MOAR
bool isMoared;
}
/**
* @dev Official mapping of mTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @dev The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract MoartrollerV3Storage is MoartrollerV2Storage {
struct MoarMarketState {
// The market's last updated moarBorrowIndex or moarSupplyIndex
uint224 index;
// The block number the index was last updated at
uint32 block;
}
/// @dev A list of all markets
MToken[] public allMarkets;
/// @dev The rate at which the flywheel distributes MOAR, per block
uint public moarRate;
/// @dev The portion of moarRate that each market currently receives
mapping(address => uint) public moarSpeeds;
/// @dev The MOAR market supply state for each market
mapping(address => MoarMarketState) public moarSupplyState;
/// @dev The MOAR market borrow state for each market
mapping(address => MoarMarketState) public moarBorrowState;
/// @dev The MOAR borrow index for each market for each supplier as of the last time they accrued MOAR
mapping(address => mapping(address => uint)) public moarSupplierIndex;
/// @dev The MOAR borrow index for each market for each borrower as of the last time they accrued MOAR
mapping(address => mapping(address => uint)) public moarBorrowerIndex;
/// @dev The MOAR accrued but not yet transferred to each user
mapping(address => uint) public moarAccrued;
}
contract MoartrollerV4Storage is MoartrollerV3Storage {
// @dev The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @dev Borrow caps enforced by borrowAllowed for each mToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint) public borrowCaps;
}
contract MoartrollerV5Storage is MoartrollerV4Storage {
/// @dev The portion of MOAR that each contributor receives per block
mapping(address => uint) public moarContributorSpeeds;
/// @dev Last block at which a contributor's MOAR rewards have been allocated
mapping(address => uint) public lastContributorBlock;
}
contract MoartrollerV6Storage is MoartrollerV5Storage {
/**
* @dev Moar token address
*/
address public moarToken;
/**
* @dev MProxy address
*/
address public mProxy;
/**
* @dev CProtection contract which can be used for collateral optimisation
*/
MProtection public cprotection;
/**
* @dev Mapping for basic token address to mToken
*/
mapping(address => MToken) public tokenAddressToMToken;
/**
* @dev Math model for liquidity calculation
*/
LiquidityMathModelInterface public liquidityMathModel;
/**
* @dev Liquidation model for liquidation related functions
*/
LiquidationModelInterface public liquidationModel;
/**
* @dev List of addresses with privileged access
*/
mapping(address => uint) public privilegedAddresses;
/**
* @dev Determines if reward claim feature is enabled
*/
bool public rewardClaimEnabled;
}
// Copyright (c) 2020 The UNION Protocol Foundation
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// import "hardhat/console.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
/**
* @title UNION Protocol Governance Token
* @dev Implementation of the basic standard token.
*/
contract UnionGovernanceToken is AccessControl, IERC20 {
using Address for address;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @notice Struct for marking number of votes from a given block
* @member from
* @member votes
*/
struct VotingCheckpoint {
uint256 from;
uint256 votes;
}
/**
* @notice Struct for locked tokens
* @member amount
* @member releaseTime
* @member votable
*/
struct LockedTokens{
uint amount;
uint releaseTime;
bool votable;
}
/**
* @notice Struct for EIP712 Domain
* @member name
* @member version
* @member chainId
* @member verifyingContract
* @member salt
*/
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
bytes32 salt;
}
/**
* @notice Struct for EIP712 VotingDelegate call
* @member owner
* @member delegate
* @member nonce
* @member expirationTime
*/
struct VotingDelegate {
address owner;
address delegate;
uint256 nonce;
uint256 expirationTime;
}
/**
* @notice Struct for EIP712 Permit call
* @member owner
* @member spender
* @member value
* @member nonce
* @member deadline
*/
struct Permit {
address owner;
address spender;
uint256 value;
uint256 nonce;
uint256 deadline;
}
/**
* @notice Vote Delegation Events
*/
event VotingDelegateChanged(address indexed _owner, address indexed _fromDelegate, address indexed _toDelegate);
event VotingDelegateRemoved(address indexed _owner);
/**
* @notice Vote Balance Events
* Emmitted when a delegate account's vote balance changes at the time of a written checkpoint
*/
event VoteBalanceChanged(address indexed _account, uint256 _oldBalance, uint256 _newBalance);
/**
* @notice Transfer/Allocator Events
*/
event TransferStatusChanged(bool _newTransferStatus);
/**
* @notice Reversion Events
*/
event ReversionStatusChanged(bool _newReversionSetting);
/**
* @notice EIP-20 Approval event
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @notice EIP-20 Transfer event
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Burn(address indexed _from, uint256 _value);
event AddressPermitted(address indexed _account);
event AddressRestricted(address indexed _account);
/**
* @dev AccessControl recognized roles
*/
bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN");
bytes32 public constant ROLE_ALLOCATE = keccak256("ROLE_ALLOCATE");
bytes32 public constant ROLE_GOVERN = keccak256("ROLE_GOVERN");
bytes32 public constant ROLE_MINT = keccak256("ROLE_MINT");
bytes32 public constant ROLE_LOCK = keccak256("ROLE_LOCK");
bytes32 public constant ROLE_TRUSTED = keccak256("ROLE_TRUSTED");
bytes32 public constant ROLE_TEST = keccak256("ROLE_TEST");
bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
);
bytes32 public constant DELEGATE_TYPEHASH = keccak256(
"DelegateVote(address owner,address delegate,uint256 nonce,uint256 expirationTime)"
);
//keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
address private constant BURN_ADDRESS = address(0);
address public UPGT_CONTRACT_ADDRESS;
/**
* @dev hashes to support EIP-712 signing and validating, EIP712DOMAIN_SEPARATOR is set at time of contract instantiation and token minting.
*/
bytes32 public immutable EIP712DOMAIN_SEPARATOR;
/**
* @dev EIP-20 token name
*/
string public name = "UNION Protocol Governance Token";
/**
* @dev EIP-20 token symbol
*/
string public symbol = "UNN";
/**
* @dev EIP-20 token decimals
*/
uint8 public decimals = 18;
/**
* @dev Contract version
*/
string public constant version = '0.0.1';
/**
* @dev Initial amount of tokens
*/
uint256 private uint256_initialSupply = 100000000000 * 10**18;
/**
* @dev Total amount of tokens
*/
uint256 private uint256_totalSupply;
/**
* @dev Chain id
*/
uint256 private uint256_chain_id;
/**
* @dev general transfer restricted as function of public sale not complete
*/
bool private b_canTransfer = false;
/**
* @dev private variable that determines if failed EIP-20 functions revert() or return false. Reversion short-circuits the return from these functions.
*/
bool private b_revert = false; //false allows false return values
/**
* @dev Locked destinations list
*/
mapping(address => bool) private m_lockedDestinations;
/**
* @dev EIP-20 allowance and balance maps
*/
mapping(address => mapping(address => uint256)) private m_allowances;
mapping(address => uint256) private m_balances;
mapping(address => LockedTokens[]) private m_lockedBalances;
/**
* @dev nonces used by accounts to this contract for signing and validating signatures under EIP-712
*/
mapping(address => uint256) private m_nonces;
/**
* @dev delegated account may for off-line vote delegation
*/
mapping(address => address) private m_delegatedAccounts;
/**
* @dev delegated account inverse map is needed to live calculate voting power
*/
mapping(address => EnumerableSet.AddressSet) private m_delegatedAccountsInverseMap;
/**
* @dev indexed mapping of vote checkpoints for each account
*/
mapping(address => mapping(uint256 => VotingCheckpoint)) private m_votingCheckpoints;
/**
* @dev mapping of account addrresses to voting checkpoints
*/
mapping(address => uint256) private m_accountVotingCheckpoints;
/**
* @dev Contructor for the token
* @param _owner address of token contract owner
* @param _initialSupply of tokens generated by this contract
* Sets Transfer the total suppply to the owner.
* Sets default admin role to the owner.
* Sets ROLE_ALLOCATE to the owner.
* Sets ROLE_GOVERN to the owner.
* Sets ROLE_MINT to the owner.
* Sets EIP 712 Domain Separator.
*/
constructor(address _owner, uint256 _initialSupply) public {
//set internal contract references
UPGT_CONTRACT_ADDRESS = address(this);
//setup roles using AccessControl
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(ROLE_ADMIN, _owner);
_setupRole(ROLE_ADMIN, _msgSender());
_setupRole(ROLE_ALLOCATE, _owner);
_setupRole(ROLE_ALLOCATE, _msgSender());
_setupRole(ROLE_TRUSTED, _owner);
_setupRole(ROLE_TRUSTED, _msgSender());
_setupRole(ROLE_GOVERN, _owner);
_setupRole(ROLE_MINT, _owner);
_setupRole(ROLE_LOCK, _owner);
_setupRole(ROLE_TEST, _owner);
m_balances[_owner] = _initialSupply;
uint256_totalSupply = _initialSupply;
b_canTransfer = false;
uint256_chain_id = _getChainId();
EIP712DOMAIN_SEPARATOR = _hash(EIP712Domain({
name : name,
version : version,
chainId : uint256_chain_id,
verifyingContract : address(this),
salt : keccak256(abi.encodePacked(name))
}
));
emit Transfer(BURN_ADDRESS, _owner, uint256_totalSupply);
}
/**
* @dev Sets transfer status to lock token transfer
* @param _canTransfer value can be true or false.
* disables transfer when set to false and enables transfer when true
* Only a member of ADMIN role can call to change transfer status
*/
function setCanTransfer(bool _canTransfer) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
b_canTransfer = _canTransfer;
emit TransferStatusChanged(_canTransfer);
}
}
/**
* @dev Gets status of token transfer lock
* @return true or false status of whether the token can be transfered
*/
function getCanTransfer() public view returns (bool) {
return b_canTransfer;
}
/**
* @dev Sets transfer reversion status to either return false or throw on error
* @param _reversion value can be true or false.
* disables return of false values for transfer failures when set to false and enables transfer-related exceptions when true
* Only a member of ADMIN role can call to change transfer reversion status
*/
function setReversion(bool _reversion) public {
if(hasRole(ROLE_ADMIN, _msgSender()) ||
hasRole(ROLE_TEST, _msgSender())
) {
b_revert = _reversion;
emit ReversionStatusChanged(_reversion);
}
}
/**
* @dev Gets status of token transfer reversion
* @return true or false status of whether the token transfer failures return false or are reverted
*/
function getReversion() public view returns (bool) {
return b_revert;
}
/**
* @dev retrieve current chain id
* @return chain id
*/
function getChainId() public pure returns (uint256) {
return _getChainId();
}
/**
* @dev Retrieve current chain id
* @return chain id
*/
function _getChainId() internal pure returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* @dev Retrieve total supply of tokens
* @return uint256 total supply of tokens
*/
function totalSupply() public view override returns (uint256) {
return uint256_totalSupply;
}
/**
* Balance related functions
*/
/**
* @dev Retrieve balance of a specified account
* @param _account address of account holding balance
* @return uint256 balance of the specified account address
*/
function balanceOf(address _account) public view override returns (uint256) {
return m_balances[_account].add(_calculateReleasedBalance(_account));
}
/**
* @dev Retrieve locked balance of a specified account
* @param _account address of account holding locked balance
* @return uint256 locked balance of the specified account address
*/
function lockedBalanceOf(address _account) public view returns (uint256) {
return _calculateLockedBalance(_account);
}
/**
* @dev Retrieve lenght of locked balance array for specific address
* @param _account address of account holding locked balance
* @return uint256 locked balance array lenght
*/
function getLockedTokensListSize(address _account) public view returns (uint256){
require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions");
return m_lockedBalances[_account].length;
}
/**
* @dev Retrieve locked tokens struct from locked balance array for specific address
* @param _account address of account holding locked tokens
* @param _index index in array with locked tokens position
* @return amount of locked tokens
* @return releaseTime descibes time when tokens will be unlocked
* @return votable flag is describing votability of tokens
*/
function getLockedTokens(address _account, uint256 _index) public view returns (uint256 amount, uint256 releaseTime, bool votable){
require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions");
require(_index < m_lockedBalances[_account].length, "UPGT_ERROR: LockedTokens position doesn't exist on given index");
LockedTokens storage lockedTokens = m_lockedBalances[_account][_index];
return (lockedTokens.amount, lockedTokens.releaseTime, lockedTokens.votable);
}
/**
* @dev Calculates locked balance of a specified account
* @param _account address of account holding locked balance
* @return uint256 locked balance of the specified account address
*/
function _calculateLockedBalance(address _account) private view returns (uint256) {
uint256 lockedBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime > block.timestamp){
lockedBalance = lockedBalance.add(m_lockedBalances[_account][i].amount);
}
}
return lockedBalance;
}
/**
* @dev Calculates released balance of a specified account
* @param _account address of account holding released balance
* @return uint256 released balance of the specified account address
*/
function _calculateReleasedBalance(address _account) private view returns (uint256) {
uint256 releasedBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){
releasedBalance = releasedBalance.add(m_lockedBalances[_account][i].amount);
}
}
return releasedBalance;
}
/**
* @dev Calculates locked votable balance of a specified account
* @param _account address of account holding locked votable balance
* @return uint256 locked votable balance of the specified account address
*/
function _calculateLockedVotableBalance(address _account) private view returns (uint256) {
uint256 lockedVotableBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].votable == true){
lockedVotableBalance = lockedVotableBalance.add(m_lockedBalances[_account][i].amount);
}
}
return lockedVotableBalance;
}
/**
* @dev Moves released balance to normal balance for a specified account
* @param _account address of account holding released balance
*/
function _moveReleasedBalance(address _account) internal virtual{
uint256 releasedToMove = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){
releasedToMove = releasedToMove.add(m_lockedBalances[_account][i].amount);
m_lockedBalances[_account][i] = m_lockedBalances[_account][m_lockedBalances[_account].length - 1];
m_lockedBalances[_account].pop();
}
}
m_balances[_account] = m_balances[_account].add(releasedToMove);
}
/**
* Allowance related functinons
*/
/**
* @dev Retrieve the spending allowance for a token holder by a specified account
* @param _owner Token account holder
* @param _spender Account given allowance
* @return uint256 allowance value
*/
function allowance(address _owner, address _spender) public override virtual view returns (uint256) {
return m_allowances[_owner][_spender];
}
/**
* @dev Message sender approval to spend for a specified amount
* @param _spender address of party approved to spend
* @param _value amount of the approval
* @return boolean success status
* public wrapper for _approve, _owner is msg.sender
*/
function approve(address _spender, uint256 _value) public override returns (bool) {
bool success = _approveUNN(_msgSender(), _spender, _value);
if(!success && b_revert){
revert("UPGT_ERROR: APPROVE ERROR");
}
return success;
}
/**
* @dev Token owner approval of amount for specified spender
* @param _owner address of party that owns the tokens being granted approval for spending
* @param _spender address of party that is granted approval for spending
* @param _value amount approved for spending
* @return boolean approval status
* if _spender allownace for a given _owner is greater than 0,
* increaseAllowance/decreaseAllowance should be used to prevent a race condition whereby the spender is able to spend the total value of both the old and new allowance. _spender cannot be burn or this governance token contract address. Addresses github.com/ethereum/EIPs/issues738
*/
function _approveUNN(address _owner, address _spender, uint256 _value) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
(m_allowances[_owner][_spender] == 0 || _value == 0)
){
m_allowances[_owner][_spender] = _value;
emit Approval(_owner, _spender, _value);
retval = true;
}
return retval;
}
/**
* @dev Increase spender allowance by specified incremental value
* @param _spender address of party that is granted approval for spending
* @param _addedValue specified incremental increase
* @return boolean increaseAllowance status
* public wrapper for _increaseAllowance, _owner restricted to msg.sender
*/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
bool success = _increaseAllowanceUNN(_msgSender(), _spender, _addedValue);
if(!success && b_revert){
revert("UPGT_ERROR: INCREASE ALLOWANCE ERROR");
}
return success;
}
/**
* @dev Allow owner to increase spender allowance by specified incremental value
* @param _owner address of the token owner
* @param _spender address of the token spender
* @param _addedValue specified incremental increase
* @return boolean return value status
* increase the number of tokens that an _owner provides as allowance to a _spender-- does not requrire the number of tokens allowed to be set first to 0. _spender cannot be either burn or this goverance token contract address.
*/
function _increaseAllowanceUNN(address _owner, address _spender, uint256 _addedValue) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
_addedValue > 0
){
m_allowances[_owner][_spender] = m_allowances[_owner][_spender].add(_addedValue);
retval = true;
emit Approval(_owner, _spender, m_allowances[_owner][_spender]);
}
return retval;
}
/**
* @dev Decrease spender allowance by specified incremental value
* @param _spender address of party that is granted approval for spending
* @param _subtractedValue specified incremental decrease
* @return boolean success status
* public wrapper for _decreaseAllowance, _owner restricted to msg.sender
*/
//public wrapper for _decreaseAllowance, _owner restricted to msg.sender
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
bool success = _decreaseAllowanceUNN(_msgSender(), _spender, _subtractedValue);
if(!success && b_revert){
revert("UPGT_ERROR: DECREASE ALLOWANCE ERROR");
}
return success;
}
/**
* @dev Allow owner to decrease spender allowance by specified incremental value
* @param _owner address of the token owner
* @param _spender address of the token spender
* @param _subtractedValue specified incremental decrease
* @return boolean return value status
* decrease the number of tokens than an _owner provdes as allowance to a _spender. A _spender cannot have a negative allowance. Does not require existing allowance to be set first to 0. _spender cannot be burn or this governance token contract address.
*/
function _decreaseAllowanceUNN(address _owner, address _spender, uint256 _subtractedValue) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
_subtractedValue > 0 &&
m_allowances[_owner][_spender] >= _subtractedValue
){
m_allowances[_owner][_spender] = m_allowances[_owner][_spender].sub(_subtractedValue);
retval = true;
emit Approval(_owner, _spender, m_allowances[_owner][_spender]);
}
return retval;
}
/**
* LockedDestination related functions
*/
/**
* @dev Adds address as a designated destination for tokens when locked for allocation only
* @param _address Address of approved desitnation for movement during lock
* @return success in setting address as eligible for transfer independent of token lock status
*/
function setAsEligibleLockedDestination(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
m_lockedDestinations[_address] = true;
retVal = true;
}
return retVal;
}
/**
* @dev removes desitnation as eligible for transfer
* @param _address address being removed
*/
function removeEligibleLockedDestination(address _address) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
require(_address != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
delete(m_lockedDestinations[_address]);
}
}
/**
* @dev checks whether a destination is eligible as recipient of transfer independent of token lock status
* @param _address address being checked
* @return whether desitnation is locked
*/
function checkEligibleLockedDesination(address _address) public view returns (bool) {
return m_lockedDestinations[_address];
}
/**
* @dev Adds address as a designated allocator that can move tokens when they are locked
* @param _address Address receiving the role of ROLE_ALLOCATE
* @return success as true or false
*/
function setAsAllocator(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
grantRole(ROLE_ALLOCATE, _address);
retVal = true;
}
return retVal;
}
/**
* @dev Removes address as a designated allocator that can move tokens when they are locked
* @param _address Address being removed from the ROLE_ALLOCATE
* @return success as true or false
*/
function removeAsAllocator(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
if(hasRole(ROLE_ALLOCATE, _address)){
revokeRole(ROLE_ALLOCATE, _address);
retVal = true;
}
}
return retVal;
}
/**
* @dev Checks to see if an address has the role of being an allocator
* @param _address Address being checked for ROLE_ALLOCATE
* @return true or false whether the address has ROLE_ALLOCATE assigned
*/
function checkAsAllocator(address _address) public view returns (bool) {
return hasRole(ROLE_ALLOCATE, _address);
}
/**
* Transfer related functions
*/
/**
* @dev Public wrapper for transfer function to move tokens of specified value to a given address
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @return status of transfer success
*/
function transfer(address _to, uint256 _value) external override returns (bool) {
bool success = _transferUNN(_msgSender(), _to, _value);
if(!success && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER");
}
return success;
}
/**
* @dev Transfer token for a specified address, but cannot transfer tokens to either the burn or this governance contract address. Also moves voting delegates as required.
* @param _owner The address owner where transfer originates
* @param _to The address to transfer to
* @param _value The amount to be transferred
* @return status of transfer success
*/
function _transferUNN(address _owner, address _to, uint256 _value) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value >= 0)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_balances[_to] = m_balances[_to].add(_value);
retval = true;
//need to move voting delegates with transfer of tokens
retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferAndLock function to move tokens of specified value to a given address and lock them for a period of time
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
* Requires ROLE_LOCK
*/
function transferAndLock(address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) {
bool retval = false;
if(hasRole(ROLE_LOCK, _msgSender())){
retval = _transferAndLock(msg.sender, _to, _value, _releaseTime, _votable);
}
if(!retval && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER AND LOCK");
}
return retval;
}
/**
* @dev Transfers tokens of specified value to a given address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
*/
function _transferAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal virtual returns (bool){
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value >= 0)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable));
retval = true;
//need to move voting delegates with transfer of tokens
// retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferFrom function
* @param _owner The address to transfer from
* @param _spender cannot be the burn address
* @param _value The amount to be transferred
* @return status of transferFrom success
* _spender cannot be either this goverance token contract or burn
*/
function transferFrom(address _owner, address _spender, uint256 _value) external override returns (bool) {
bool success = _transferFromUNN(_owner, _spender, _value);
if(!success && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER FROM");
}
return success;
}
/**
* @dev Transfer token for a specified address. _spender cannot be either this goverance token contract or burn
* @param _owner The address to transfer from
* @param _spender cannot be the burn address
* @param _value The amount to be transferred
* @return status of transferFrom success
* _spender cannot be either this goverance token contract or burn
*/
function _transferFromUNN(address _owner, address _spender, uint256 _value) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_spender)) {
if(
_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value > 0) &&
(m_allowances[_owner][_msgSender()] >= _value)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_balances[_spender] = m_balances[_spender].add(_value);
m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value);
retval = true;
//need to move delegates that exist for this owner in line with transfer
retval = retval && _moveVotingDelegates(_owner, _spender, _value);
emit Transfer(_owner, _spender, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferFromAndLock function to move tokens of specified value from given address to another address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
* Requires ROLE_LOCK
*/
function transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) {
bool retval = false;
if(hasRole(ROLE_LOCK, _msgSender())){
retval = _transferFromAndLock(_owner, _to, _value, _releaseTime, _votable);
}
if(!retval && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER FROM AND LOCK");
}
return retval;
}
/**
* @dev Transfers tokens of specified value from a given address to another address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
*/
function _transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value > 0) &&
(m_allowances[_owner][_msgSender()] >= _value)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable));
m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value);
retval = true;
//need to move delegates that exist for this owner in line with transfer
// retval = retval && _moveVotingDelegates(_owner, _to, _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public function to burn tokens
* @param _value number of tokens to be burned
* @return whether tokens were burned
* Only ROLE_MINTER may burn tokens
*/
function burn(uint256 _value) external returns (bool) {
bool success = _burn(_value);
if(!success && b_revert){
revert("UPGT_ERROR: FAILED TO BURN");
}
return success;
}
/**
* @dev Private function Burn tokens
* @param _value number of tokens to be burned
* @return bool whether the tokens were burned
* only a minter may burn tokens, meaning that tokens being burned must be previously send to a ROLE_MINTER wallet.
*/
function _burn(uint256 _value) internal returns (bool) {
bool retval = false;
if(hasRole(ROLE_MINT, _msgSender()) &&
(m_balances[_msgSender()] >= _value)
){
m_balances[_msgSender()] -= _value;
uint256_totalSupply = uint256_totalSupply.sub(_value);
retval = true;
emit Burn(_msgSender(), _value);
}
return retval;
}
/**
* Voting related functions
*/
/**
* @dev Public wrapper for _calculateVotingPower function which calulates voting power
* @dev voting power = balance + locked votable balance + delegations
* @return uint256 voting power
*/
function calculateVotingPower() public view returns (uint256) {
return _calculateVotingPower(_msgSender());
}
/**
* @dev Calulates voting power of specified address
* @param _account address of token holder
* @return uint256 voting power
*/
function _calculateVotingPower(address _account) private view returns (uint256) {
uint256 votingPower = m_balances[_account].add(_calculateLockedVotableBalance(_account));
for (uint i=0; i<m_delegatedAccountsInverseMap[_account].length(); i++) {
if(m_delegatedAccountsInverseMap[_account].at(i) != address(0)){
address delegatedAccount = m_delegatedAccountsInverseMap[_account].at(i);
votingPower = votingPower.add(m_balances[delegatedAccount]).add(_calculateLockedVotableBalance(delegatedAccount));
}
}
return votingPower;
}
/**
* @dev Moves a number of votes from a token holder to a designated representative
* @param _source address of token holder
* @param _destination address of voting delegate
* @param _amount of voting delegation transfered to designated representative
* @return bool whether move was successful
* Requires ROLE_TEST
*/
function moveVotingDelegates(
address _source,
address _destination,
uint256 _amount) public returns (bool) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _moveVotingDelegates(_source, _destination, _amount);
}
/**
* @dev Moves a number of votes from a token holder to a designated representative
* @param _source address of token holder
* @param _destination address of voting delegate
* @param _amount of voting delegation transfered to designated representative
* @return bool whether move was successful
*/
function _moveVotingDelegates(
address _source,
address _destination,
uint256 _amount
) internal returns (bool) {
if(_source != _destination && _amount > 0) {
if(_source != BURN_ADDRESS) {
uint256 sourceNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_source];
uint256 sourceNumberOfVotingCheckpointsOriginal = (sourceNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][sourceNumberOfVotingCheckpoints.sub(1)].votes : 0;
if(sourceNumberOfVotingCheckpointsOriginal >= _amount) {
uint256 sourceNumberOfVotingCheckpointsNew = sourceNumberOfVotingCheckpointsOriginal.sub(_amount);
_writeVotingCheckpoint(_source, sourceNumberOfVotingCheckpoints, sourceNumberOfVotingCheckpointsOriginal, sourceNumberOfVotingCheckpointsNew);
}
}
if(_destination != BURN_ADDRESS) {
uint256 destinationNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_destination];
uint256 destinationNumberOfVotingCheckpointsOriginal = (destinationNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][destinationNumberOfVotingCheckpoints.sub(1)].votes : 0;
uint256 destinationNumberOfVotingCheckpointsNew = destinationNumberOfVotingCheckpointsOriginal.add(_amount);
_writeVotingCheckpoint(_destination, destinationNumberOfVotingCheckpoints, destinationNumberOfVotingCheckpointsOriginal, destinationNumberOfVotingCheckpointsNew);
}
}
return true;
}
/**
* @dev Writes voting checkpoint for a given voting delegate
* @param _votingDelegate exercising votes
* @param _numberOfVotingCheckpoints number of voting checkpoints for current vote
* @param _oldVotes previous number of votes
* @param _newVotes new number of votes
* Public function for writing voting checkpoint
* Requires ROLE_TEST
*/
function writeVotingCheckpoint(
address _votingDelegate,
uint256 _numberOfVotingCheckpoints,
uint256 _oldVotes,
uint256 _newVotes) public {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
_writeVotingCheckpoint(_votingDelegate, _numberOfVotingCheckpoints, _oldVotes, _newVotes);
}
/**
* @dev Writes voting checkpoint for a given voting delegate
* @param _votingDelegate exercising votes
* @param _numberOfVotingCheckpoints number of voting checkpoints for current vote
* @param _oldVotes previous number of votes
* @param _newVotes new number of votes
* Private function for writing voting checkpoint
*/
function _writeVotingCheckpoint(
address _votingDelegate,
uint256 _numberOfVotingCheckpoints,
uint256 _oldVotes,
uint256 _newVotes) internal {
if(_numberOfVotingCheckpoints > 0 && m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints.sub(1)].from == block.number) {
m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints-1].votes = _newVotes;
}
else {
m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints] = VotingCheckpoint(block.number, _newVotes);
_numberOfVotingCheckpoints = _numberOfVotingCheckpoints.add(1);
}
emit VoteBalanceChanged(_votingDelegate, _oldVotes, _newVotes);
}
/**
* @dev Calculate account votes as of a specific block
* @param _account address whose votes are counted
* @param _blockNumber from which votes are being counted
* @return number of votes counted
*/
function getVoteCountAtBlock(
address _account,
uint256 _blockNumber) public view returns (uint256) {
uint256 voteCount = 0;
if(_blockNumber < block.number) {
if(m_accountVotingCheckpoints[_account] != 0) {
if(m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].from <= _blockNumber) {
voteCount = m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].votes;
}
else if(m_votingCheckpoints[_account][0].from > _blockNumber) {
voteCount = 0;
}
else {
uint256 lower = 0;
uint256 upper = m_accountVotingCheckpoints[_account].sub(1);
while(upper > lower) {
uint256 center = upper.sub((upper.sub(lower).div(2)));
VotingCheckpoint memory votingCheckpoint = m_votingCheckpoints[_account][center];
if(votingCheckpoint.from == _blockNumber) {
voteCount = votingCheckpoint.votes;
break;
}
else if(votingCheckpoint.from < _blockNumber) {
lower = center;
}
else {
upper = center.sub(1);
}
}
}
}
}
return voteCount;
}
/**
* @dev Vote Delegation Functions
* @param _to address where message sender is assigning votes
* @return success of message sender delegating vote
* delegate function does not allow assignment to burn
*/
function delegateVote(address _to) public returns (bool) {
return _delegateVote(_msgSender(), _to);
}
/**
* @dev Delegate votes from token holder to another address
* @param _from Token holder
* @param _toDelegate Address that will be delegated to for purpose of voting
* @return success as to whether delegation has been a success
*/
function _delegateVote(
address _from,
address _toDelegate) internal returns (bool) {
bool retval = false;
if(_toDelegate != BURN_ADDRESS) {
address currentDelegate = m_delegatedAccounts[_from];
uint256 fromAccountBalance = m_balances[_from].add(_calculateLockedVotableBalance(_from));
address oldToDelegate = m_delegatedAccounts[_from];
m_delegatedAccounts[_from] = _toDelegate;
m_delegatedAccountsInverseMap[oldToDelegate].remove(_from);
if(_from != _toDelegate){
m_delegatedAccountsInverseMap[_toDelegate].add(_from);
}
retval = true;
retval = retval && _moveVotingDelegates(currentDelegate, _toDelegate, fromAccountBalance);
if(retval) {
if(_from == _toDelegate){
emit VotingDelegateRemoved(_from);
}
else{
emit VotingDelegateChanged(_from, currentDelegate, _toDelegate);
}
}
}
return retval;
}
/**
* @dev Revert voting delegate control to owner account
* @param _account The account that has delegated its vote
* @return success of reverting delegation to owner
*/
function _revertVotingDelegationToOwner(address _account) internal returns (bool) {
return _delegateVote(_account, _account);
}
/**
* @dev Used by an message sending account to recall its voting delegates
* @return success of reverting delegation to owner
*/
function recallVotingDelegate() public returns (bool) {
return _revertVotingDelegationToOwner(_msgSender());
}
/**
* @dev Retrieve the voting delegate for a specified account
* @param _account The account that has delegated its vote
*/
function getVotingDelegate(address _account) public view returns (address) {
return m_delegatedAccounts[_account];
}
/**
* EIP-712 related functions
*/
/**
* @dev EIP-712 Ethereum Typed Structured Data Hashing and Signing for Allocation Permit
* @param _owner address of token owner
* @param _spender address of designated spender
* @param _value value permitted for spend
* @param _deadline expiration of signature
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
*/
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _ecv,
bytes32 _ecr,
bytes32 _ecs
) external returns (bool) {
require(block.timestamp <= _deadline, "UPGT_ERROR: wrong timestamp");
require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
EIP712DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, m_nonces[_owner]++, _deadline))
)
);
require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user");
require(_owner != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
return _approveUNN(_owner, _spender, _value);
}
/**
* @dev EIP-712 ETH Typed Structured Data Hashing and Signing for Delegate Vote
* @param _owner address of token owner
* @param _delegate address of voting delegate
* @param _expiretimestamp expiration of delegation signature
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @ @return bool true or false depedening on whether vote was successfully delegated
*/
function delegateVoteBySignature(
address _owner,
address _delegate,
uint256 _expiretimestamp,
uint8 _ecv,
bytes32 _ecr,
bytes32 _ecs
) external returns (bool) {
require(block.timestamp <= _expiretimestamp, "UPGT_ERROR: wrong timestamp");
require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
EIP712DOMAIN_SEPARATOR,
_hash(VotingDelegate(
{
owner : _owner,
delegate : _delegate,
nonce : m_nonces[_owner]++,
expirationTime : _expiretimestamp
})
)
)
);
require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user");
require(_owner!= BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
return _delegateVote(_owner, _delegate);
}
/**
* @dev Public hash EIP712Domain struct for EIP-712
* @param _eip712Domain EIP712Domain struct
* @return bytes32 hash of _eip712Domain
* Requires ROLE_TEST
*/
function hashEIP712Domain(EIP712Domain memory _eip712Domain) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_eip712Domain);
}
/**
* @dev Hash Delegate struct for EIP-712
* @param _delegate VotingDelegate struct
* @return bytes32 hash of _delegate
* Requires ROLE_TEST
*/
function hashDelegate(VotingDelegate memory _delegate) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_delegate);
}
/**
* @dev Public hash Permit struct for EIP-712
* @param _permit Permit struct
* @return bytes32 hash of _permit
* Requires ROLE_TEST
*/
function hashPermit(Permit memory _permit) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_permit);
}
/**
* @param _digest signed, hashed message
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @return address of the validated signer
* based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function
* Requires ROLE_TEST
*/
function recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) public view returns (address) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _recoverSigner(_digest, _ecv, _ecr, _ecs);
}
/**
* @dev Private hash EIP712Domain struct for EIP-712
* @param _eip712Domain EIP712Domain struct
* @return bytes32 hash of _eip712Domain
*/
function _hash(EIP712Domain memory _eip712Domain) internal pure returns (bytes32) {
return keccak256(
abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(_eip712Domain.name)),
keccak256(bytes(_eip712Domain.version)),
_eip712Domain.chainId,
_eip712Domain.verifyingContract,
_eip712Domain.salt
)
);
}
/**
* @dev Private hash Delegate struct for EIP-712
* @param _delegate VotingDelegate struct
* @return bytes32 hash of _delegate
*/
function _hash(VotingDelegate memory _delegate) internal pure returns (bytes32) {
return keccak256(
abi.encode(
DELEGATE_TYPEHASH,
_delegate.owner,
_delegate.delegate,
_delegate.nonce,
_delegate.expirationTime
)
);
}
/**
* @dev Private hash Permit struct for EIP-712
* @param _permit Permit struct
* @return bytes32 hash of _permit
*/
function _hash(Permit memory _permit) internal pure returns (bytes32) {
return keccak256(abi.encode(
PERMIT_TYPEHASH,
_permit.owner,
_permit.spender,
_permit.value,
_permit.nonce,
_permit.deadline
));
}
/**
* @dev Recover signer information from provided digest
* @param _digest signed, hashed message
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @return address of the validated signer
* based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function
*/
function _recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if(uint256(_ecs) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if(_ecv != 27 && _ecv != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(_digest, _ecv, _ecr, _ecs);
require(signer != BURN_ADDRESS, "ECDSA: invalid signature");
return signer;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../Interfaces/EIP20Interface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title SafeEIP20
* @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.
* This is a forked version of Openzeppelin's SafeERC20 contract but supporting
* EIP20Interface instead of Openzeppelin's IERC20
* 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 SafeEIP20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(EIP20Interface token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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 experimental ABIEncoderV2;
import "./PriceOracle.sol";
import "./MoartrollerInterface.sol";
pragma solidity ^0.6.12;
interface LiquidationModelInterface {
function liquidateCalculateSeizeUserTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint);
function liquidateCalculateSeizeTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint);
struct LiquidateCalculateSeizeUserTokensArgumentsSet {
PriceOracle oracle;
MoartrollerInterface moartroller;
address mTokenBorrowed;
address mTokenCollateral;
uint actualRepayAmount;
address accountForLiquidation;
uint liquidationIncentiveMantissa;
}
}
// 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: BSD-3-Clause
pragma solidity ^0.6.12;
/**
* @title MOAR's InterestRateModel Interface
* @author MOAR
*/
interface InterestRateModelInterface {
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC721Upgradeable.sol";
import "./IERC721MetadataUpgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "../../introspection/ERC165Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/EnumerableSetUpgradeable.sol";
import "../../utils/EnumerableMapUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable 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 => EnumerableSetUpgradeable.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMapUpgradeable.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.
*/
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_;
// 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 = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721Upgradeable.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 = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.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(ERC721Upgradeable.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(
IERC721ReceiverUpgradeable(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(ERC721Upgradeable.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 { }
uint256[41] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
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 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.12;
interface CopMappingInterface {
function getTokenAddress() external view returns (address);
function getProtectionData(uint256 underlyingTokenId) external view returns (address, uint256, uint256, uint256, uint, uint);
function getUnderlyingAsset(uint256 underlyingTokenId) external view returns (address);
function getUnderlyingAmount(uint256 underlyingTokenId) external view returns (uint256);
function getUnderlyingStrikePrice(uint256 underlyingTokenId) external view returns (uint);
function getUnderlyingDeadline(uint256 underlyingTokenId) external view returns (uint);
}
// 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.2 <0.8.0;
import "../../introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <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
pragma solidity >=0.6.2 <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
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface 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
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
/*
* 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;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// 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;
}
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
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;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMapUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/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";
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @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: BSD-3-Clause
pragma solidity ^0.6.12;
import "./MToken.sol";
import "./Interfaces/MErc20Interface.sol";
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Utils/SafeEIP20.sol";
/**
* @title MOAR's MErc20 Contract
* @notice MTokens which wrap an EIP-20 underlying
*/
contract MErc20 is MToken, MErc20Interface {
using SafeEIP20 for EIP20Interface;
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param moartroller_ The address of the Moartroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function init(address underlying_,
Moartroller moartroller_,
AbstractInterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// MToken initialize does the bulk of the work
super.init(moartroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives mTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external override returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems mTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of mTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external override returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems mTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external override returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external override returns (uint) {
return borrowInternal(borrowAmount);
}
function borrowFor(address payable borrower, uint borrowAmount) external override returns (uint) {
return borrowForInternal(borrower, borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external override returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower.
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external override returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external override returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, mTokenCollateral);
return err;
}
/**
* @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
* @param token The address of the ERC-20 token to sweep
*/
function sweepToken(EIP20Interface token) override external {
require(address(token) != underlying, "MErc20::sweepToken: can not sweep underlying token");
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(admin, balance);
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external override returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal override view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*`
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal override returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
uint balanceBefore = token.balanceOf(address(this));
token.safeTransferFrom(from, address(this), amount);
// Calculate the amount that was *actually* transferred
uint balanceAfter = token.balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal override {
EIP20Interface token = EIP20Interface(underlying);
token.safeTransfer(to, amount);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
interface MErc20Interface {
/*** User contract ***/
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 borrowFor(address payable borrower, 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, MToken mTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
|
Transfers collateral tokens (this market) to the liquidator. Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another MToken. Its absolutely critical to use msg.sender as the seizer mToken and not a parameter. seizerToken The contract seizing the collateral (i.e. borrowed mToken) liquidator The account receiving seized collateral borrower The account having collateral seized seizeTokens The number of mTokens to seize return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Fail if seize not allowed / Fail if borrower = liquidator /
|
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
uint allowed = moartroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, allowed);
}
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
accountTokens[liquidator] = liquidatorTokensNew;
return uint(Error.NO_ERROR);
}
| 11,818,093 |
./full_match/1/0xFb8F626AD693ad0AF769ddB265084E8973f63a3C/sources/contracts/BlockHistory.sol
|
Parses a merkle inclusion proof from the bytes proof the encoded merkle inclusion proof return result the array of proof hashes/ solidity doesn't support getting calldata outputs from abi.decode but we can decode it; calldata arrays are just (offset,length)
|
function parseMerkleProof(bytes calldata proof)
internal
pure
returns (bytes32[] calldata result)
{
require(proof.length % 32 == 0);
require(proof.length >= 32);
assembly {
result.offset := add(proof.offset, 0x20)
result.length := calldataload(proof.offset)
}
}
| 4,930,395 |
./full_match/4/0xc70D7E1432449a14A7A7aC88B43ddDFdE7B305E6/sources/browser/MolVault_v2.sol
|
Deposit NFT Set sale status
|
function deposit(
address _tokenAddress,
uint256 _tokenId,
uint256 _ethPrice,
uint256 _tokenPrice,
uint8 _forSale)
public onlyWhitelisted {
require(IERC721(_tokenAddress).ownerOf(_tokenId) == msg.sender, "!owner");
bytes memory tokenKey = getTokenKey(_tokenAddress, _tokenId);
NFTs[tokenKey] = true;
IERC721(_tokenAddress).transferFrom(msg.sender, vault, _tokenId);
sale[tokenKey].ethPrice = _ethPrice;
sale[tokenKey].tokenPrice = _tokenPrice;
sale[tokenKey].forSale = _forSale;
}
| 701,603 |
./partial_match/1/0x323a60675142021Adc78B147C72D479de923f4a5/sources/JWCToken.sol
|
Get token exchange rate Note: just use when ICO/
|
function getTokenExchangeRate() public constant returns(uint256 rate) {
rate = tokenExchangeRate;
if(now<phasePresale_To){
if(now>=phasePresale_From)
rate = 10000;
rate = 7000;
}
} else if(now<phasePublicSale3_To){
}
| 2,581,004 |
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @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];
}
}
/**
* @title Partial Basic
* @dev Partial Basic is an experimental cryptocurrency that guarantees
* unconditional, indeterminate rewards to network participants.
*/
contract PartialBasic is StandardToken {
using SafeMath for uint256;
string public constant name = "Partial Basic"; // solium-disable-line uppercase
string public constant symbol = "PB"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
uint256 public constant BASE_REWARD = 20000 ether;
uint256 private constant PRECISION = 10**18;
uint256 public totalNodes;
uint256 public rewardStartTime;
uint256 public rewardCheckpoint;
uint256 private rewardTimestamp;
mapping(address => uint256) public nodes;
mapping(address => uint256) private claimed;
event Mint(address indexed to, uint256 amount);
event AddNode(address indexed owner);
/**
* @dev add a node for a specified address.
* @param _owner The address to add a node for.
*/
function addNode(address _owner) external {
uint256 checkpointCandidate;
if (rewardStartTime == 0) {
// initialise rewards
rewardStartTime = block.timestamp;
} else {
// reward per node must increase to be a valid checkpoint
// or a valid reward for this block must have already been checkpointed
checkpointCandidate = rewardPerNode();
require(checkpointCandidate > rewardCheckpoint || block.timestamp == rewardTimestamp);
}
// claim outstanding rewards
sync(_owner);
if (rewardCheckpoint != checkpointCandidate) {
// checkpoint the total reward per node
rewardCheckpoint = checkpointCandidate;
}
if (rewardTimestamp != block.timestamp) {
// reset the timestamp for the reward
rewardTimestamp = block.timestamp;
}
// add node for address
nodes[_owner] = nodes[_owner].add(1);
// prevent new nodes from claiming old rewards
claimed[_owner] = rewardCheckpoint.mul(nodes[_owner]);
// update the total nodes in the network
totalNodes = totalNodes.add(1);
// fire event
emit AddNode(_owner);
}
/**
* @dev Gets the total reward for a node.
* @return A uint256 representing the total reward of a node.
*/
function rewardPerNode() public view returns (uint256) {
// no reward if there are no active nodes
if (totalNodes == 0) {
return;
}
// days since last checkpoint
uint256 totalDays = block.timestamp.sub(rewardTimestamp).mul(PRECISION).div(1 days);
// reward * days / nodes
uint256 newReward = BASE_REWARD.mul(totalDays).div(PRECISION).div(totalNodes);
// checkpoint + newReward
return rewardCheckpoint.add(newReward);
}
/**
* @dev Gets the outstanding reward of a specified address.
* @param _owner The address to query the reward of.
* @return A uint256 representing the outstanding reward of the passed address.
*/
function calculateReward(address _owner) public view returns (uint256) {
// address must be running a node
if (isMining(_owner)) {
// return outstanding reward
uint256 reward = rewardPerNode().mul(nodes[_owner]);
return reward.sub(claimed[_owner]);
}
}
/**
* @dev sync an outstanding reward for a specified address.
* @param _owner The address to sync rewards for.
*/
function sync(address _owner) public {
uint256 reward = calculateReward(_owner);
if (reward > 0) {
claimed[_owner] = claimed[_owner].add(reward);
balances[_owner] = balances[_owner].add(reward);
emit Mint(_owner, reward);
emit Transfer(address(0), _owner, reward);
}
}
/**
* @dev transfer token for a specified address.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
sync(msg.sender);
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param _from address The address which you want to send tokens from.
* @param _to address The address which you want to transfer to.
* @param _value uint256 the amount of tokens to be transferred.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
sync(_from);
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the 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].add(calculateReward(_owner));
}
/**
* @dev returns the approximate total number of tokens in existence
* @return A uint256 representing the approximate total number of tokens in existence.
*/
function totalSupply() public view returns (uint256) {
if (rewardStartTime == 0) {
return;
}
// days since start of rewards
uint256 totalDays = block.timestamp.sub(rewardStartTime).mul(PRECISION).div(1 days);
// reward * days
return BASE_REWARD.mul(totalDays).div(PRECISION);
}
/**
* @dev returns the mining status of the passed address.
* @return A uint256 representing the mining status of the passed address.
*/
function isMining(address _owner) public view returns (bool) {
return nodes[_owner] != 0;
}
/**
* @dev A batch query to get all node information for a specified address.
* @param _owner The address to query the details of.
* @return A bool representing the mining status of the passed address.
* @return A uint256 representing the number of nodes owned by the passed address.
* @return A uint256 representing the amount owned by the passed address.
* @return A uint256 representing the outstanding reward of the passed address.
* @return A uint256 representing the total reward per node.
* @return A uint256 representing the total nodes in the network.
* @return A uint256 representing the total number of tokens in existence.
*/
function getInfo(address _owner) public view returns (bool, uint256, uint256, uint256, uint256, uint256, uint256) {
return (isMining(_owner), nodes[_owner], balanceOf(_owner), calculateReward(_owner), rewardPerNode(), totalNodes, totalSupply());
}
}
|
Gets the balance of the specified address. _owner The address to query the 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].add(calculateReward(_owner));
}
| 13,740,169 |
./partial_match/4/0x4a6948a622C2B4DB9aee84B35c3bEC8F64442956/sources/MyDefiProject.sol
|
Solidity can't return string arrays. So we'll have to provide the _dataIndex Of the piece of data we want
|
function getUserData(uint256 _id, uint256 _dataIndex) public view returns (string memory) {
return users[_id].data[_dataIndex];
}
| 8,508,630 |
./full_match/43114/0xff164Ede3E7C375E8764E9e3a22D3E35F780EEBC/sources/home/pedro/Documents/projects/avalabs/party-swap/party-swap-periphery/contracts/PartyRouter.sol
|
refund dust eth, if any
|
function swapAVAXForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) {
require(path[0] == WAVAX, 'PartyRouter: INVALID_PATH');
amounts = PartyLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'PartyRouter: EXCESSIVE_INPUT_AMOUNT');
assert(IWAVAX(WAVAX).transfer(PartyLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
if (msg.value > amounts[0]) TransferHelper.safeTransferAVAX(msg.sender, msg.value - amounts[0]);
}
| 4,528,070 |
./full_match/1/0x4D654112663ea69d6f836f67EEB4BEd3793e5605/sources/browser/FrenchWineToken.sol
|
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair 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), "FWINE::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "FWINE::delegateBySig: invalid nonce");
require(now <= expiry, "FWINE::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 9,744,205 |
/**
*Submitted for verification at Etherscan.io on 2021-03-22
*/
// 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);
}
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library SafeERC20 {
function _safeApprove(IERC20 token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), '!TransferHelper: APPROVE_FAILED');
}
function safeApprove(IERC20 token, address to, uint value) internal {
if (value > 0) _safeApprove(token, to, 0);
return _safeApprove(token, to, value);
}
function safeTransfer(IERC20 token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), '!TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), '!TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, '!TransferHelper: ETH_TRANSFER_FAILED');
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IMintERC20 {
/**
* @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);
function mint(address recipient, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address sender, uint256 amount) external;
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
*Submitted for verification at Etherscan.io on 2021-01-14
*/
pragma solidity >=0.6.0 <0.8.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 <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.
*/
contract Context 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.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
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.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
pragma solidity ^0.7.0;
interface IWETHelper {
function withdraw(uint) external;
}
contract WETHelper {
receive() external payable {
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, '!WETHelper: ETH_TRANSFER_FAILED');
}
function withdraw(address _eth, address _to, uint256 _amount) public {
IWETHelper(_eth).withdraw(_amount);
safeTransferETH(_to, _amount);
}
}
pragma solidity ^0.7.0;
interface IUniswapV2Router02Api {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
library UniTools {
function swapExactTokensForTokens(
address _uniRouter,
address _fromToken,
address _toToken,
uint256 _amount) internal returns (uint256) {
if (_fromToken == _toToken || _amount == 0) return _amount;
address[] memory path = new address[](2);
path[0] = _fromToken;
path[1] = _toToken;
uint[] memory amount = IUniswapV2Router02Api(_uniRouter).swapExactTokensForTokens(
_amount, 0, path, address(this), 0xffffffff);
return amount[amount.length - 1];
}
function swapExactTokensForTokens(
address _fromToken,
address _toToken,
uint256 _amount) internal returns (uint256) {
return swapExactTokensForTokens(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, _fromToken, _toToken, _amount);
}
function swapExactTokensForTokens3(
address _uniRouter,
address _fromToken,
address _midToken,
address _toToken,
uint256 _amount) internal returns (uint256) {
address[] memory path;
if (_midToken == address(0)) {
path = new address[](2);
path[0] = _fromToken;
path[1] = _toToken;
} else {
path = new address[](3);
path[0] = _fromToken;
path[1] = _midToken;
path[2] = _toToken;
}
uint[] memory amount = IUniswapV2Router02Api(_uniRouter).swapExactTokensForTokens(
_amount, 0, path, address(this), 0xffffffff);
return amount[amount.length - 1];
}
function swapExactTokensForTokens3(
address _fromToken,
address _midToken,
address _toToken,
uint256 _amount) internal returns (uint256) {
return swapExactTokensForTokens3(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, _fromToken, _midToken, _toToken, _amount);
}
}
pragma solidity 0.7.6;
interface IMigratorChef {
// Perform LP token migration from legacy UniswapV2 to SushiSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for IMintERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 lpAmount; // Single token, swap to LP token.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 buybackRatio; // Buyback ratio, 0 means no ratio. 5 means 0.5%
uint256 poolType; // Pool type
uint256 amount; // User deposit amount
uint256 lpAmount; // ETH/Token convert to uniswap liq amount
address routerv2; // RouterV2
address moneyToken; // Money Token, USDT, BUSD, ETH, BNB, BTC
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// Pool type.
uint256 internal constant POOL_THISLPTOKEN = 0;
uint256 internal constant POOL_TOKEN = 1;
uint256 internal constant POOL_LPTOKEN = 2;
uint256 internal constant POOL_SLPTOKEN = 3;
uint256 internal constant POOL_SLPLPTOKEN = 4;
uint256 internal constant POOL_UNSUPPORT = 5;
// ETH Mainnet
address public constant UNIV2ROUTER2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant SLPV2ROUTER2 = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// The SUSHI TOKEN!
IMintERC20 public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
// Treasury address;
address public treasury;
uint256 public mintReward;
address public pairaddr;
// ETH Helper for the transfer, stateless.
WETHelper public wethelper;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, uint256 buybackAmount, uint256 liquidity);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, uint256 buybackAmount, uint256 liquidity);
event Mint(address indexed to, uint256 amount, uint256 devamount);
function initialize(
IMintERC20 _sushi,
address _devaddr,
address _treasury,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public initializer {
Ownable.__Ownable_init();
sushi = _sushi;
devaddr = _devaddr;
treasury = _treasury;
sushiPerBlock = _sushiPerBlock;
startBlock = _startBlock;
bonusEndBlock = _bonusEndBlock;
wethelper = new WETHelper();
}
receive() external payable {
assert(msg.sender == WETH);
}
function setPair(address _pairaddr) public onlyOwner {
pairaddr = _pairaddr;
IERC20(pairaddr).safeApprove(UNIV2ROUTER2, uint(-1));
IERC20(WETH).safeApprove(UNIV2ROUTER2, uint(-1));
IERC20(address(sushi)).safeApprove(UNIV2ROUTER2, uint(-1));
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IERC20 _lpToken, address _moneyToken, bool _withUpdate, uint256 _buybackRatio, uint256 _type) public {
require(msg.sender == owner() || msg.sender == devaddr, "!dev addr");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
address routerv2 = UNIV2ROUTER2;
if (_type == POOL_SLPTOKEN || _type == POOL_SLPLPTOKEN) {
routerv2 = SLPV2ROUTER2;
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
buybackRatio: _buybackRatio,
poolType: _type,
amount: 0,
lpAmount: 0,
routerv2: routerv2,
moneyToken: _moneyToken,
lastRewardBlock: lastRewardBlock,
accSushiPerShare: 0
}));
_lpToken.safeApprove(UNIV2ROUTER2, uint(-1));
_lpToken.safeApprove(SLPV2ROUTER2, uint(-1));
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate, uint256 _buybackRatio) public {
require(msg.sender == owner() || msg.sender == devaddr, "!dev addr");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].buybackRatio = _buybackRatio;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.amount;
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.amount;
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
mint(devaddr, sushiReward, sushiReward.div(100));
mintReward.add(sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public payable {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 buybackAmount;
uint256 liquidity;
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeSushiTransfer(msg.sender, pending);
}
}
if (msg.value > 0) {
IWETH(WETH).deposit{value: msg.value}();
}
if (address(pool.lpToken) == WETH) {
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
if (msg.value > 0) {
_amount = _amount.add(msg.value);
}
} else if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
if(_amount > 0) {
buybackAmount = _amount.mul(pool.buybackRatio).div(1000);
if (pool.buybackRatio > 0 && buybackAmount == 0) {
buybackAmount = _amount;
}
pool.lpToken.safeTransfer(treasury, buybackAmount);
_amount = _amount.sub(buybackAmount);
if (pool.poolType == POOL_TOKEN || pool.poolType == POOL_SLPTOKEN) {
liquidity = tokenToLp(pool.routerv2, pool.lpToken, pool.moneyToken, _amount);
user.lpAmount = user.lpAmount.add(liquidity);
pool.lpAmount = pool.lpAmount.add(liquidity);
}
pool.amount = pool.amount.add(_amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount, buybackAmount, liquidity);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeSushiTransfer(msg.sender, pending);
}
uint256 buybackAmount;
uint256 liquidity;
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.amount = pool.amount.sub(_amount);
if (pool.poolType == POOL_TOKEN || pool.poolType == POOL_SLPTOKEN) {
liquidity = user.lpAmount.mul(_amount).div(user.amount.add(_amount));
uint256 amount2 = lpToToken(pool.routerv2, pool.lpToken, pool.moneyToken, liquidity);
if (amount2 < _amount) _amount = amount2;
user.lpAmount = user.lpAmount.sub(liquidity);
pool.lpAmount = pool.lpAmount.sub(liquidity);
}
buybackAmount = _amount.mul(pool.buybackRatio).div(1000);
if (pool.buybackRatio > 0 && buybackAmount == 0) {
buybackAmount = _amount;
}
pool.lpToken.safeTransfer(treasury, buybackAmount);
_amount = _amount.sub(buybackAmount);
if (address(pool.lpToken) == WETH) {
withdrawEth(address(msg.sender), _amount, false);
} else {
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
}
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount, buybackAmount, liquidity);
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
// Update Treasury contract address;
function setTreasury(address _treasury) public {
require(msg.sender == owner() || msg.sender == devaddr, "!dev addr");
treasury = _treasury;
}
function tokenToLp(address _uniRouter, IERC20 _token, address _moneyToken, uint256 _amount) internal returns (uint256 liq) {
if (_amount == 0) return 0;
if (address(_token) != WETH) {
_amount = UniTools.swapExactTokensForTokens3(_uniRouter, address(_token), _moneyToken, WETH, _amount);
}
uint256 amountBuy = _amount.mul(5025).div(10000);
uint256 amountEth = _amount.sub(amountBuy);
uint256 amountToken = UniTools.swapExactTokensForTokens(WETH, address(sushi), amountEth);
(,, liq) = IUniswapV2Router02(UNIV2ROUTER2).addLiquidity(
WETH, address(sushi), amountEth, amountToken, 0, 0, address(this), 0xffffffff);
}
function lpToToken(address _uniRouter, IERC20 _token, address _moneyToken, uint256 _liquidity) internal returns (uint256 amountAsset){
if (_liquidity == 0) return 0;
(uint256 amountToken, uint256 amountEth) = IUniswapV2Router02(UNIV2ROUTER2).removeLiquidity(
address(sushi), WETH, _liquidity, 0, 0, address(this), 0xffffffff);
amountEth = amountEth.add(UniTools.swapExactTokensForTokens(address(sushi), WETH, amountToken));
if (address(_token) == WETH) {
amountAsset = amountEth;
} else {
amountAsset = UniTools.swapExactTokensForTokens3(_uniRouter, WETH, _moneyToken, address(_token), amountEth);
}
}
function withdrawEth(address _to, uint256 _amount, bool _isWeth) internal {
if (_isWeth) {
IERC20(WETH).safeTransfer(_to, _amount);
} else {
IERC20(WETH).safeTransfer(address(wethelper), _amount);
wethelper.withdraw(WETH, _to, _amount);
}
}
function mint(address devto, uint256 rewardAmount, uint256 devRewardAmount) internal {
if (rewardAmount == 0) {
emit Mint(devto, 0, 0);
return;
}
require(sushi.transfer(devto, devRewardAmount), '!sushi transfer of pool failed');
emit Mint(devto, rewardAmount, devRewardAmount);
}
}
|
Add a new lp to the pool. Can only be called by the owner.
|
function add(uint256 _allocPoint, IERC20 _lpToken, address _moneyToken, bool _withUpdate, uint256 _buybackRatio, uint256 _type) public {
require(msg.sender == owner() || msg.sender == devaddr, "!dev addr");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
address routerv2 = UNIV2ROUTER2;
if (_type == POOL_SLPTOKEN || _type == POOL_SLPLPTOKEN) {
routerv2 = SLPV2ROUTER2;
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
buybackRatio: _buybackRatio,
poolType: _type,
amount: 0,
lpAmount: 0,
routerv2: routerv2,
moneyToken: _moneyToken,
lastRewardBlock: lastRewardBlock,
accSushiPerShare: 0
}));
_lpToken.safeApprove(UNIV2ROUTER2, uint(-1));
_lpToken.safeApprove(SLPV2ROUTER2, uint(-1));
}
| 6,515,646 |
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol
// Added public isInitialized() view of private initialized bool.
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
/**
* @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;
}
/**
* @dev Return true if and only if the contract has been initialized
* @return whether the contract has been initialized
*/
function isInitialized() public view returns (bool) {
return initialized;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
interface IPoolFactory {
function isPool(address pool) external view returns (bool);
}
// SPDX-License-Identifier: MIT
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) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
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);
}
// SPDX-License-Identifier: MIT
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {Address} from "Address.sol";
import {Context} from "Context.sol";
import {IERC20} from "IERC20.sol";
import {SafeMath} from "SafeMath.sol";
import {Initializable} from "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 ERC20 is Initializable, Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_initialize(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public virtual view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public virtual override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function updateNameAndSymbol(string memory __name, string memory __symbol) internal {
_name = __name;
_symbol = __symbol;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {ITrueFiPool2} from "ITrueFiPool2.sol";
interface ITrueLender2 {
// @dev calculate overall value of the pools
function value(ITrueFiPool2 pool) external view returns (uint256);
// @dev distribute a basket of tokens for exiting user
function distribute(
address recipient,
uint256 numerator,
uint256 denominator
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IERC20} from "IERC20.sol";
interface IERC20WithDecimals is IERC20 {
function decimals() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IERC20WithDecimals} from "IERC20WithDecimals.sol";
/**
* @dev Oracle that converts any token to and from TRU
* Used for liquidations and valuing of liquidated TRU in the pool
*/
interface ITrueFiPoolOracle {
// token address
function token() external view returns (IERC20WithDecimals);
// amount of tokens 1 TRU is worth
function truToToken(uint256 truAmount) external view returns (uint256);
// amount of TRU 1 token is worth
function tokenToTru(uint256 tokenAmount) external view returns (uint256);
// USD price of token with 18 decimals
function tokenToUsd(uint256 tokenAmount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
interface I1Inch3 {
struct SwapDescription {
address srcToken;
address dstToken;
address srcReceiver;
address dstReceiver;
uint256 amount;
uint256 minReturnAmount;
uint256 flags;
bytes permit;
}
function swap(
address caller,
SwapDescription calldata desc,
bytes calldata data
)
external
returns (
uint256 returnAmount,
uint256 gasLeft,
uint256 chiSpent
);
function unoswap(
address srcToken,
uint256 amount,
uint256 minReturn,
bytes32[] calldata /* pools */
) external payable returns (uint256 returnAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {ERC20, IERC20} from "UpgradeableERC20.sol";
import {ITrueLender2} from "ITrueLender2.sol";
import {ITrueFiPoolOracle} from "ITrueFiPoolOracle.sol";
import {I1Inch3} from "I1Inch3.sol";
interface ITrueFiPool2 is IERC20 {
function initialize(
ERC20 _token,
ERC20 _stakingToken,
ITrueLender2 _lender,
I1Inch3 __1Inch,
address __owner
) external;
function token() external view returns (ERC20);
function oracle() external view returns (ITrueFiPoolOracle);
/**
* @dev Join the pool by depositing tokens
* @param amount amount of tokens to deposit
*/
function join(uint256 amount) external;
/**
* @dev borrow from pool
* 1. Transfer TUSD to sender
* 2. Only lending pool should be allowed to call this
*/
function borrow(uint256 amount) external;
/**
* @dev pay borrowed money back to pool
* 1. Transfer TUSD from sender
* 2. Only lending pool should be allowed to call this
*/
function repay(uint256 currencyAmount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {ITrueFiPool2} from "ITrueFiPool2.sol";
interface ILoanFactory2 {
function createLoanToken(
ITrueFiPool2 _pool,
uint256 _amount,
uint256 _term,
uint256 _apy
) external;
function isLoanToken(address) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "Context.sol";
import "IERC20.sol";
import "SafeMath.sol";
import "Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {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;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "IERC20.sol";
import "SafeMath.sol";
import "Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using 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.10;
import {IERC20} from "IERC20.sol";
import {ITrueFiPool2} from "ITrueFiPool2.sol";
interface ILoanToken2 is IERC20 {
enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated}
function borrower() external view returns (address);
function amount() external view returns (uint256);
function term() external view returns (uint256);
function apy() external view returns (uint256);
function start() external view returns (uint256);
function lender() external view returns (address);
function debt() external view returns (uint256);
function pool() external view returns (ITrueFiPool2);
function profit() external view returns (uint256);
function status() external view returns (Status);
function getParameters()
external
view
returns (
uint256,
uint256,
uint256
);
function fund() external;
function withdraw(address _beneficiary) external;
function settle() external;
function enterDefault() external;
function liquidate() external;
function redeem(uint256 _amount) external;
function repay(address _sender, uint256 _amount) external;
function repayInFull(address _sender) external;
function reclaim() external;
function allowTransfer(address account, bool _status) external;
function repaid() external view returns (uint256);
function isRepaid() external view returns (bool);
function balance() external view returns (uint256);
function value(uint256 _balance) external view returns (uint256);
function token() external view returns (IERC20);
function version() external pure returns (uint8);
}
//interface IContractWithPool {
// function pool() external view returns (ITrueFiPool2);
//}
//
//// Had to be split because of multiple inheritance problem
//interface ILoanToken2 is ILoanToken, IContractWithPool {
//
//}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IERC20} from "IERC20.sol";
interface ILoanToken is IERC20 {
enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated}
function borrower() external view returns (address);
function amount() external view returns (uint256);
function term() external view returns (uint256);
function apy() external view returns (uint256);
function start() external view returns (uint256);
function lender() external view returns (address);
function debt() external view returns (uint256);
function profit() external view returns (uint256);
function status() external view returns (Status);
function borrowerFee() external view returns (uint256);
function receivedAmount() external view returns (uint256);
function isLoanToken() external pure returns (bool);
function getParameters()
external
view
returns (
uint256,
uint256,
uint256
);
function fund() external;
function withdraw(address _beneficiary) external;
function settle() external;
function enterDefault() external;
function liquidate() external;
function redeem(uint256 _amount) external;
function repay(address _sender, uint256 _amount) external;
function repayInFull(address _sender) external;
function reclaim() external;
function allowTransfer(address account, bool _status) external;
function repaid() external view returns (uint256);
function isRepaid() external view returns (bool);
function balance() external view returns (uint256);
function value(uint256 _balance) external view returns (uint256);
function currencyToken() external view returns (IERC20);
function version() external pure returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {ERC20} from "ERC20.sol";
import {IERC20} from "IERC20.sol";
import {SafeMath} from "SafeMath.sol";
import {SafeERC20} from "SafeERC20.sol";
import {ILoanToken} from "ILoanToken.sol";
/**
* @title LoanToken
* @dev A token which represents share of a debt obligation
*
* Each LoanToken has:
* - borrower address
* - borrow amount
* - loan term
* - loan APY
*
* Loan progresses through the following states:
* Awaiting: Waiting for funding to meet capital requirements
* Funded: Capital requirements met, borrower can withdraw
* Withdrawn: Borrower withdraws money, loan waiting to be repaid
* Settled: Loan has been paid back in full with interest
* Defaulted: Loan has not been paid back in full
* Liquidated: Loan has Defaulted and stakers have been Liquidated
*
* - LoanTokens are non-transferable except for whitelisted addresses
* - This version of LoanToken only supports a single funder
*/
contract LoanToken is ILoanToken, ERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint128 public constant lastMinutePaybackDuration = 1 days;
address public override borrower;
address public liquidator;
uint256 public override amount;
uint256 public override term;
uint256 public override apy;
uint256 public override start;
address public override lender;
uint256 public override debt;
uint256 public redeemed;
// borrow fee -> 25 = 0.25%
uint256 public override borrowerFee = 25;
// whitelist for transfers
mapping(address => bool) public canTransfer;
Status public override status;
IERC20 public override currencyToken;
/**
* @dev Emitted when the loan is funded
* @param lender Address which funded the loan
*/
event Funded(address lender);
/**
* @dev Emitted when transfer whitelist is updated
* @param account Account to whitelist for transfers
* @param status New whitelist status
*/
event TransferAllowanceChanged(address account, bool status);
/**
* @dev Emitted when borrower withdraws funds
* @param beneficiary Account which will receive funds
*/
event Withdrawn(address beneficiary);
/**
* @dev Emitted when loan has been fully repaid
* @param returnedAmount Amount that was returned
*/
event Settled(uint256 returnedAmount);
/**
* @dev Emitted when term is over without full repayment
* @param returnedAmount Amount that was returned before expiry
*/
event Defaulted(uint256 returnedAmount);
/**
* @dev Emitted when a LoanToken is redeemed for underlying currencyTokens
* @param receiver Receiver of currencyTokens
* @param burnedAmount Amount of LoanTokens burned
* @param redeemedAmount Amount of currencyToken received
*/
event Redeemed(address receiver, uint256 burnedAmount, uint256 redeemedAmount);
/**
* @dev Emitted when a LoanToken is repaid by the borrower in underlying currencyTokens
* @param repayer Sender of currencyTokens
* @param repaidAmount Amount of currencyToken repaid
*/
event Repaid(address repayer, uint256 repaidAmount);
/**
* @dev Emitted when borrower reclaims remaining currencyTokens
* @param borrower Receiver of remaining currencyTokens
* @param reclaimedAmount Amount of currencyTokens repaid
*/
event Reclaimed(address borrower, uint256 reclaimedAmount);
/**
* @dev Emitted when loan gets liquidated
* @param status Final loan status
*/
event Liquidated(Status status);
/**
* @dev Create a Loan
* @param _currencyToken Token to lend
* @param _borrower Borrower address
* @param _amount Borrow amount of currency tokens
* @param _term Loan length
* @param _apy Loan APY
*/
constructor(
IERC20 _currencyToken,
address _borrower,
address _lender,
address _liquidator,
uint256 _amount,
uint256 _term,
uint256 _apy
) public ERC20("Loan Token", "LOAN") {
require(_lender != address(0), "LoanToken: Lender is not set");
currencyToken = _currencyToken;
borrower = _borrower;
liquidator = _liquidator;
amount = _amount;
term = _term;
apy = _apy;
lender = _lender;
debt = interest(amount);
}
/**
* @dev Only borrower can withdraw & repay loan
*/
modifier onlyBorrower() {
require(msg.sender == borrower, "LoanToken: Caller is not the borrower");
_;
}
/**
* @dev Only liquidator can liquidate
*/
modifier onlyLiquidator() {
require(msg.sender == liquidator, "LoanToken: Caller is not the liquidator");
_;
}
/**
* @dev Only after loan has been closed: Settled, Defaulted, or Liquidated
*/
modifier onlyAfterClose() {
require(status >= Status.Settled, "LoanToken: Only after loan has been closed");
_;
}
/**
* @dev Only when loan is Funded
*/
modifier onlyOngoing() {
require(status == Status.Funded || status == Status.Withdrawn, "LoanToken: Current status should be Funded or Withdrawn");
_;
}
/**
* @dev Only when loan is Funded
*/
modifier onlyFunded() {
require(status == Status.Funded, "LoanToken: Current status should be Funded");
_;
}
/**
* @dev Only when loan is Withdrawn
*/
modifier onlyAfterWithdraw() {
require(status >= Status.Withdrawn, "LoanToken: Only after loan has been withdrawn");
_;
}
/**
* @dev Only when loan is Awaiting
*/
modifier onlyAwaiting() {
require(status == Status.Awaiting, "LoanToken: Current status should be Awaiting");
_;
}
/**
* @dev Only when loan is Defaulted
*/
modifier onlyDefaulted() {
require(status == Status.Defaulted, "LoanToken: Current status should be Defaulted");
_;
}
/**
* @dev Only whitelisted accounts or lender
*/
modifier onlyWhoCanTransfer(address sender) {
require(
sender == lender || canTransfer[sender],
"LoanToken: This can be performed only by lender or accounts allowed to transfer"
);
_;
}
/**
* @dev Only lender can perform certain actions
*/
modifier onlyLender() {
require(msg.sender == lender, "LoanToken: This can be performed only by lender");
_;
}
/**
* @dev Return true if this contract is a LoanToken
* @return True if this contract is a LoanToken
*/
function isLoanToken() external override pure returns (bool) {
return true;
}
/**
* @dev Get loan parameters
* @return amount, term, apy
*/
function getParameters()
external
override
view
returns (
uint256,
uint256,
uint256
)
{
return (amount, apy, term);
}
/**
* @dev Get coupon value of this loan token in currencyToken
* This assumes the loan will be paid back on time, with interest
* @param _balance number of LoanTokens to get value for
* @return coupon value of _balance LoanTokens in currencyTokens
*/
function value(uint256 _balance) external override view returns (uint256) {
if (_balance == 0) {
return 0;
}
uint256 passed = block.timestamp.sub(start);
if (passed > term || status == Status.Settled) {
passed = term;
}
// assume year is 365 days
uint256 interest = amount.mul(apy).mul(passed).div(365 days).div(10000);
return amount.add(interest).mul(_balance).div(debt);
}
/**
* @dev Fund a loan
* Set status, start time, lender
*/
function fund() external override onlyAwaiting onlyLender {
status = Status.Funded;
start = block.timestamp;
_mint(msg.sender, debt);
currencyToken.safeTransferFrom(msg.sender, address(this), receivedAmount());
emit Funded(msg.sender);
}
/**
* @dev Whitelist accounts to transfer
* @param account address to allow transfers for
* @param _status true allows transfers, false disables transfers
*/
function allowTransfer(address account, bool _status) external override onlyLender {
canTransfer[account] = _status;
emit TransferAllowanceChanged(account, _status);
}
/**
* @dev Borrower calls this function to withdraw funds
* Sets the status of the loan to Withdrawn
* @param _beneficiary address to send funds to
*/
function withdraw(address _beneficiary) external override onlyBorrower onlyFunded {
status = Status.Withdrawn;
currencyToken.safeTransfer(_beneficiary, receivedAmount());
emit Withdrawn(_beneficiary);
}
/**
* @dev Settle the loan after checking it has been repaid
*/
function settle() public override onlyOngoing {
require(isRepaid(), "LoanToken: loan must be repaid to settle");
status = Status.Settled;
emit Settled(_balance());
}
/**
* @dev Default the loan if it has not been repaid by the end of term
*/
function enterDefault() external override onlyOngoing {
require(!isRepaid(), "LoanToken: cannot default a repaid loan");
require(start.add(term).add(lastMinutePaybackDuration) <= block.timestamp, "LoanToken: Loan cannot be defaulted yet");
status = Status.Defaulted;
emit Defaulted(_balance());
}
/**
* @dev Liquidate the loan if it has defaulted
*/
function liquidate() external override onlyDefaulted onlyLiquidator {
status = Status.Liquidated;
emit Liquidated(status);
}
/**
* @dev Redeem LoanToken balances for underlying currencyToken
* Can only call this function after the loan is Closed
* @param _amount amount to redeem
*/
function redeem(uint256 _amount) external override onlyAfterClose {
uint256 amountToReturn = _amount.mul(_balance()).div(totalSupply());
redeemed = redeemed.add(amountToReturn);
_burn(msg.sender, _amount);
currencyToken.safeTransfer(msg.sender, amountToReturn);
emit Redeemed(msg.sender, _amount, amountToReturn);
}
/**
* @dev Function for borrower to repay the loan
* Borrower can repay at any time
* @param _sender account sending currencyToken to repay
* @param _amount amount of currencyToken to repay
*/
function repay(address _sender, uint256 _amount) external override {
_repay(_sender, _amount);
}
/**
* @dev Function for borrower to repay all of the remaining loan balance
* Borrower should use this to ensure full repayment
* @param _sender account sending currencyToken to repay
*/
function repayInFull(address _sender) external override {
_repay(_sender, debt.sub(_balance()));
}
/**
* @dev Internal function for loan repayment
* If _amount is sufficient, then this also settles the loan
* @param _sender account sending currencyToken to repay
* @param _amount amount of currencyToken to repay
*/
function _repay(address _sender, uint256 _amount) internal onlyAfterWithdraw {
require(_amount <= debt.sub(_balance()), "LoanToken: Cannot repay over the debt");
emit Repaid(_sender, _amount);
currencyToken.safeTransferFrom(_sender, address(this), _amount);
if (isRepaid()) {
settle();
}
}
/**
* @dev Function for borrower to reclaim stuck currencyToken
* Can only call this function after the loan is Closed
* and all of LoanToken holders have been burnt
*/
function reclaim() external override onlyAfterClose onlyBorrower {
require(totalSupply() == 0, "LoanToken: Cannot reclaim when LoanTokens are in circulation");
uint256 balanceRemaining = _balance();
require(balanceRemaining > 0, "LoanToken: Cannot reclaim when balance 0");
currencyToken.safeTransfer(borrower, balanceRemaining);
emit Reclaimed(borrower, balanceRemaining);
}
/**
* @dev Check how much was already repaid
* Funds stored on the contract's address plus funds already redeemed by lenders
* @return Uint256 representing what value was already repaid
*/
function repaid() external override view onlyAfterWithdraw returns (uint256) {
return _balance().add(redeemed);
}
/**
* @dev Check whether an ongoing loan has been repaid in full
* @return true if and only if this loan has been repaid
*/
function isRepaid() public override view onlyOngoing returns (bool) {
return _balance() >= debt;
}
/**
* @dev Public currency token balance function
* @return currencyToken balance of this contract
*/
function balance() external override view returns (uint256) {
return _balance();
}
/**
* @dev Get currency token balance for this contract
* @return currencyToken balance of this contract
*/
function _balance() internal view returns (uint256) {
return currencyToken.balanceOf(address(this));
}
/**
* @dev Calculate amount borrowed minus fee
* @return Amount minus fees
*/
function receivedAmount() public override view returns (uint256) {
return amount.sub(amount.mul(borrowerFee).div(10000));
}
/**
* @dev Calculate interest that will be paid by this loan for an amount (returned funds included)
* amount + ((amount * apy * term) / (365 days / precision))
* @param _amount amount
* @return uint256 Amount of interest paid for _amount
*/
function interest(uint256 _amount) internal view returns (uint256) {
return _amount.add(_amount.mul(apy).mul(term).div(365 days).div(10000));
}
/**
* @dev get profit for this loan
* @return profit for this loan
*/
function profit() external override view returns (uint256) {
return debt.sub(amount);
}
/**
* @dev Override ERC20 _transfer so only whitelisted addresses can transfer
* @param sender sender of the transaction
* @param recipient recipient of the transaction
* @param _amount amount to send
*/
function _transfer(
address sender,
address recipient,
uint256 _amount
) internal override onlyWhoCanTransfer(sender) {
return super._transfer(sender, recipient, _amount);
}
function version() external virtual override pure returns (uint8) {
return 3;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {ERC20} from "ERC20.sol";
import {IERC20} from "IERC20.sol";
import {SafeMath} from "SafeMath.sol";
import {SafeERC20} from "SafeERC20.sol";
import {ILoanToken2, ITrueFiPool2} from "ILoanToken2.sol";
import {LoanToken} from "LoanToken.sol";
/**
* @title LoanToken V2
* @dev A token which represents share of a debt obligation
*
* Each LoanToken has:
* - borrower address
* - borrow amount
* - loan term
* - loan APY
*
* Loan progresses through the following states:
* Awaiting: Waiting for funding to meet capital requirements
* Funded: Capital requirements met, borrower can withdraw
* Withdrawn: Borrower withdraws money, loan waiting to be repaid
* Settled: Loan has been paid back in full with interest
* Defaulted: Loan has not been paid back in full
* Liquidated: Loan has Defaulted and stakers have been Liquidated
*
* - LoanTokens are non-transferable except for whitelisted addresses
* - This version of LoanToken only supports a single funder
*/
contract LoanToken2 is ILoanToken2, ERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint128 public constant LAST_MINUTE_PAYBACK_DURATION = 1 days;
uint256 private constant APY_PRECISION = 10000;
address public override borrower;
address public liquidator;
uint256 public override amount;
uint256 public override term;
// apy precision: 10000 = 100%
uint256 public override apy;
uint256 public override start;
address public override lender;
uint256 public override debt;
uint256 public redeemed;
// whitelist for transfers
mapping(address => bool) public canTransfer;
Status public override status;
IERC20 public override token;
ITrueFiPool2 public override pool;
/**
* @dev Emitted when the loan is funded
* @param lender Address which funded the loan
*/
event Funded(address lender);
/**
* @dev Emitted when transfer whitelist is updated
* @param account Account to whitelist for transfers
* @param status New whitelist status
*/
event TransferAllowanceChanged(address account, bool status);
/**
* @dev Emitted when borrower withdraws funds
* @param beneficiary Account which will receive funds
*/
event Withdrawn(address beneficiary);
/**
* @dev Emitted when loan has been fully repaid
* @param returnedAmount Amount that was returned
*/
event Settled(uint256 returnedAmount);
/**
* @dev Emitted when term is over without full repayment
* @param returnedAmount Amount that was returned before expiry
*/
event Defaulted(uint256 returnedAmount);
/**
* @dev Emitted when a LoanToken is redeemed for underlying tokens
* @param receiver Receiver of tokens
* @param burnedAmount Amount of LoanTokens burned
* @param redeemedAmount Amount of token received
*/
event Redeemed(address receiver, uint256 burnedAmount, uint256 redeemedAmount);
/**
* @dev Emitted when a LoanToken is repaid by the borrower in underlying tokens
* @param repayer Sender of tokens
* @param repaidAmount Amount of token repaid
*/
event Repaid(address repayer, uint256 repaidAmount);
/**
* @dev Emitted when borrower reclaims remaining tokens
* @param borrower Receiver of remaining tokens
* @param reclaimedAmount Amount of tokens repaid
*/
event Reclaimed(address borrower, uint256 reclaimedAmount);
/**
* @dev Emitted when loan gets liquidated
* @param status Final loan status
*/
event Liquidated(Status status);
/**
* @dev Create a Loan
* @param _pool Pool to lend from
* @param _borrower Borrower address
* @param _lender Lender address
* @param _liquidator Liquidator address
* @param _amount Borrow amount of loaned tokens
* @param _term Loan length
* @param _apy Loan APY
*/
constructor(
ITrueFiPool2 _pool,
address _borrower,
address _lender,
address _liquidator,
uint256 _amount,
uint256 _term,
uint256 _apy
) public ERC20("TrueFi Loan Token", "LOAN") {
require(_lender != address(0), "LoanToken2: Lender is not set");
pool = _pool;
token = _pool.token();
borrower = _borrower;
liquidator = _liquidator;
amount = _amount;
term = _term;
apy = _apy;
lender = _lender;
debt = interest(amount);
}
/**
* @dev Only borrower can withdraw & repay loan
*/
modifier onlyBorrower() {
require(msg.sender == borrower, "LoanToken2: Caller is not the borrower");
_;
}
/**
* @dev Only liquidator can liquidate
*/
modifier onlyLiquidator() {
require(msg.sender == liquidator, "LoanToken2: Caller is not the liquidator");
_;
}
/**
* @dev Only after loan has been closed: Settled, Defaulted, or Liquidated
*/
modifier onlyAfterClose() {
require(status >= Status.Settled, "LoanToken2: Only after loan has been closed");
_;
}
/**
* @dev Only when loan is Funded
*/
modifier onlyOngoing() {
require(status == Status.Funded || status == Status.Withdrawn, "LoanToken2: Current status should be Funded or Withdrawn");
_;
}
/**
* @dev Only when loan is Funded
*/
modifier onlyFunded() {
require(status == Status.Funded, "LoanToken2: Current status should be Funded");
_;
}
/**
* @dev Only when loan is Withdrawn
*/
modifier onlyAfterWithdraw() {
require(status >= Status.Withdrawn, "LoanToken2: Only after loan has been withdrawn");
_;
}
/**
* @dev Only when loan is Awaiting
*/
modifier onlyAwaiting() {
require(status == Status.Awaiting, "LoanToken2: Current status should be Awaiting");
_;
}
/**
* @dev Only when loan is Defaulted
*/
modifier onlyDefaulted() {
require(status == Status.Defaulted, "LoanToken2: Current status should be Defaulted");
_;
}
/**
* @dev Only whitelisted accounts or lender
*/
modifier onlyWhoCanTransfer(address sender) {
require(
sender == lender || canTransfer[sender],
"LoanToken2: This can be performed only by lender or accounts allowed to transfer"
);
_;
}
/**
* @dev Only lender can perform certain actions
*/
modifier onlyLender() {
require(msg.sender == lender, "LoanToken2: This can be performed only by lender");
_;
}
/**
* @dev Get loan parameters
* @return amount, term, apy
*/
function getParameters()
external
override
view
returns (
uint256,
uint256,
uint256
)
{
return (amount, apy, term);
}
/**
* @dev Get coupon value of this loan token in token
* This assumes the loan will be paid back on time, with interest
* @param _balance number of LoanTokens to get value for
* @return coupon value of _balance LoanTokens in tokens
*/
function value(uint256 _balance) external override view returns (uint256) {
if (_balance == 0) {
return 0;
}
uint256 passed = block.timestamp.sub(start);
if (passed > term || status == Status.Settled) {
passed = term;
}
// assume year is 365 days
uint256 interest = amount.mul(apy).mul(passed).div(365 days).div(APY_PRECISION);
return amount.add(interest).mul(_balance).div(debt);
}
/**
* @dev Fund a loan
* Set status, start time, lender
*/
function fund() external override onlyAwaiting onlyLender {
status = Status.Funded;
start = block.timestamp;
_mint(msg.sender, debt);
token.safeTransferFrom(msg.sender, address(this), amount);
emit Funded(msg.sender);
}
/**
* @dev Whitelist accounts to transfer
* @param account address to allow transfers for
* @param _status true allows transfers, false disables transfers
*/
function allowTransfer(address account, bool _status) external override onlyLender {
canTransfer[account] = _status;
emit TransferAllowanceChanged(account, _status);
}
/**
* @dev Borrower calls this function to withdraw funds
* Sets the status of the loan to Withdrawn
* @param _beneficiary address to send funds to
*/
function withdraw(address _beneficiary) external override onlyBorrower onlyFunded {
status = Status.Withdrawn;
token.safeTransfer(_beneficiary, amount);
emit Withdrawn(_beneficiary);
}
/**
* @dev Settle the loan after checking it has been repaid
*/
function settle() public override onlyOngoing {
require(isRepaid(), "LoanToken2: loan must be repaid to settle");
status = Status.Settled;
emit Settled(_balance());
}
/**
* @dev Default the loan if it has not been repaid by the end of term
*/
function enterDefault() external override onlyOngoing {
require(!isRepaid(), "LoanToken2: cannot default a repaid loan");
require(start.add(term).add(LAST_MINUTE_PAYBACK_DURATION) <= block.timestamp, "LoanToken2: Loan cannot be defaulted yet");
status = Status.Defaulted;
emit Defaulted(_balance());
}
/**
* @dev Liquidate the loan if it has defaulted
*/
function liquidate() external override onlyDefaulted onlyLiquidator {
status = Status.Liquidated;
emit Liquidated(status);
}
/**
* @dev Redeem LoanToken balances for underlying token
* Can only call this function after the loan is Closed
* @param _amount amount to redeem
*/
function redeem(uint256 _amount) external override onlyAfterClose {
uint256 amountToReturn = _amount.mul(_balance()).div(totalSupply());
redeemed = redeemed.add(amountToReturn);
_burn(msg.sender, _amount);
token.safeTransfer(msg.sender, amountToReturn);
emit Redeemed(msg.sender, _amount, amountToReturn);
}
/**
* @dev Function for borrower to repay the loan
* Borrower can repay at any time
* @param _sender account sending token to repay
* @param _amount amount of token to repay
*/
function repay(address _sender, uint256 _amount) external override {
_repay(_sender, _amount);
}
/**
* @dev Function for borrower to repay all of the remaining loan balance
* Borrower should use this to ensure full repayment
* @param _sender account sending token to repay
*/
function repayInFull(address _sender) external override {
_repay(_sender, debt.sub(_balance()));
}
/**
* @dev Internal function for loan repayment
* If _amount is sufficient, then this also settles the loan
* @param _sender account sending token to repay
* @param _amount amount of token to repay
*/
function _repay(address _sender, uint256 _amount) internal onlyAfterWithdraw {
require(_amount <= debt.sub(_balance()), "LoanToken2: Cannot repay over the debt");
emit Repaid(_sender, _amount);
token.safeTransferFrom(_sender, address(this), _amount);
if (isRepaid()) {
settle();
}
}
/**
* @dev Function for borrower to reclaim stuck token
* Can only call this function after the loan is Closed
* and all of LoanToken holders have been burnt
*/
function reclaim() external override onlyAfterClose onlyBorrower {
require(totalSupply() == 0, "LoanToken2: Cannot reclaim when LoanTokens are in circulation");
uint256 balanceRemaining = _balance();
require(balanceRemaining > 0, "LoanToken2: Cannot reclaim when balance 0");
token.safeTransfer(borrower, balanceRemaining);
emit Reclaimed(borrower, balanceRemaining);
}
/**
* @dev Check how much was already repaid
* Funds stored on the contract's address plus funds already redeemed by lenders
* @return Uint256 representing what value was already repaid
*/
function repaid() external override view onlyAfterWithdraw returns (uint256) {
return _balance().add(redeemed);
}
/**
* @dev Check whether an ongoing loan has been repaid in full
* @return true if and only if this loan has been repaid
*/
function isRepaid() public override view onlyOngoing returns (bool) {
return _balance() >= debt;
}
/**
* @dev Public currency token balance function
* @return token balance of this contract
*/
function balance() external override view returns (uint256) {
return _balance();
}
/**
* @dev Get currency token balance for this contract
* @return token balance of this contract
*/
function _balance() internal view returns (uint256) {
return token.balanceOf(address(this));
}
/**
* @dev Calculate interest that will be paid by this loan for an amount (returned funds included)
* amount + ((amount * apy * term) / 365 days / precision)
* @param _amount amount
* @return uint256 Amount of interest paid for _amount
*/
function interest(uint256 _amount) internal view returns (uint256) {
return _amount.add(_amount.mul(apy).mul(term).div(365 days).div(APY_PRECISION));
}
/**
* @dev get profit for this loan
* @return profit for this loan
*/
function profit() external override view returns (uint256) {
return debt.sub(amount);
}
/**
* @dev Override ERC20 _transfer so only whitelisted addresses can transfer
* @param sender sender of the transaction
* @param recipient recipient of the transaction
* @param _amount amount to send
*/
function _transfer(
address sender,
address recipient,
uint256 _amount
) internal override onlyWhoCanTransfer(sender) {
return super._transfer(sender, recipient, _amount);
}
function version() external override pure returns (uint8) {
return 4;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {Initializable} from "Initializable.sol";
import {IPoolFactory} from "IPoolFactory.sol";
import {ILoanFactory2} from "ILoanFactory2.sol";
import {ITrueFiPool2} from "ITrueFiPool2.sol";
import {LoanToken2, IERC20} from "LoanToken2.sol";
/**
* @title LoanFactory2
* @notice Deploy LoanTokens for pools created by PoolFactory, with this Contract
* @dev LoanTokens are deployed through a factory to ensure that all
* LoanTokens adhere to the same contract code, rather than using an interface.
*/
contract LoanFactory2 is ILoanFactory2, Initializable {
// ================ WARNING ==================
// ===== THIS CONTRACT IS INITIALIZABLE ======
// === STORAGE VARIABLES ARE DECLARED BELOW ==
// REMOVAL OR REORDER OF VARIABLES WILL RESULT
// ========= IN STORAGE CORRUPTION ===========
// @dev Track Valid LoanTokens
mapping(address => bool) public override isLoanToken;
IPoolFactory public poolFactory;
address public lender;
address public liquidator;
// ======= STORAGE DECLARATION END ============
/**
* @dev Emitted when a LoanToken is created
* @param contractAddress LoanToken contract address
*/
event LoanTokenCreated(address contractAddress);
/**
* @dev Initialize this contract and set currency token
* @param _poolFactory PoolFactory address
* @param _lender Lender address
* @param _liquidator Liquidator address
*/
function initialize(
IPoolFactory _poolFactory,
address _lender,
address _liquidator
) external initializer {
poolFactory = _poolFactory;
lender = _lender;
liquidator = _liquidator;
}
/**
* @dev Deploy LoanToken with parameters
* @param _amount Amount to borrow
* @param _term Length of loan
* @param _apy Loan yield
*/
function createLoanToken(
ITrueFiPool2 _pool,
uint256 _amount,
uint256 _term,
uint256 _apy
) external override {
require(_amount > 0, "LoanFactory: Loans of amount 0, will not be approved");
require(_term > 0, "LoanFactory: Loans cannot have instantaneous term of repay");
require(poolFactory.isPool(address(_pool)), "LoanFactory: Pool was not created by PoolFactory");
address newToken = address(new LoanToken2(_pool, msg.sender, lender, liquidator, _amount, _term, _apy));
isLoanToken[newToken] = true;
emit LoanTokenCreated(newToken);
}
}
|
Liquidate the loan if it has defaulted/
|
function liquidate() external override onlyDefaulted onlyLiquidator {
status = Status.Liquidated;
emit Liquidated(status);
}
| 1,718,006 |
pragma solidity >= 0.5.0 < 0.7.0;
// pragma experimental ABIEncoderV2; // To support struct as return value
// WifiAllocation.sol: Performs bandwidth allocation according to the proportional rule
// Based on the previous version, and added support for requesting both (1) bandwidth and (2) burst data volume
contract WifiAllocation {
// Only owner can perform the allocation
address payable public owner;
uint public totalBandwidth;
uint public totalDesiredBandwidth;
uint public totalDesiredNonDynamic;
uint public totalDesiredDynamic;
uint public totalDesiredBurst;
// The owner can set a minimum unit price of the bandwidth.
// Unit: wei
// The price has to be an integer, so it is scaled for higher precision; same for bandwidth
uint constant bandwidthPriceScalingFactor = 100;
uint constant bandwidthScalingFactor = 100;
uint constant burstPriceScalingFactor = 100;
uint public minBandwidthPrice;
uint public bandwidthPrice;
uint public oldPrice;
uint public minBurstPriceFactor;
// If user does not specify desired burst, a default value is returned (e.g., 1MB)
uint public burstPrice;
// uint public weight; // Changed to local variables to reduce gas cost
// uint public weightedPrice;
// The bids to be collected by the contract owner
uint public pendingCollection;
uint public totalCollected;
uint public latestTransaction;
// Keep record of all users
uint public numUsers;
uint[] public allocatedBandwidth;
uint[] public currentBalances;
bool[] public isActive;
// Whether the user accepts dynamic bandwidth allocation
// i.e., the allocated bandwidth may fluctuate, while the bid remains the same
bool[] public isDynamic;
// The corresponding prices that users are charged according to
uint[] public actualPrices;
uint[] public burstVol;
struct User {
address userAddress;
uint desiredBandwidth;
uint receivedBandwidth;
uint lastPaymentTime;
uint thresholdBid;
uint burst;
}
mapping(uint => User) users;
mapping(address => uint) occupiedID;
mapping(address => uint) pendingWithdrawl;
event UponAllocation(
uint _numUsers,
uint[] _allocatedBandwidth,
uint[] _currentBalances,
uint[] _actualPrices,
bool[] _isActive,
uint[] _burstVol
);
modifier onlyOwner {
require(
msg.sender == owner,
"Only the owner can call this function"
);
_;
}
modifier onlyNotOwner {
require(
msg.sender != owner,
"The owner cannot call this function"
);
_;
}
modifier requirePayment {
require(
msg.value > 0,
"You must pay some value !"
);
_;
}
constructor(uint _totalBandwidth, uint _minBandwidthPrice, uint _minBurstPriceFactor) public {
// Initialises with the total bandwidth specified
owner = msg.sender;
totalBandwidth = _totalBandwidth;
minBandwidthPrice = _minBandwidthPrice;
minBurstPriceFactor = _minBurstPriceFactor;
bandwidthPrice = minBandwidthPrice * bandwidthPriceScalingFactor;
// By default totalDesiredBurst is set to 1
burstPrice = minBurstPriceFactor * 1 * 1;
}
// Called by a user when joining or exitting the wifi connection
function uponConnection(uint bandwidth, uint thresholdBid, uint burst) public payable onlyNotOwner {
latestTransaction = now;
if(bandwidth > 0) {
// The user wants to join the connection
// Check if user already exists
if(occupiedID[msg.sender] > 0) {
uint userID = occupiedID[msg.sender];
// Array index starts from 0, userID starts from 1
if(isActive[userID - 1]) {
/// @notice Case1: The user is still actively connected: renewal of connection
connectionRenewal(userID, bandwidth, thresholdBid, burst);
} else {
/// @notice Case2: The user has been disconnected: reentry of connection
connectionReentry(userID, bandwidth, thresholdBid, burst);
}
} else {
/// @notice Case3: The user has never connected before: initialisation of connection
occupiedID[msg.sender] = connectionInitialisation(bandwidth, thresholdBid, burst);
}
} else {
/// @notice Case4: The user wants to quit the connection (by indicating a bandwidth of 0)
require(occupiedID[msg.sender] > 0, "You are not an existing user!");
connectionTermination(occupiedID[msg.sender]);
withdrawBalance();
}
}
// Called by an ACTIVE user when he only selects to top up balance
function addBalance() public payable onlyNotOwner {
require(occupiedID[msg.sender] > 0, "You are not an existing user!");
currentBalances[occupiedID[msg.sender] - 1] += msg.value;
}
// // Called by the owner to check results for testing purposes
// function getAllocationResults() public onlyOwner {
// // returns (uint[] memory, uint[] memory, uint, bool[] memory, bool[] memory, uint[] memory) {
// // updateBalance();
// emit UponAllocation(numUsers, allocatedBandwidth, currentBalances, actualPrices, isActive);
// // return (currentBalances, actualPrices, totalCollected, isActive, isDynamic, allocatedBandwidth);
// }
// // Called by users to check the real-time supply and price
// function getPriceAndSupply() public view returns (uint, uint, uint, uint) {
// // Param1: current unit price of bandwidth (scaled by bandwidthPriceScalingFactor)
// // Param2: total demand (totalDesiredBandwidth)
// // Param3: total demand of dynamic users (totalDesiredDynamic)
// // Param4: total demand of non-dynamic users (totalDesiredNonDynamic)
// return (bandwidthPrice, totalDesiredBandwidth, totalDesiredDynamic, totalDesiredNonDynamic);
// }
// Get user profile
// function getUserProfile(uint userID) public view returns (User memory) {
// return users[userID];
// }
// Get userID
function getUserID(address _user) public view returns (uint) {
return occupiedID[_user];
}
function getUserAllocation(uint _userID) public view returns (uint) {
return allocatedBandwidth[_userID]/bandwidthScalingFactor;
}
function getUserBalance(uint _userID) public view returns (uint) {
return currentBalances[_userID];
}
// Perform bandwidth allocation depending on the demand and supply
function performAllocation() public {
if(totalDesiredBandwidth <= totalBandwidth) {
demandNotExceedSupply();
} else {
demandExceedSupply();
}
}
// Deduct balance according to usage
// If the balance is not enough, the user is deactived from connection
function updateBalance() public {
for(uint i = 0; i < numUsers; i++) {
if(isActive[i]) {
uint currentTime = now;
uint currentFee = bandwidthPrice * users[i + 1].receivedBandwidth * (currentTime - users[i + 1].lastPaymentTime) / (bandwidthPriceScalingFactor * bandwidthScalingFactor);
// Since there is no capacity limit on burst volume, users are only charged at a constant price specified by owner
// The cost of burst is VOLUME * UNIT PRICE * TIME DURATION
currentFee += burstPrice * users[i + 1].burst * (currentTime - users[i + 1].lastPaymentTime) / burstPriceScalingFactor;
users[i + 1].lastPaymentTime = currentTime;
if(currentBalances[i] >= currentFee) {
currentBalances[i] -= currentFee;
pendingCollection += currentFee;
} else {
// Deactivate the user from connection
currentFee = currentBalances[i];
currentBalances[i] = 0;
pendingCollection += currentFee;
users[i + 1].receivedBandwidth = 0;
totalDesiredBandwidth -= users[i + 1].desiredBandwidth;
if(isDynamic[i]) {
totalDesiredDynamic -= users[i + 1].desiredBandwidth;
} else {
totalDesiredNonDynamic -= users[i + 1].desiredBandwidth;
}
users[i + 1].desiredBandwidth = 0;
allocatedBandwidth[i] = 0;
actualPrices[i] = 0;
isActive[i] = false;
isDynamic[i] = false;
users[i + 1].burst = 0;
burstVol[i] = 0;
// Calculate the allocation again since the demand has changed
// performAllocation();
}
}
}
collectBids();
emit UponAllocation(numUsers, allocatedBandwidth, currentBalances, actualPrices, isActive, burstVol);
}
// Top-up back to user according to the bandwidth wasted
// e.g. userID 1, bandwidth 1MB, duration 2 second: (1, 100, 200, false)
function topBack(uint userID, uint bandwidth, uint duration, bool useOldPrice) public onlyOwner {
uint timingFactor = 100;
if(isActive[userID]) {
uint price = useOldPrice ? oldPrice : bandwidthPrice;
uint topBackFee = price * bandwidth * duration / (bandwidthPriceScalingFactor * bandwidthScalingFactor * timingFactor);
currentBalances[userID] += topBackFee;
if (pendingCollection >= topBackFee) {
pendingCollection -= topBackFee;
} else {
pendingCollection = 0;
}
}
}
// When the user has never connected before
function connectionInitialisation(uint bandwidth, uint thresholdBid, uint burst) internal requirePayment returns (uint userID) {
// Create profile for the new user
userID = ++numUsers;
// {userAddress, desiredBandwidth, receivedBandwidth, lastPaymentTime, thresholdBid, burst}
users[userID] = User(msg.sender, bandwidth, 0, now, thresholdBid, burst);
isActive.push(true);
totalDesiredBandwidth += bandwidth;
// In this case, the thresholdBid is compared with desiredBandwidth * bandwidthPrice to determine whether the user is dynamic
if(bandwidthPrice * bandwidth / bandwidthPriceScalingFactor > thresholdBid) {
isDynamic.push(true);
totalDesiredDynamic += bandwidth;
} else {
isDynamic.push(false);
totalDesiredNonDynamic += bandwidth;
}
totalDesiredBurst += burst;
allocatedBandwidth.push(0);
currentBalances.push(msg.value);
actualPrices.push(bandwidthPrice);
burstVol.push(burst);
updatePrice(bandwidth * bandwidthScalingFactor, true);
performAllocation();
updateBalance();
}
// When the user is still connected
// The user can either top up his balance or modify his desired bandwidth
function connectionRenewal(uint userID, uint bandwidth, uint thresholdBid, uint burst) internal {
totalDesiredBandwidth = totalDesiredBandwidth + bandwidth - users[userID].desiredBandwidth;
// Since the user is still active, there is no need to update isDynamic (later in performAllocation())
if(isDynamic[userID - 1]) {
totalDesiredDynamic = totalDesiredDynamic + bandwidth - users[userID].desiredBandwidth;
} else {
totalDesiredNonDynamic = totalDesiredNonDynamic + bandwidth - users[userID].desiredBandwidth;
}
totalDesiredBurst = totalDesiredBurst + burst - users[userID].burst;
// Update user profile
currentBalances[userID - 1] += msg.value;
users[userID].desiredBandwidth = bandwidth;
users[userID].thresholdBid = thresholdBid;
users[userID].burst = burst;
burstVol[userID - 1] = burst;
// No need to update lastPaymentTime here
// Check whether the demand is increasing or decreasing, depending on the *actually received bandwidth(WHICH IS SCALED)*
// e.g., User i desires 40 units bandwidth at price 1.2, but receives 32 units at price 1.5
// Now he only wants 20 units instead, so the total bid is reduced by 1.5 * (32 - 20)
// ***NOTE***: receivedBandwidth is scaled by bandwidthScalingFactor
// bool isPositive = (bandwidth * bandwidthScalingFactor >= users[userID].receivedBandwidth);
// updatePrice(isPositive ? (bandwidth * bandwidthScalingFactor - users[userID].receivedBandwidth) : (users[userID].receivedBandwidth - bandwidth * bandwidthScalingFactor), isPositive);
// --------------------------------------
// // ***REMOVED***: depending on the *desired bandwidth* instead, otherwise a user who only wants to top up his balance but retaining his desired bandwidth may
// // unintentionally increase the price
bool isPositive = (bandwidth >= users[userID].desiredBandwidth);
updatePrice(isPositive ? (bandwidth - users[userID].desiredBandwidth) * bandwidthScalingFactor : (users[userID].desiredBandwidth - bandwidth) * bandwidthScalingFactor, isPositive);
performAllocation();
updateBalance();
}
// When the user has connected before but was deactivated from connection
// The owner still keeps the user profile for a certain period
function connectionReentry(uint userID, uint bandwidth, uint thresholdBid, uint burst) internal requirePayment {
// Update user profile
isActive[userID - 1] = true;
totalDesiredBandwidth += bandwidth;
// In this case, the thresholdBid is compared with desiredBandwidth * bandwidthPrice to determine whether the user is dynamic
if(bandwidthPrice * bandwidth / bandwidthPriceScalingFactor > thresholdBid) {
isDynamic[userID - 1] = true;
totalDesiredDynamic += bandwidth;
} else {
isDynamic[userID - 1] = false;
totalDesiredNonDynamic += bandwidth;
}
totalDesiredBurst += burst;
currentBalances[userID - 1] += msg.value;
users[userID].desiredBandwidth = bandwidth;
users[userID].lastPaymentTime = now;
users[userID].thresholdBid = thresholdBid;
users[userID].burst = burst;
burstVol[userID - 1] = burst;
updatePrice(bandwidth * bandwidthScalingFactor, true);
performAllocation();
updateBalance();
}
// When the user wants to quit the connection
// The owner still keeps the user profile for a certain period
function connectionTermination(uint userID) internal {
uint deltaBandwidth = users[userID].receivedBandwidth;
// uint deltaBandwidth = users[userID].desiredBandwidth * bandwidthScalingFactor;
pendingWithdrawl[users[userID].userAddress] += (currentBalances[userID - 1] + msg.value);
isActive[userID - 1] = false;
totalDesiredBandwidth -= users[userID].desiredBandwidth;
if(isDynamic[userID - 1]) {
totalDesiredDynamic -= users[userID].desiredBandwidth;
} else {
totalDesiredNonDynamic -= users[userID].desiredBandwidth;
}
totalDesiredBurst -= users[userID].burst;
isDynamic[userID - 1] = false;
currentBalances[userID - 1] = 0;
users[userID].receivedBandwidth = 0;
users[userID].desiredBandwidth = 0;
users[userID].thresholdBid = 0;
users[userID].burst = 0;
burstVol[userID - 1] = 0;
allocatedBandwidth[userID - 1] = 0;
actualPrices[userID - 1] = 0;
// Similar to connectionRenewal(), the deltaBandwidth depends on the *actually received bandwidth*
updatePrice(deltaBandwidth, false);
performAllocation();
updateBalance();
}
// When the total desired bandwidth does not exceed the available bandwidth:
// Everyone simply gets as much as desired
function demandNotExceedSupply() internal {
for(uint i = 0; i < numUsers; i++) {
if(isActive[i]) {
actualPrices[i] = bandwidthPrice;
allocatedBandwidth[i] = users[i + 1].desiredBandwidth * bandwidthScalingFactor;
users[i + 1].receivedBandwidth = users[i + 1].desiredBandwidth * bandwidthScalingFactor;
}
}
}
// When the total desired bandwidth exceeds the available bandwidth:
// The resource allocation mechanism is triggered
function demandExceedSupply() internal {
// uint weight;
uint weightedPrice;
updateIsDynamic();
if(totalDesiredNonDynamic >= totalBandwidth) {
// Ignore isDynamic[] and actualPrices[], and all users are charged bandwidthPrice
// Proportionally allocate the bandwidth according to desired bandwidth
for(uint i = 0; i < numUsers; i++) {
if(isActive[i]) {
actualPrices[i] = bandwidthPrice;
allocatedBandwidth[i] = users[i + 1].desiredBandwidth * totalBandwidth * bandwidthScalingFactor / totalDesiredBandwidth;
users[i + 1].receivedBandwidth = allocatedBandwidth[i];
}
}
} else {
// Non-dynamic users receive desired bandwidth, while dynamic users proportionally share the remaining
// weight = totalDesiredDynamic * bandwidthPriceScalingFactor / (totalBandwidth - totalDesiredNonDynamic);
// weightedPrice = weight * bandwidthPrice / bandwidthPriceScalingFactor;
weightedPrice = totalDesiredDynamic * bandwidthPrice / (totalBandwidth - totalDesiredNonDynamic);
for(uint i = 0; i < numUsers; i++) {
if(isActive[i]) {
if(isDynamic[i]) {
actualPrices[i] = bandwidthPrice;
allocatedBandwidth[i] = users[i + 1].desiredBandwidth * (totalBandwidth - totalDesiredNonDynamic) * bandwidthScalingFactor / totalDesiredDynamic;
users[i + 1].receivedBandwidth = allocatedBandwidth[i];
} else {
// actualPrices[i] = weight * bandwidthPrice / bandwidthPriceScalingFactor;
actualPrices[i] = weightedPrice;
allocatedBandwidth[i] = users[i + 1].desiredBandwidth * bandwidthScalingFactor;
users[i + 1].receivedBandwidth = users[i + 1].desiredBandwidth * bandwidthScalingFactor;
}
}
}
}
}
// Update the real-time unit price according to user demand
// NOTICE: deltaBandwidth is a scaled value
function updatePrice(uint deltaBandwidth, bool isPositive) internal {
// uint prevPrice = bandwidthPrice;
oldPrice = bandwidthPrice;
if(totalDesiredBandwidth <= totalBandwidth) {
bandwidthPrice = minBandwidthPrice * bandwidthPriceScalingFactor;
} else {
if(isPositive) {
// New price = Total bid / Total bandwidth = Current price * (Total allocated bandwidth + New demand) / Total bandwidth
// (1) Total allocated bandwidth < Total bandwidth, i.e., totalDesiredBandwidth - deltaBandwidth < totalBandwidth
// (2) Total allocated bandwidth = Total bandwidth, i.e., totalDesiredBandwidth - deltaBandwidth >= totalBandwidth
if(totalDesiredBandwidth * bandwidthScalingFactor - deltaBandwidth < totalBandwidth * bandwidthScalingFactor) {
bandwidthPrice = bandwidthPrice * totalDesiredBandwidth / totalBandwidth;
} else {
bandwidthPrice = bandwidthPrice * (totalBandwidth * bandwidthScalingFactor + deltaBandwidth) / (totalBandwidth * bandwidthScalingFactor);
// bandwidthPrice = bandwidthPrice * totalDesiredBandwidth * bandwidthScalingFactor / (totalDesiredBandwidth * bandwidthScalingFactor - deltaBandwidth);
}
} else {
// The condition has guaranteed that: Total allocated bandwidth = Total bandwidth
// New price = Total bid / Total bandwidth = Current Price * (Total bandwidth - Reduced demand) / Total bandwidth
bandwidthPrice = bandwidthPrice * (totalBandwidth * bandwidthScalingFactor - deltaBandwidth) / (totalBandwidth * bandwidthScalingFactor);
// bandwidthPrice = bandwidthPrice * totalDesiredBandwidth * bandwidthScalingFactor / (totalDesiredBandwidth * bandwidthScalingFactor + deltaBandwidth);
}
}
burstPrice = minBurstPriceFactor * totalDesiredBurst * totalDesiredBurst;
}
// Update whether the user is dynamic according to current demand and price
function updateIsDynamic() internal {
// uint weight;
uint weightedPrice;
if(totalDesiredNonDynamic >= totalBandwidth) {
for(uint i = 0; i < numUsers; i++) {
if(isActive[i]) {
// In this case, the thresholdBid is compared with desiredBandwidth * bandwidthPrice to determine whether the user is dynamic
if(!isDynamic[i] && bandwidthPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor > users[i + 1].thresholdBid) {
isDynamic[i] = true;
totalDesiredNonDynamic -= users[i + 1].desiredBandwidth;
totalDesiredDynamic += users[i + 1].desiredBandwidth;
} else if (isDynamic[i] && bandwidthPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor <= users[i + 1].thresholdBid) {
isDynamic[i] = false;
totalDesiredDynamic -= users[i + 1].desiredBandwidth;
totalDesiredNonDynamic += users[i + 1].desiredBandwidth;
}
}
}
}
// Not using *else* here, since a second-round update may be needed after the first *if*
// weight > 1, so some non-dynamic users after the first round may be tagged as dynamic in this round
// weight is decreasing, so probably multiple rounds of update are needed
// ***UPDATE***: Limit the number of cycles to avoid gas over limit
uint numCycle;
while(true) {
numCycle++;
bool hasChanged;
if(totalDesiredNonDynamic < totalBandwidth) {
// weight = totalDesiredDynamic * bandwidthPriceScalingFactor / (totalBandwidth - totalDesiredNonDynamic);
// weightedPrice = weight * bandwidthPrice / bandwidthPriceScalingFactor;
weightedPrice = totalDesiredDynamic * bandwidthPrice / (totalBandwidth - totalDesiredNonDynamic);
// If the bid per unit time exceeds the thresholdBid, the user becomes dynamic
for(uint i = 0; i < numUsers; i++) {
if(isActive[i]) {
// In this case, the thresholdBid is compared with desiredBandwidth * weightedPrice to determine whether the user is dynamic
if(!isDynamic[i] && weightedPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor > users[i + 1].thresholdBid) {
isDynamic[i] = true;
totalDesiredNonDynamic -= users[i + 1].desiredBandwidth;
totalDesiredDynamic += users[i + 1].desiredBandwidth;
hasChanged = true;
} else if(isDynamic[i] && weightedPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor <= users[i + 1].thresholdBid) {
isDynamic[i] = false;
totalDesiredDynamic -= users[i + 1].desiredBandwidth;
totalDesiredNonDynamic += users[i + 1].desiredBandwidth;
hasChanged = true;
}
}
}
}
// Check numCycle to avoid infinite loop, e.g., when a user keeps changing between the dynamic and non-dynamic users
if(!hasChanged || numCycle == 10 || totalDesiredNonDynamic == 0) {
break;
}
}
}
// Allow the user to withdraw remaining balance upon connection termination
function withdrawBalance() internal {
uint amount = pendingWithdrawl[msg.sender];
pendingWithdrawl[msg.sender] = 0;
msg.sender.transfer(amount);
}
// Allow the owner to collect bids submitted by users
function collectBids() internal {
uint amount = pendingCollection;
pendingCollection = 0;
totalCollected += amount;
owner.transfer(amount);
}
// Clearing all existing user profiles and reset the parameters
function resetAll() internal onlyOwner {
for(uint i = 0; i < numUsers; i++) {
delete(pendingWithdrawl[users[i + 1].userAddress]);
delete(occupiedID[users[i + 1].userAddress]);
delete(users[i + 1]);
}
delete currentBalances;
delete allocatedBandwidth;
delete actualPrices;
delete isDynamic;
delete isActive;
delete numUsers;
delete totalCollected;
delete pendingCollection;
bandwidthPrice = minBandwidthPrice * bandwidthPriceScalingFactor;
delete totalDesiredBurst;
delete totalDesiredDynamic;
delete totalDesiredNonDynamic;
delete totalDesiredBandwidth;
delete burstVol;
}
}
|
Perform bandwidth allocation depending on the demand and supply
|
function performAllocation() public {
if(totalDesiredBandwidth <= totalBandwidth) {
demandNotExceedSupply();
demandExceedSupply();
}
}
| 6,478,407 |
/**
*Submitted for verification at Etherscan.io on 2021-11-10
*/
/* SPDX-License-Identifier: GPL-3.0
████████╗██╗░░██╗███████╗░░██████╗░░█████╗░███╗░░██╗░██████╗░░█████╗░███████╗███╗░░██╗░██████╗
╚══██╔══╝██║░░██║██╔════╝░░██╔══██╗██╔══██╗████╗░██║██╔════╝░██╔══██╗██╔════╝████╗░██║██╔════╝
░░░██║░░░███████║█████╗░░░░██████╔╝███████║██╔██╗██║██║░░██╗░███████║█████╗░░██╔██╗██║╚█████╗░
░░░██║░░░██╔══██║██╔══╝░░░░██╔═══╝░██╔══██║██║╚████║██║░░╚██╗██╔══██║██╔══╝░░██║╚████║░╚═══██╗
░░░██║░░░██║░░██║███████╗░░██║░░░░░██║░░██║██║░╚███║╚██████╔╝██║░░██║███████╗██║░╚███║██████╔╝
░░░╚═╝░░░╚═╝░░╚═╝╚══════╝░░╚═╝░░░░░╚═╝░░╚═╝╚═╝░░╚══╝░╚═════╝░╚═╝░░╚═╝╚══════╝╚═╝░░╚══╝╚═════╝░
*/
pragma solidity ^0.8.0;
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed 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: PangaensTheGenesis.sol
/**
* @dev Contract to mint the Pangaens The Genesis NFT collection.
*
* The contract allows user to mint during both presale and the public sale
*
*/
contract PangaensTheGenesis is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
using ECDSA for bytes32;
// Mint constants
uint256 public presaleCost = 0.05 ether;
uint256 public publicSaleCost = 0.06 ether;
uint256 public maxSupply = 8900;
uint256 public specialMintMaxSupply = 200;
uint256 public publicSaleMaxMintPerTx = 20;
uint256 public presaleMaxMint = 10;
// Mint flags
bool public isPresaleActive = false;
bool public isPublicSaleActive = false;
bool public revealed = false;
// URI for presale and public mint
string private baseURI;
string private preRevealURI;
// Mapping presale mint address. Allows presale mint only once
mapping (address => bool) private presaleClaimed;
// Presale signer address to verify WL
address private presaleSigner;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
* Sets the baseURI, preRevealedURI & presaleSigner values to be used in the contract
*
*/
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initPreRevealURI,
address _initPresaleSigner
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setPreRevealURI(_initPreRevealURI);
setPresaleSigner(_initPresaleSigner);
}
/**
* @dev Public sale mint
*
* @param _mintAmount Number of tokens to mint.
*/
function mintPublicSale(
uint256 _mintAmount
) external nonReentrant payable {
require(isPublicSaleActive, "Sale is not active");
require(_mintAmount > 0, "Must mint at least 1 NFT");
require(_mintAmount <= publicSaleMaxMintPerTx, "Mint count exceeds limit for public sale");
require((publicSaleCost * _mintAmount) <= msg.value, "ETH sent does not match required payment");
// Mint
_mintToUser(msg.sender, _mintAmount, maxSupply);
}
/**
* @dev Presale mint
*
* @param _hashMessage Must be a valid hash message.
* @param _signature Must be a valid signature.
* @param _mintAmount Number of tokens to mint.
*/
function mintPresale(
bytes32 _hashMessage,
bytes memory _signature,
uint256 _mintAmount
) external nonReentrant payable {
require(isPresaleActive, "Presale not active");
require(!isPublicSaleActive, "Cannot mint while main sale is active");
require(_mintAmount > 0, "Must mint at least 1 NFT");
require(_mintAmount <= presaleMaxMint, "Mint count exceeds limit for presale");
require((presaleCost * _mintAmount) <= msg.value, "ETH sent does not match required payment");
require(!presaleClaimed[msg.sender], "User already minted in the presale with this address");
// Verify signature
require(_verifySigner(_hashMessage, _signature), "Invalid signature");
// Verify hash sent is for the given sender address
require(_verifyHash(_hashMessage, msg.sender), "Invalid hash for address");
// Mint
_mintToUser(msg.sender, _mintAmount, maxSupply);
//Adds the user to the presale claimed map
presaleClaimed[msg.sender] = true;
}
/**
* @dev Verify signature sent is valid
*/
function _verifySigner(bytes32 _hashMessage, bytes memory _signature) private view returns (bool) {
return _hashMessage.recover(_signature) == presaleSigner;
}
/**
* @dev Verify hash sent is for the user address
*/
function _verifyHash(bytes32 hash, address _user) private pure returns(bool){
return hash == keccak256(abi.encodePacked(_user)).toEthSignedMessageHash();
}
/**
* @dev Mints to the given recipient. Internal mint function
*/
function _mintToUser(address recipient, uint256 _mintAmount, uint256 maxMintSupply) private {
uint256 supply = totalSupply();
require(supply + _mintAmount <= maxMintSupply, "Cannot mint more than available");
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(recipient, supply + i);
}
}
/**
* @dev Returns the baseURI
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/**
* @dev Overrides the tokenURI method
*
* @param tokenId ID of the token
* @return string preRevealURI if not revealed else baseURI
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(!revealed) {
return preRevealURI;
}
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : "";
}
/**
* @dev Mint for giveaways. Used by onlyOwner
*
* @param _user Recipient user address
* @param _mintAmount Number of tokens to mint
*/
function specialMint(address _user, uint256 _mintAmount) external onlyOwner {
require(_mintAmount > 0, "Must mint at least 1 NFT");
// Mint
_mintToUser(_user, _mintAmount, specialMintMaxSupply);
}
/**
* @dev Allows to enable/disable public sale minting
*/
function togglePublicSaleState() external onlyOwner {
isPublicSaleActive = !isPublicSaleActive;
}
/**
* @dev Allows to enable/disable presale minting
*/
function togglePresaleState() external onlyOwner {
isPresaleActive = !isPresaleActive;
}
/**
* @dev Sets the new preRevealURI
*/
function setPreRevealURI(string memory _newPreRevealURI) public onlyOwner {
preRevealURI = _newPreRevealURI;
}
/**
* @dev Sets the revealed flag
*/
function reveal(bool _state) public onlyOwner {
revealed = _state;
}
/**
* @dev Sets the new baseURI
*/
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
/**
* @dev Sets the new cost for public sale
*/
function setPublicSaleCost(uint256 _newCost) public onlyOwner() {
publicSaleCost = _newCost;
}
/**
* @dev Sets the new cost for presale
*/
function setPresaleCost(uint256 _newCost) public onlyOwner() {
presaleCost = _newCost;
}
/**
* @dev Sets the new maximum mint amount per transaction for public sale
*/
function setPublicSaleMaxMintPerTx(uint256 _newmaxMintAmount) public onlyOwner() {
publicSaleMaxMintPerTx = _newmaxMintAmount;
}
/**
* @dev Sets the new maximum mint amount for presale
*/
function setPresaleMaxMint(uint256 _newmaxMintAmount) public onlyOwner() {
presaleMaxMint = _newmaxMintAmount;
}
/**
* @dev Sets a new signature verifier for presale
*/
function setPresaleSigner(address _signer) public onlyOwner {
presaleSigner = _signer;
}
/**
* @dev Returns whether a user has claimed in the presale
*/
function getPresaleClaimed(address _user) external view returns (bool) {
return presaleClaimed[_user];
}
/**
* @dev Withdraws the funds from the contract
*/
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{value:address(this).balance }("");
require(success);
}
}
|
Overrides the tokenURI method tokenId ID of the token return string preRevealURI if not revealed else baseURI/
|
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(!revealed) {
return preRevealURI;
}
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : "";
}
| 2,412,646 |
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeMathUInt128.sol";
import "./SafeCast.sol";
import "./Utils.sol";
import "./Storage.sol";
import "./Config.sol";
import "./Events.sol";
import "./Bytes.sol";
import "./Operations.sol";
import "./UpgradeableMaster.sol";
import "./PairTokenManager.sol";
/// @title zkSync main contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
/// @author Stars Labs
contract ZkSync is PairTokenManager, UpgradeableMaster, Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
bytes32 private constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
function pairFor(address tokenA, address tokenB, bytes32 _salt) external view returns (address pair) {
pair = pairmanager.pairFor(tokenA, tokenB, _salt);
}
function createPair(address _tokenA, address _tokenB, bytes32 salt) external {
require(_tokenA != _tokenB ||
keccak256(abi.encodePacked(IERC20(_tokenA).symbol())) == keccak256(abi.encodePacked("EGS")),
"pair same token invalid");
requireActive();
governance.requireGovernor(msg.sender);
//check _tokenA is registered or not
uint16 tokenAID = governance.validateTokenAddress(_tokenA);
//check _tokenB is registered or not
uint16 tokenBID = governance.validateTokenAddress(_tokenB);
//create pair
(address token0, address token1, uint16 token0_id, uint16 token1_id) = _tokenA < _tokenB ? (_tokenA, _tokenB, tokenAID, tokenBID) : (_tokenB, _tokenA, tokenBID, tokenAID);
address pair = pairmanager.createPair(token0, token1, salt);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
token0_id,
token1_id,
validatePairTokenAddress(pair),
pair
);
}
//create pair including ETH
function createETHPair(address _tokenERC20, bytes32 salt) external {
requireActive();
governance.requireGovernor(msg.sender);
//check _tokenERC20 is registered or not
uint16 erc20ID = governance.validateTokenAddress(_tokenERC20);
//create pair
address pair = pairmanager.createPair(address(0), _tokenERC20, salt);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
0,
erc20ID,
validatePairTokenAddress(pair),
pair);
}
function registerCreatePair(uint16 _tokenA, uint16 _tokenB, uint16 _tokenPair, address _pair) internal {
// Priority Queue request
(uint16 token0, uint16 token1) = _tokenA < _tokenB ? (_tokenA, _tokenB) : (_tokenB, _tokenA);
Operations.CreatePair memory op = Operations.CreatePair({
accountId: 0, //unknown at this point
tokenA: token0,
tokenB: token1,
tokenPair: _tokenPair,
pair: _pair
});
// pubData
bytes memory pubData = Operations.writeCreatePairPubdata(op);
addPriorityRequest(Operations.OpType.CreatePair, pubData);
emit OnchainCreatePair(token0, token1, _tokenPair, _pair);
}
// Upgrade functional
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external pure override returns (uint256) {
return UPGRADE_NOTICE_PERIOD;
}
/// @notice Notification that upgrade notice period started
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeNoticePeriodStarted() external override {}
/// @notice Notification that upgrade preparation status is activated
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradePreparationStarted() external override {
upgradePreparationActive = true;
upgradePreparationActivationTime = block.timestamp;
}
/// @notice Notification that upgrade canceled
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeCanceled() external override {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Notification that upgrade finishes
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeFinishes() external override {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external view override returns (bool) {
return !exodusMode;
}
/// @notice zkSync contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// @dev _governanceAddress The address of Governance contract
/// @dev _verifierAddress The address of Verifier contract
/// @dev _pairManagerAddress the address of UniswapV2Factory contract
/// @dev _zkSyncCommitBlockAddress the address of ZkSyncCommitBlockAddress contract
/// @dev _genesisStateHash Genesis blocks (first block) state tree root hash
function initialize(bytes calldata initializationParameters) external {
initializeReentrancyGuard();
(
address _governanceAddress,
address _verifierAddress,
address _verifierExitAddress,
address _pairManagerAddress,
address _zkSyncCommitBlockAddress,
bytes32 _genesisStateHash
) = abi.decode(initializationParameters, (address, address, address, address, address, bytes32));
governance = Governance(_governanceAddress);
verifier = Verifier(_verifierAddress);
verifier_exit = VerifierExit(_verifierExitAddress);
pairmanager = UniswapV2Factory(_pairManagerAddress);
zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress;
// We need initial state hash because it is used in the commitment of the next block
StoredBlockInfo memory storedBlockZero =
StoredBlockInfo(0, 0, EMPTY_STRING_KECCAK, 0, _genesisStateHash, bytes32(0));
storedBlockHashes[0] = hashStoredBlockInfo(storedBlockZero);
}
// Priority queue
/// @notice Saves priority request in storage
/// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event
/// @param _opType Rollup operation type
/// @param _pubData Operation pubdata
function addPriorityRequest(
Operations.OpType _opType,
bytes memory _pubData
) internal {
// Expiration block is: current block number + priority expiration delta
uint64 expirationBlock = uint64(block.number + PRIORITY_EXPIRATION);
uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests;
bytes20 hashedPubData = Utils.hashBytesToBytes20(_pubData);
priorityRequests[nextPriorityRequestId] = PriorityOperation({
hashedPubData: hashedPubData,
expirationBlock: expirationBlock,
opType: _opType
});
emit NewPriorityRequest(msg.sender, nextPriorityRequestId, _opType, _pubData, uint256(expirationBlock));
totalOpenPriorityRequests++;
}
/// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external nonReentrant {
require(totalBlocksCommitted == totalBlocksProven, "wq1"); // All the blocks must be proven
require(totalBlocksCommitted == totalBlocksExecuted, "w12"); // All the blocks must be executed
if (upgradeParameters.length != 0) {
StoredBlockInfo memory lastBlockInfo;
(lastBlockInfo) = abi.decode(upgradeParameters, (StoredBlockInfo));
storedBlockHashes[totalBlocksExecuted] = hashStoredBlockInfo(lastBlockInfo);
}
zkSyncCommitBlockAddress = address(0xcb4c185cC1bC048742D3b6AB760Efd2D3592c58f);
}
/// @notice Checks that current state not is exodus mode
function requireActive() internal view {
require(!exodusMode, "L"); // exodus mode activated
}
/// @notice Accrues users balances from deposit priority requests in Exodus mode
/// @dev WARNING: Only for Exodus mode
/// @dev Canceling may take several separate transactions to be completed
/// @param _n number of requests to process
function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] memory _depositsPubdata) external nonReentrant {
require(exodusMode, "8"); // exodus mode not active
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess == _depositsPubdata.length, "A");
require(toProcess > 0, "9"); // no deposits to process
uint64 currentDepositIdx = 0;
for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) {
if (priorityRequests[id].opType == Operations.OpType.Deposit) {
bytes memory depositPubdata = _depositsPubdata[currentDepositIdx];
require(Utils.hashBytesToBytes20(depositPubdata) == priorityRequests[id].hashedPubData, "a");
++currentDepositIdx;
Operations.Deposit memory op = Operations.readDepositPubdata(depositPubdata);
bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, op.tokenId);
pendingBalances[packedBalanceKey].balanceToWithdraw += op.amount;
}
delete priorityRequests[id];
}
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
/// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit
function depositETH() external payable {
require(msg.value > 0, "1");
requireActive();
require(tokenIds[msg.sender] == 0, "da");
registerDeposit(0, SafeCast.toUint128(msg.value), msg.sender);
}
/// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit
/// @param _token Token address
/// @param _amount Token amount
function depositERC20(IERC20 _token, uint104 _amount) external nonReentrant {
requireActive();
require(tokenIds[msg.sender] == 0, "db");
// Get token id by its address
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused
require(_token.balanceOf(address(this)) + _amount <= MAX_ERC20_TOKEN_BALANCE, "bgt");
} else {
// lpToken
lpTokenId = validatePairTokenAddress(address(_token));
}
uint256 balance_before = 0;
uint256 balance_after = 0;
uint128 deposit_amount = 0;
// lpToken
if (lpTokenId > 0) {
// Note: For lp token, main contract always has no money
balance_before = _token.balanceOf(msg.sender);
pairmanager.burn(address(_token), msg.sender, SafeCast.toUint128(_amount)); //
balance_after = _token.balanceOf(msg.sender);
deposit_amount = SafeCast.toUint128(balance_before.sub(balance_after));
require(deposit_amount <= MAX_DEPOSIT_AMOUNT, "C1");
registerDeposit(lpTokenId, deposit_amount, msg.sender);
} else {
// token
balance_before = _token.balanceOf(address(this));
require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "fd012"); // token transfer failed deposit
balance_after = _token.balanceOf(address(this));
deposit_amount = SafeCast.toUint128(balance_after.sub(balance_before));
require(deposit_amount <= MAX_DEPOSIT_AMOUNT, "C2");
registerDeposit(tokenId, deposit_amount, msg.sender);
}
}
/// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract
/// @param _address Address of the tokens owner
/// @param _token Address of token, zero address is used for ETH
function getPendingBalance(address _address, address _token) public view returns (uint128) {
uint16 tokenId = 0;
if (_token != address(0)) {
tokenId = governance.validateTokenAddress(_token);
}
return pendingBalances[packAddressAndTokenId(_address, tokenId)].balanceToWithdraw;
}
/// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract
/// @param _address Address of the tokens owner
/// @param _tokenId token id, 0 is used for ETH
function getBalanceToWithdraw(address _address, uint16 _tokenId) public view returns (uint128) {
return pendingBalances[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw;
}
/// @notice Register full exit request - pack pubdata, add priority request
/// @param _accountId Numerical id of the account
/// @param _token Token address, 0 address for ether
function requestFullExit(uint32 _accountId, address _token) public nonReentrant {
requireActive();
require(_accountId <= MAX_ACCOUNT_ID, "e");
uint16 tokenId;
uint16 lpTokenId = tokenIds[_token];
if (_token == address(0)) {
tokenId = 0;
} else if (lpTokenId == 0) {
// This means it is not a pair address
// 非lpToken
tokenId = governance.validateTokenAddress(_token);
require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused
} else {
// lpToken
tokenId = lpTokenId;
}
// Priority Queue request
Operations.FullExit memory op =
Operations.FullExit({
accountId: _accountId,
owner: msg.sender,
tokenId: tokenId,
amount: 0, // unknown at this point
pairAccountId: 0
});
bytes memory pubData = Operations.writeFullExitPubdataForPriorityQueue(op);
addPriorityRequest(Operations.OpType.FullExit, pubData);
// User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value
// In this case operator should just overwrite this slot during confirming withdrawal
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
pendingBalances[packedBalanceKey].gasReserveValue = FILLED_GAS_RESERVE_VALUE;
}
/// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event.
/// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest
/// @dev of existed priority requests expiration block number.
/// @return bool flag that is true if the Exodus mode must be entered.
function activateExodusMode() public returns (bool) {
bool trigger =
block.number >= priorityRequests[firstPriorityRequestId].expirationBlock &&
priorityRequests[firstPriorityRequestId].expirationBlock != 0;
if (trigger) {
if (!exodusMode) {
exodusMode = true;
emit ExodusMode();
}
return true;
} else {
return false;
}
}
/// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event
/// @param _tokenId Token by id
/// @param _amount Token amount
/// @param _owner Receiver
function registerDeposit(
uint16 _tokenId,
uint128 _amount,
address _owner
) internal {
// Priority Queue request
Operations.Deposit memory op =
Operations.Deposit({
accountId: 0, // unknown at this point
owner: _owner,
tokenId: _tokenId,
amount: _amount,
pairAccountId: 0
});
bytes memory pubData = Operations.writeDepositPubdataForPriorityQueue(op);
addPriorityRequest(Operations.OpType.Deposit, pubData);
emit OnchainDeposit(
msg.sender,
_tokenId,
_amount,
_owner
);
}
// The contract is too large. Break some functions to zkSyncCommitBlockAddress
fallback() external payable {
address nextAddress = zkSyncCommitBlockAddress;
require(nextAddress != address(0), "zkSyncCommitBlockAddress should be set");
// Execute external function from facet using delegatecall and return any value.
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), nextAddress, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
/// @dev Address of lock flag variable.
/// @dev Flag is placed at random memory location to not interfere with Storage contract.
uint256 private constant LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1;
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/566a774222707e424896c0c390a84dc3c13bdcb2/contracts/security/ReentrancyGuard.sol
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
function initializeReentrancyGuard() internal {
uint256 lockSlotOldValue;
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange every call to nonReentrant
// will be cheaper.
assembly {
lockSlotOldValue := sload(LOCK_FLAG_ADDRESS)
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
// Check that storage slot for reentrancy guard is empty to rule out possibility of slot conflict
require(lockSlotOldValue == 0, "1B");
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
uint256 _status;
assembly {
_status := sload(LOCK_FLAG_ADDRESS)
}
// On the first call to nonReentrant, _notEntered will be true
require(_status == _NOT_ENTERED);
// Any calls to nonReentrant after this point will fail
assembly {
sstore(LOCK_FLAG_ADDRESS, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "14");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "v");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "15");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "x");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "y");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUInt128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 c = a + b;
require(c >= a, "12");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint128 a, uint128 b) internal pure returns (uint128) {
return sub(a, b, "aa");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b <= a, errorMessage);
uint128 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint128 a, uint128 b) internal pure returns (uint128) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint128 c = a * b;
require(c / a == b, "13");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint128 a, uint128 b) internal pure returns (uint128) {
return div(a, b, "ac");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint128 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint128 a, uint128 b) internal pure returns (uint128) {
return mod(a, b, "ad");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*
* _Available since v2.5.0._
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "16");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "17");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "18");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "19");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "1a");
return uint8(value);
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./IERC20.sol";
import "./Bytes.sol";
library Utils {
/// @notice Returns lesser of two values
function minU32(uint32 a, uint32 b) internal pure returns (uint32) {
return a < b ? a : b;
}
/// @notice Returns lesser of two values
function minU64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
/// @notice Sends tokens
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transfer` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function sendERC20(
IERC20 _token,
address _to,
uint256 _amount
) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) =
address(_token).call(abi.encodeWithSignature("transfer(address,uint256)", _to, _amount));
// `transfer` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Transfers token from one address to another
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _from Address of sender
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function transferFromERC20(
IERC20 _token,
address _from,
address _to,
uint256 _amount
) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) =
address(_token).call(abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount));
// `transferFrom` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Recovers signer's address from ethereum signature for given message
/// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1)
/// @param _messageHash signed message hash.
/// @return address of the signer
function recoverAddressFromEthSignature(bytes memory _signature, bytes32 _messageHash)
internal
pure
returns (address)
{
require(_signature.length == 65, "P"); // incorrect signature length
bytes32 signR;
bytes32 signS;
uint8 signV;
assembly {
signR := mload(add(_signature, 32))
signS := mload(add(_signature, 64))
signV := byte(0, mload(add(_signature, 96)))
}
return ecrecover(_messageHash, signV, signR, signS);
}
/// @notice Returns new_hash = hash(old_hash + bytes)
function concatHash(bytes32 _hash, bytes memory _bytes) internal pure returns (bytes32) {
bytes32 result;
assembly {
let bytesLen := add(mload(_bytes), 32)
mstore(_bytes, _hash)
result := keccak256(_bytes, bytesLen)
mstore(_bytes, sub(bytesLen, 32))
}
return result;
}
function hashBytesToBytes20(bytes memory _bytes) internal pure returns (bytes20) {
return bytes20(uint160(uint256(keccak256(_bytes))));
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./IERC20.sol";
import "./Governance.sol";
import "./Verifier.sol";
import "./VerifierExit.sol";
import "./Operations.sol";
import "./uniswap/UniswapV2Factory.sol";
/// @title zkSync storage contract
/// @author Matter Labs
contract Storage {
/// @dev Flag indicates that upgrade preparation status is active
/// @dev Will store false in case of not active upgrade mode
bool internal upgradePreparationActive;
/// @dev Upgrade preparation activation timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint256 internal upgradePreparationActivationTime;
/// @dev Verifier contract. Used to verify block proof
Verifier public verifier;
/// @dev Verifier contract. Used to verify exit proof
VerifierExit public verifier_exit;
/// @dev Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list
Governance public governance;
// NEW ADD
UniswapV2Factory internal pairmanager;
uint8 internal constant FILLED_GAS_RESERVE_VALUE = 0xff; // we use it to set gas revert value so slot will not be emptied with 0 balance
struct PendingBalance {
uint128 balanceToWithdraw;
uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value
}
/// @dev Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw
mapping(bytes22 => PendingBalance) public pendingBalances;
/// @notice Total number of executed blocks i.e. blocks[totalBlocksExecuted] points at the latest executed block (block 0 is genesis)
uint32 public totalBlocksExecuted;
/// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block
uint32 public totalBlocksCommitted;
/// @notice Flag indicates that a user has exited in the exodus mode certain token balance (per account id and tokenId)
mapping(uint32 => mapping(uint16 => bool)) public performedExodus;
/// @notice Flag indicates that exodus (mass exit) mode is triggered
/// @notice Once it was raised, it can not be cleared again, and all users must exit
bool public exodusMode;
/// @notice First open priority request id
uint64 public firstPriorityRequestId;
/// @notice Total number of requests
uint64 public totalOpenPriorityRequests;
/// @notice Total number of committed requests.
/// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big
uint64 public totalCommittedPriorityRequests;
/// @notice Packs address and token id into single word to use as a key in balances mapping
function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) {
return bytes22((uint176(_address) | (uint176(_tokenId) << 160)));
}
/// @Rollup block stored data
/// @member blockNumber Rollup block number
/// @member priorityOperations Number of priority operations processed
/// @member pendingOnchainOperationsHash Hash of all operations that must be processed after verify
/// @member timestamp Rollup block timestamp, have the same format as Ethereum block constant
/// @member stateHash Root hash of the rollup state
/// @member commitment Verified input for the zkSync circuit
struct StoredBlockInfo {
uint32 blockNumber;
uint64 priorityOperations;
bytes32 pendingOnchainOperationsHash;
uint256 timestamp;
bytes32 stateHash;
bytes32 commitment;
}
/// @notice Returns the keccak hash of the ABI-encoded StoredBlockInfo
function hashStoredBlockInfo(StoredBlockInfo memory _storedBlockInfo) public pure returns (bytes32) {
return keccak256(abi.encode(_storedBlockInfo));
}
/// @dev Stored hashed StoredBlockInfo for some block number
mapping(uint32 => bytes32) public storedBlockHashes;
/// @notice Total blocks proven.
uint32 public totalBlocksProven;
/// @notice Priority Operation container
/// @member hashedPubData Hashed priority operation public data
/// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before)
/// @member opType Priority operation type
struct PriorityOperation {
bytes20 hashedPubData;
uint64 expirationBlock;
Operations.OpType opType;
}
/// @dev Priority Requests mapping (request id - operation)
/// @dev Contains op type, pubdata and expiration block of unsatisfied requests.
/// @dev Numbers are in order of requests receiving
// requestId -> PriorityOperation
mapping(uint64 => PriorityOperation) public priorityRequests;
// NEW ADD
address public zkSyncCommitBlockAddress;
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title zkSync configuration constants
/// @author Matter Labs
/// @author Stars Labs
contract Config {
/// @dev ERC20 tokens and ETH withdrawals gas limit, used only for complete withdrawals
uint256 constant WITHDRAWAL_GAS_LIMIT = 100000;
/// @dev Bytes in one chunk
uint8 constant CHUNK_BYTES = 9;
/// @dev zkSync address length
uint8 constant ADDRESS_BYTES = 20;
uint8 constant PUBKEY_HASH_BYTES = 20;
/// @dev Public key bytes length
uint8 constant PUBKEY_BYTES = 32;
/// @dev Ethereum signature r/s bytes length
uint8 constant ETH_SIGN_RS_BYTES = 32;
/// @dev Success flag bytes length
uint8 constant SUCCESS_FLAG_BYTES = 1;
/// @dev Max amount of tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 511;
/// @dev Max account id that could be registered in the network
uint32 internal constant MAX_ACCOUNT_ID = 16777215;
/// @dev Max deposit of ERC20 token that is possible to deposit
uint128 internal constant MAX_DEPOSIT_AMOUNT = 20282409603651670423947251286015;
/// @dev Max ERC20 token balance that is possible to deposit, suppose ((2**126) - 1)
uint128 internal constant MAX_ERC20_TOKEN_BALANCE = (2**126) - 1;
/// @dev Expected average period of block creation
uint256 constant BLOCK_PERIOD = 15 seconds;
/// @dev ETH blocks verification expectation
/// @dev Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN.
/// @dev If set to 0 validator can revert blocks at any time.
uint256 constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD;
uint256 constant NOOP_BYTES = 1 * CHUNK_BYTES;
uint256 constant DEPOSIT_BYTES = 6 * CHUNK_BYTES;
uint256 constant TRANSFER_TO_NEW_BYTES = 6 * CHUNK_BYTES;
uint256 constant WITHDRAW_BYTES = 6 * CHUNK_BYTES;
uint256 constant TRANSFER_BYTES = 2 * CHUNK_BYTES;
uint256 constant FORCED_EXIT_BYTES = 6 * CHUNK_BYTES;
// NEW ADD
uint256 constant CREATE_PAIR_BYTES = 4 * CHUNK_BYTES;
/// @dev Full exit operation length
uint256 constant FULL_EXIT_BYTES = 6 * CHUNK_BYTES;
/// @dev ChangePubKey operation length
uint256 constant CHANGE_PUBKEY_BYTES = 6 * CHUNK_BYTES;
/// @dev Expiration delta for priority request to be satisfied (in seconds)
/// @dev NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD)
/// @dev otherwise incorrect block with priority op could not be reverted.
uint256 constant PRIORITY_EXPIRATION_PERIOD = 14 days;
/// @dev Expiration delta for priority request to be satisfied (in ETH blocks)
uint256 constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD / BLOCK_PERIOD;
/// @dev Maximum number of priority request to clear during verifying the block
/// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots
/// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure
uint64 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6;
/// @dev Reserved time for users to send full exit priority operation in case of an upgrade (in seconds)
uint256 constant MASS_FULL_EXIT_PERIOD = 9 days;
/// @dev Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds)
uint256 constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days;
/// @dev Notice period before activation preparation status of upgrade mode (in seconds)
/// @dev NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it.
uint256 constant UPGRADE_NOTICE_PERIOD = 0 days;
/// @dev Timestamp - seconds since unix epoch
uint256 constant COMMIT_TIMESTAMP_NOT_OLDER = 168 hours;
/// @dev Maximum available error between real commit block timestamp and analog used in the verifier (in seconds)
/// @dev Must be used cause miner's `block.timestamp` value can differ on some small value (as we know - 15 seconds)
uint256 constant COMMIT_TIMESTAMP_APPROXIMATION_DELTA = 15 minutes;
/// @dev Bit mask to apply for verifier public input before verifying.
uint256 constant INPUT_MASK = (~uint256(0) >> 3);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Upgradeable.sol";
import "./Operations.sol";
/// @title zkSync events
/// @author Matter Labs
/// @author Stars Labs
interface Events {
/// @notice Event emitted when a block is committed
event BlockCommit(uint32 indexed blockNumber);
event BlockVerification(uint32 indexed blockNumber);
/// @notice Event emitted when user funds are withdrawn from the zkSync contract
event Withdrawal(uint16 indexed tokenId, uint128 amount);
event OnchainWithdrawal(
address indexed owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Event emitted when user send a transaction to deposit her funds
event OnchainDeposit(
address indexed sender,
uint16 indexed tokenId,
uint128 amount,
address indexed owner
);
event OnchainCreatePair(
uint16 indexed tokenAId,
uint16 indexed tokenBId,
uint16 indexed pairId,
address pair
);
/// @notice Event emitted when blocks are reverted
event BlocksRevert(uint32 totalBlocksVerified, uint32 totalBlocksCommitted);
/// @notice Exodus mode entered event
event ExodusMode();
/// @notice New priority request event. Emitted when a request is placed into mapping
event NewPriorityRequest(
address sender,
uint64 serialId,
Operations.OpType opType,
bytes pubData,
uint256 expirationBlock
);
/// @notice Deposit committed event.
event DepositCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Full exit committed event.
event FullExitCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
event CreatePairCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
uint16 tokenAId,
uint16 tokenBId,
uint16 indexed tokenPairId,
address pair
);
/// @notice Notice period changed
event NoticePeriodChange(uint256 newNoticePeriod);
}
/// @title Upgrade events
/// @author Matter Labs
interface UpgradeEvents {
/// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts
event NewUpgradable(uint256 indexed versionId, address indexed upgradeable);
/// @notice Upgrade mode enter event
event NoticePeriodStart(
uint256 indexed versionId,
address[] newTargets,
uint256 noticePeriod // notice period (in seconds)
);
/// @notice Upgrade mode cancel event
event UpgradeCancel(uint256 indexed versionId);
/// @notice Upgrade mode preparation status event
event PreparationStart(uint256 indexed versionId);
/// @notice Upgrade mode complete event
event UpgradeComplete(uint256 indexed versionId, address[] newTargets);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
// Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word)
// implements the following algorithm:
// f(bytes memory input, uint offset) -> X out
// where byte representation of out is N bytes from input at the given offset
// 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N]
// W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N
// 2) We load W from memory into out, last N bytes of W are placed into out
library Bytes {
function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 2);
}
function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 3);
}
function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 4);
}
function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 16);
}
// Copies 'len' lower bytes from 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'.
function toBytesFromUIntTruncated(uint256 self, uint8 byteLength) private pure returns (bytes memory bts) {
require(byteLength <= 32, "Q");
bts = new bytes(byteLength);
// Even though the bytes will allocate a full word, we don't want
// any potential garbage bytes in there.
uint256 data = self << ((32 - byteLength) * 8);
assembly {
mstore(
add(bts, 32), // BYTES_HEADER_SIZE
data
)
}
}
// Copies 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length '20'.
function toBytesFromAddress(address self) internal pure returns (bytes memory bts) {
bts = toBytesFromUIntTruncated(uint256(self), 20);
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) {
uint256 offset = _start + 20;
require(self.length >= offset, "R");
assembly {
addr := mload(add(self, offset))
}
}
// Reasoning about why this function works is similar to that of other similar functions, except NOTE below.
// NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) {
require(self.length >= (_start + 20), "S");
assembly {
r := mload(add(add(self, 0x20), _start))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x2)
function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) {
uint256 offset = _start + 0x2;
require(_bytes.length >= offset, "T");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x3)
function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) {
uint256 offset = _start + 0x3;
require(_bytes.length >= offset, "U");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x4)
function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) {
uint256 offset = _start + 0x4;
require(_bytes.length >= offset, "V");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x10)
function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) {
uint256 offset = _start + 0x10;
require(_bytes.length >= offset, "W");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x14)
function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) {
uint256 offset = _start + 0x14;
require(_bytes.length >= offset, "X");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "Y");
assembly {
r := mload(add(_bytes, offset))
}
}
// Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228
// Get slice from bytes arrays
// Returns the newly created 'bytes memory'
// NOTE: theoretically possible overflow of (_start + _length)
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_bytes.length >= (_start + _length), "Z"); // bytes length is less then start byte + length bytes
bytes memory tempBytes = new bytes(_length);
if (_length != 0) {
assembly {
let slice_curr := add(tempBytes, 0x20)
let slice_end := add(slice_curr, _length)
for {
let array_current := add(_bytes, add(_start, 0x20))
} lt(slice_curr, slice_end) {
slice_curr := add(slice_curr, 0x20)
array_current := add(array_current, 0x20)
} {
mstore(slice_curr, mload(array_current))
}
}
}
return tempBytes;
}
/// Reads byte stream
/// @return new_offset - offset + amount of bytes read
/// @return data - actually read data
// NOTE: theoretically possible overflow of (_offset + _length)
function read(
bytes memory _data,
uint256 _offset,
uint256 _length
) internal pure returns (uint256 new_offset, bytes memory data) {
data = slice(_data, _offset, _length);
new_offset = _offset + _length;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readBool(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bool r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]) != 0;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readUint8(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint8 r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]);
}
// NOTE: theoretically possible overflow of (_offset + 2)
function readUInt16(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint16 r) {
new_offset = _offset + 2;
r = bytesToUInt16(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 3)
function readUInt24(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 4)
function readUInt32(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint32 r) {
new_offset = _offset + 4;
r = bytesToUInt32(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 16)
function readUInt128(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint128 r) {
new_offset = _offset + 16;
r = bytesToUInt128(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readUInt160(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint160 r) {
new_offset = _offset + 20;
r = bytesToUInt160(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readAddress(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, address r) {
new_offset = _offset + 20;
r = bytesToAddress(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readBytes20(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bytes20 r) {
new_offset = _offset + 20;
r = bytesToBytes20(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 32)
function readBytes32(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bytes32 r) {
new_offset = _offset + 32;
r = bytesToBytes32(_data, _offset);
}
/// Trim bytes into single word
function trim(bytes memory _data, uint256 _new_length) internal pure returns (uint256 r) {
require(_new_length <= 0x20, "10"); // new_length is longer than word
require(_data.length >= _new_length, "11"); // data is to short
uint256 a;
assembly {
a := mload(add(_data, 0x20)) // load bytes into uint256
}
return a >> ((0x20 - _new_length) * 8);
}
// Helper function for hex conversion.
function halfByteToHex(bytes1 _byte) internal pure returns (bytes1 _hexByte) {
require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range.
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
return bytes1(uint8(0x66656463626139383736353433323130 >> (uint8(_byte) * 8)));
}
// Convert bytes to ASCII hex representation
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) {
bytes memory outStringBytes = new bytes(_input.length * 2);
// code in `assembly` construction is equivalent of the next code:
// for (uint i = 0; i < _input.length; ++i) {
// outStringBytes[i*2] = halfByteToHex(_input[i] >> 4);
// outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f);
// }
assembly {
let input_curr := add(_input, 0x20)
let input_end := add(input_curr, mload(_input))
for {
let out_curr := add(outStringBytes, 0x20)
} lt(input_curr, input_end) {
input_curr := add(input_curr, 0x01)
out_curr := add(out_curr, 0x02)
} {
let curr_input_byte := shr(0xf8, mload(input_curr))
// here outStringByte from each half of input byte calculates by the next:
//
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
// outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8)))
mstore(
out_curr,
shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
mstore(
add(out_curr, 0x01),
shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
}
}
return outStringBytes;
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Bytes.sol";
import "./Utils.sol";
/// @title zkSync operations tools
/// @author Matter Labs
/// @author Stars Labs
library Operations {
/// @notice zkSync circuit operation type
enum OpType {
Noop, //0
Deposit,
TransferToNew,
Withdraw,
Transfer,
FullExit, //5
ChangePubKey,
MiningMaintenance,
ClaimBonus,
CreatePair,
AddLiquidity,//10
RemoveLiquidity,
Swap
}
// Byte lengths
uint8 constant OP_TYPE_BYTES = 1;
uint8 constant TOKEN_BYTES = 2;
uint8 constant PUBKEY_BYTES = 32;
uint8 constant NONCE_BYTES = 4;
uint8 constant PUBKEY_HASH_BYTES = 20;
uint8 constant ADDRESS_BYTES = 20;
/// @dev Packed fee bytes lengths
uint8 constant FEE_BYTES = 2;
/// @dev zkSync account id bytes lengths
uint8 constant ACCOUNT_ID_BYTES = 4;
uint8 constant AMOUNT_BYTES = 16;
/// @dev Signature (for example full exit signature) bytes length
uint8 constant SIGNATURE_BYTES = 64;
// Deposit pubdata
struct Deposit {
// uint8 opType
uint32 accountId;
uint16 tokenId;
uint128 amount;
address owner;
uint32 pairAccountId;
}
// NEW ADD ACCOUNT_ID_BYTES
uint256 public constant PACKED_DEPOSIT_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES + ACCOUNT_ID_BYTES;
/// Deserialize deposit pubdata
function readDepositPubdata(bytes memory _data) internal pure returns (Deposit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "N"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
// NEW ADD pairAccountId
function writeDepositPubdataForPriorityQueue(Deposit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
uint8(OpType.Deposit),
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
op.owner, // owner
bytes4(0) // pairAccountId
);
}
/// @notice Write deposit pubdata for priority queue check.
function checkDepositInPriorityQueue(Deposit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeDepositPubdataForPriorityQueue(op)) == hashedPubdata;
}
// FullExit pubdata
struct FullExit {
// uint8 opType
uint32 accountId;
address owner;
uint16 tokenId;
uint128 amount;
uint32 pairAccountId;
}
// NEW ADD ACCOUNT_ID_BYTES
uint256 public constant PACKED_FULL_EXIT_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ACCOUNT_ID_BYTES;
function readFullExitPubdata(bytes memory _data) internal pure returns (FullExit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
// NEW ADD pairAccountId
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "O"); // reading invalid full exit pubdata size
}
function writeFullExitPubdataForPriorityQueue(FullExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
uint8(OpType.FullExit),
op.accountId, // accountId
op.owner, // owner
op.tokenId, // tokenId
uint128(0), // amount -- ignored
// NEW ADD pairAccountId
uint32(0) // pairAccountId -- ignored
);
}
function checkFullExitInPriorityQueue(FullExit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeFullExitPubdataForPriorityQueue(op)) == hashedPubdata;
}
// Withdraw pubdata
struct Withdraw {
//uint8 opType; -- present in pubdata, ignored at serialization
// NEW ADD
uint32 accountId;
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address owner;
// NEW ADD
uint32 pairAccountId;
}
function readWithdrawPubdata(bytes memory _data) internal pure returns (Withdraw memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
// CHANGE uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES;
uint256 offset = OP_TYPE_BYTES; // opType
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
offset += FEE_BYTES; // fee (ignored)
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
// NEW ADD
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
}
// ForcedExit pubdata
struct ForcedExit {
//uint8 opType; -- present in pubdata, ignored at serialization
//uint32 initiatorAccountId; -- present in pubdata, ignored at serialization
//uint32 targetAccountId; -- present in pubdata, ignored at serialization
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address target;
}
function readForcedExitPubdata(bytes memory _data) internal pure returns (ForcedExit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES * 2; // opType + initiatorAccountId + targetAccountId (ignored)
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
offset += FEE_BYTES; // fee (ignored)
(offset, parsed.target) = Bytes.readAddress(_data, offset); // target
}
// ChangePubKey
enum ChangePubkeyType {ECRECOVER, CREATE2, OldECRECOVER}
struct ChangePubKey {
// uint8 opType; -- present in pubdata, ignored at serialization
uint32 accountId;
bytes20 pubKeyHash;
address owner;
uint32 nonce;
//uint16 tokenId; -- present in pubdata, ignored at serialization
//uint16 fee; -- present in pubdata, ignored at serialization
}
function readChangePubKeyPubdata(bytes memory _data) internal pure returns (ChangePubKey memory parsed) {
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce
}
// CreatePair pubdata
// NEW ADD
struct CreatePair {
// uint8 opType; -- present in pubdata, ignored at serialization
uint32 accountId;
uint16 tokenA;
uint16 tokenB;
uint16 tokenPair;
address pair;
}
// NEW ADD
uint256 public constant PACKED_CREATE_PAIR_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES;
// NEW ADD
function readCreatePairPubdata(bytes memory _data) internal pure returns (CreatePair memory parsed)
{
uint256 offset = OP_TYPE_BYTES; // opType
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId
(offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId
(offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId
(offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId
require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size
}
// NEW ADD
function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
OpType.CreatePair,
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenA, // tokenAId
op.tokenB, // tokenBId
op.tokenPair, // pairId
op.pair // pair account
);
}
function checkCreatePairInPriorityQueue(CreatePair memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeCreatePairPubdata(op)) == hashedPubdata;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it)
/// @author Matter Labs
interface UpgradeableMaster {
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint256);
/// @notice Notifies contract that notice period started
function upgradeNoticePeriodStarted() external;
/// @notice Notifies contract that upgrade preparation status is activated
function upgradePreparationStarted() external;
/// @notice Notifies contract that upgrade canceled
function upgradeCanceled() external;
/// @notice Notifies contract that upgrade finishes
function upgradeFinishes() external;
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
contract PairTokenManager {
/// @dev Max amount of pair tokens registered in the network.
/// This is computed by: 2048 - 512 = 1536
uint16 constant MAX_AMOUNT_OF_PAIR_TOKENS = 1536;
uint16 constant PAIR_TOKEN_START_ID = 512;
/// @dev Total number of pair tokens registered in the network
uint16 public totalPairTokens;
/// @dev List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @dev List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @dev Token added to Franklin net
event NewToken(
address indexed token,
uint16 indexed tokenId
);
function addPairToken(address _token) internal {
require(tokenIds[_token] == 0, "pan1"); // token exists
require(totalPairTokens < MAX_AMOUNT_OF_PAIR_TOKENS, "pan2"); // no free identifiers for tokens
uint16 newPairTokenId = PAIR_TOKEN_START_ID + totalPairTokens;
totalPairTokens++;
// tokenId -> token
tokenAddresses[newPairTokenId] = _token;
// token -> tokenId
tokenIds[_token] = newPairTokenId;
emit NewToken(_token, newPairTokenId);
}
/// @dev Validate pair token address
/// @param _tokenAddr Token address
/// @return tokens id
function validatePairTokenAddress(address _tokenAddr) public view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "pms3");
require(tokenId < (PAIR_TOKEN_START_ID + MAX_AMOUNT_OF_PAIR_TOKENS), "pms4");
require(tokenId >= PAIR_TOKEN_START_ID, "pms5");
return tokenId;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: UNLICENSED
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
function symbol() external pure returns (string memory);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Config.sol";
/// @title Governance Contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
/// @author Stars Labs
contract Governance is Config {
/// @notice Token added to Franklin net
event NewToken(address indexed token, uint16 indexed tokenId);
/// @notice Governor changed
event NewGovernor(address newGovernor);
/// @notice Validator's status changed
event ValidatorStatusUpdate(address indexed validatorAddress, bool isActive);
event TokenPausedUpdate(address indexed token, bool paused);
/// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades
address public networkGovernor;
/// @notice Total number of ERC20 tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 public totalTokens;
/// @notice List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @notice List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @notice List of permitted validators
mapping(address => bool) public validators;
/// @notice Paused tokens list, deposits are impossible to create for paused tokens
mapping(uint16 => bool) public pausedTokens;
/// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _networkGovernor The address of network governor
function initialize(bytes calldata initializationParameters) external {
address _networkGovernor = abi.decode(initializationParameters, (address));
networkGovernor = _networkGovernor;
}
/// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Change current governor
/// @param _newGovernor Address of the new governor
function changeGovernor(address _newGovernor) external {
requireGovernor(msg.sender);
if (networkGovernor != _newGovernor) {
networkGovernor = _newGovernor;
emit NewGovernor(_newGovernor);
}
}
/// @notice Add token to the list of networks tokens
/// @param _token Token address
function addToken(address _token) external {
requireGovernor(msg.sender);
require(_token != address(0), "1e0");
require(tokenIds[_token] == 0, "1e"); // token exists
require(totalTokens < MAX_AMOUNT_OF_REGISTERED_TOKENS, "1f"); // no free identifiers for tokens
totalTokens++;
uint16 newTokenId = totalTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth
// tokenId -> token
tokenAddresses[newTokenId] = _token;
// token -> tokenId
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @notice Pause token deposits for the given token
/// @param _tokenAddr Token address
/// @param _tokenPaused Token paused status
function setTokenPaused(address _tokenAddr, bool _tokenPaused) external {
requireGovernor(msg.sender);
uint16 tokenId = this.validateTokenAddress(_tokenAddr);
if (pausedTokens[tokenId] != _tokenPaused) {
pausedTokens[tokenId] = _tokenPaused;
emit TokenPausedUpdate(_tokenAddr, _tokenPaused);
}
}
/// @notice Change validator status (active or not active)
/// @param _validator Validator address
/// @param _active Active flag
function setValidator(address _validator, bool _active) external {
requireGovernor(msg.sender);
if (validators[_validator] != _active) {
validators[_validator] = _active;
emit ValidatorStatusUpdate(_validator, _active);
}
}
/// @notice Check if specified address is is governor
/// @param _address Address to check
function requireGovernor(address _address) public view {
require(_address == networkGovernor, "1g"); // only by governor
}
/// @notice Checks if validator is active
/// @param _address Validator address
function requireActiveValidator(address _address) external view {
require(validators[_address], "1h"); // validator is not active
}
/// @notice Validate token id (must be less than or equal to total tokens amount)
/// @param _tokenId Token id
/// @return bool flag that indicates if token id is less than or equal to total tokens amount
function isValidTokenId(uint16 _tokenId) external view returns (bool) {
return _tokenId <= totalTokens;
}
/// @notice Validate token address
/// @param _tokenAddr Token address
/// @return tokens id
function validateTokenAddress(address _tokenAddr) external view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "1i"); // 0 is not a valid token
return tokenId;
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./KeysWithPlonkVerifier.sol";
import "./Config.sol";
// Hardcoded constants to avoid accessing store
contract Verifier is KeysWithPlonkVerifier, Config {
function initialize(bytes calldata) external {}
/// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function verifyAggregatedBlockProof(
uint256[] memory _recursiveInput,
uint256[] memory _proof,
uint8[] memory _vkIndexes,
uint256[] memory _individual_vks_inputs,
uint256[16] memory _subproofs_limbs
) external view returns (bool) {
for (uint256 i = 0; i < _individual_vks_inputs.length; ++i) {
uint256 commitment = _individual_vks_inputs[i];
_individual_vks_inputs[i] = commitment & INPUT_MASK;
}
VerificationKey memory vk = getVkAggregated(uint32(_vkIndexes.length));
return
verify_serialized_proof_with_recursion(
_recursiveInput,
_proof,
VK_TREE_ROOT,
VK_MAX_INDEX,
_vkIndexes,
_individual_vks_inputs,
_subproofs_limbs,
vk
);
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./KeysWithPlonkVerifier.sol";
import "./Config.sol";
// Hardcoded constants to avoid accessing store
contract VerifierExit is KeysWithPlonkVerifierOld, Config {
function initialize(bytes calldata) external {}
/// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function verifyExitProof(
bytes32 _rootHash,
uint32 _accountId,
address _owner,
uint16 _tokenId,
uint128 _amount,
uint256[] calldata _proof
) external view returns (bool) {
bytes32 commitment =
sha256(abi.encodePacked(uint256(_rootHash) , _accountId, _owner, _tokenId, _amount));
uint256[] memory inputs = new uint256[](1);
inputs[0] = uint256(commitment) & INPUT_MASK;
ProofOld memory proof = deserialize_proof_old(inputs, _proof);
VerificationKeyOld memory vk = getVkExit();
require(vk.num_inputs == inputs.length);
return verify_old(proof, vk);
}
function concatBytes(bytes memory param1, bytes memory param2) public pure returns (bytes memory) {
bytes memory merged = new bytes(param1.length + param2.length);
uint k = 0;
for (uint i = 0; i < param1.length; i++) {
merged[k] = param1[i];
k++;
}
for (uint i = 0; i < param2.length; i++) {
merged[k] = param2[i];
k++;
}
return merged;
}
function verifyLpExitProof(
bytes calldata _account_data,
bytes calldata _token_data,
uint256[] calldata _proof
) external view returns (bool) {
bytes memory commit_data = concatBytes(_account_data, _token_data);
bytes32 commitment = sha256(commit_data);
uint256[] memory inputs = new uint256[](1);
inputs[0] = uint256(commitment) & INPUT_MASK;
ProofOld memory proof = deserialize_proof_old(inputs, _proof);
VerificationKeyOld memory vk = getVkExitLp();
require(vk.num_inputs == inputs.length);
return verify_old(proof, vk);
}
}
pragma solidity ^0.7.0;
import './UniswapV2Pair.sol';
import "../IERC20.sol";
/// @author ZKSwap L2 Labs
/// @author Stars Labs
contract UniswapV2Factory {
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
address public zkSyncAddress;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor() {}
function initialize(bytes calldata data) external {}
function setZkSyncAddress(address _zksyncAddress) external {
require(zkSyncAddress == address(0), "szsa1");
zkSyncAddress = _zksyncAddress;
}
/// @notice PairManager contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function allPairsLength() external view returns (uint) {
return allPairs.length;
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address tokenA, address tokenB, bytes32 _salt) external view returns (address pair) {
require(msg.sender == zkSyncAddress, 'fcp2');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1, _salt));
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
address(this),
salt,
keccak256(bytecode)
))));
}
function createPair(address tokenA, address tokenB, bytes32 _salt) external returns (address pair) {
require(msg.sender == zkSyncAddress, 'fcp1');
require(tokenA != tokenB ||
keccak256(abi.encodePacked(IERC20(tokenA).symbol())) == keccak256(abi.encodePacked("EGS")),
'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1, _salt));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
require(zkSyncAddress != address(0), 'wzk');
UniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function mint(address pair, address to, uint256 amount) external {
require(msg.sender == zkSyncAddress, 'fmt1');
UniswapV2Pair(pair).mint(to, amount);
}
function burn(address pair, address to, uint256 amount) external {
require(msg.sender == zkSyncAddress, 'fbr1');
UniswapV2Pair(pair).burn(to, amount);
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./PlonkCore.sol";
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkVerifier is VerifierWithDeserialize {
uint256 constant VK_TREE_ROOT = 0x108678a23c44e8c0b590d3204fa7b710b4e74e590722c4d1f42cd1e6744bf4d3;
uint8 constant VK_MAX_INDEX = 3;
function getVkAggregated(uint32 _proofs) internal pure returns (VerificationKey memory vk) {
if (_proofs == uint32(1)) { return getVkAggregated1(); }
else if (_proofs == uint32(4)) { return getVkAggregated4(); }
else if (_proofs == uint32(8)) { return getVkAggregated8(); }
else if (_proofs == uint32(18)) { return getVkAggregated18(); }
}
function getVkAggregated1() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 4194304;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x18c95f1ae6514e11a1b30fd7923947c5ffcec5347f16e91b4dd654168326bede);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x19fbd6706b4cbde524865701eae0ae6a270608a09c3afdab7760b685c1c6c41b,
0x25082a191f0690c175cc9af1106c6c323b5b5de4e24dc23be1e965e1851bca48
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x16c02d9ca95023d1812a58d16407d1ea065073f02c916290e39242303a8a1d8e,
0x230338b422ce8533e27cd50086c28cb160cf05a7ae34ecd5899dbdf449dc7ce0
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x1db0d133243750e1ea692050bbf6068a49dc9f6bae1f11960b6ce9e10adae0f5,
0x12a453ed0121ae05de60848b4374d54ae4b7127cb307372e14e8daf5097c5123
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x1062ed5e86781fd34f78938e5950c2481a79f132085d2bc7566351ddff9fa3b7,
0x2fd7aac30f645293cc99883ab57d8c99a518d5b4ab40913808045e8653497346
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x062755048bb95739f845e8659795813127283bf799443d62fea600ae23e7f263,
0x2af86098beaa241281c78a454c5d1aa6e9eedc818c96cd1e6518e1ac2d26aa39
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x0994e25148bbd25be655034f81062d1ebf0a1c2b41e0971434beab1ae8101474,
0x27cc8cfb1fafd13068aeee0e08a272577d89f8aa0fb8507aabbc62f37587b98f
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x044edf69ce10cfb6206795f92c3be2b0d26ab9afd3977b789840ee58c7dbe927,
0x2a8aa20c106f8dc7e849bc9698064dcfa9ed0a4050d794a1db0f13b0ee3def37
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x136967f1a2696db05583a58dbf8971c5d9d1dc5f5c97e88f3b4822aa52fefa1c,
0x127b41299ea5c840c3b12dbe7b172380f432b7b63ce3b004750d6abb9e7b3b7a
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x02fd5638bf3cc2901395ad1124b951e474271770a337147a2167e9797ab9d951,
0x0fcb2e56b077c8461c36911c9252008286d782e96030769bf279024fc81d412a
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x1865c60ecad86f81c6c952445707203c9c7fdace3740232ceb704aefd5bd45b3,
0x2f35e29b39ec8bb054e2cff33c0299dd13f8c78ea24a07622128a7444aba3f26
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x2a86ec9c6c1f903650b5abbf0337be556b03f79aecc4d917e90c7db94518dde6,
0x15b1b6be641336eebd58e7991be2991debbbd780e70c32b49225aa98d10b7016
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x213e42fcec5297b8e01a602684fcd412208d15bdac6b6331a8819d478ba46899,
0x03223485f4e808a3b2496ae1a3c0dfbcbf4391cffc57ee01e8fca114636ead18
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x2e9b02f8cf605ad1a36e99e990a07d435de06716448ad53053c7a7a5341f71e1,
0x2d6fdf0bc8bd89112387b1894d6f24b45dcb122c09c84344b6fc77a619dd1d59
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated4() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 8388608;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x1283ba6f4b7b1a76ba2008fe823128bea4adb9269cbfd7c41c223be65bc60863);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x2988e24b15bce9a1e3a4d1d9a8f7c7a65db6c29fd4c6f4afe1a3fbd954d4b4b6,
0x0bdb6e5ba27a22e03270c7c71399b866b28d7cec504d30e665d67be58e306e12
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x20f3d30d3a91a7419d658f8c035e42a811c9f75eac2617e65729033286d36089,
0x07ac91e8194eb78a9db537e9459dd6ca26bef8770dde54ac3dd396450b1d4cfe
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x0311872bab6df6e9095a9afe40b12e2ed58f00cc88835442e6b4cf73fb3e147d,
0x2cdfc5b5e73737809b54644b2f96494f8fcc1dd0fb440f64f44930b432c4542d
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x28fd545b1e960d2eff3142271affa4096ef724212031fdabe22dd4738f36472b,
0x2c743150ee9894ff3965d8f1129399a3b89a1a9289d4cfa904b0a648d3a8a9fa
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x2c283ce950eee1173b78657e57c80658a8398e7970a9a45b20cd39aff16ad61a,
0x081c003cbd09f7c3e0d723d6ebbaf432421c188d5759f5ee8ff1ee1dc357d4a8
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x2eb50a2dd293a71a0c038e958c5237bd7f50b2f0c9ee6385895a553de1517d43,
0x15fdc2b5b28fc351f987b98aa6caec7552cefbafa14e6651061eec4f41993b65
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x17a9403e5c846c1ca5e767c89250113aa156fdb1f026aa0b4db59c09d06816ec,
0x2512241972ca3ee4839ac72a4cab39ddb413a7553556abd7909284b34ee73f6b
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x09edd69c8baa7928b16615e993e3032bc8cbf9f42bfa3cf28caba1078d371edb,
0x12e5c39148af860a87b14ae938f33eafa91deeb548cda4cc23ed9ba3e6e496b8
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x0e25c0027706ca3fd3daae849f7c50ec88d4d030da02452001dec7b554cc71b4,
0x2421da0ca385ff7ba9e5ae68890655669248c8c8187e67d12b2a7ae97e2cff8b
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x151536359fe184567bce57379833f6fae485e5cc9bc27423d83d281aaf2701df,
0x116beb145bc27faae5a8ae30c28040d3baafb3ea47360e528227b94adb9e4f26
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x23ee338093db23364a6e44acfb60d810a4c4bd6565b185374f7840152d3ae82c,
0x0f6714f3ee113b9dfb6b653f04bf497602588b16b96ac682d9a5dd880a0aa601
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x05860b0ea3c6f22150812aee304bf35e1a95cfa569a8da52b42dba44a122378a,
0x19e5a9f3097289272e65e842968752c5355d1cdb2d3d737050e4dfe32ebe1e41
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x3046881fcbe369ac6f99fea8b9505de85ded3de3bc445060be4bc6ef651fa352,
0x06fe14c1dd6c2f2b48aebeb6fd525573d276b2e148ad25e75c57a58588f755ec
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated8() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 16777216;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x1951441010b2b95a6e47a6075066a50a036f5ba978c050f2821df86636c0facb);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x218bdb295b7207114aeea948e2d3baef158d4057812f94005d8ff54341b6ce6f,
0x1398585c039ba3cf336687301e95fbbf6b0638d31c64b1d815bb49091d0c1aad
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x2e40b8a98e688c9e00f607a64520a850d35f277dc0b645628494337bb75870e8,
0x2da4ef753cc4869e53cff171009dbffea9166b8ffbafd17783d712278a79f13e
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x1b638de3c6cc2e0badc48305ee3533678a45f52edf30277303551128772303a2,
0x2794c375cbebb7c28379e8abf42d529a1c291319020099935550c83796ba14ac
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x189cd01d67b44cf2c1e10765c69adaafd6a5929952cf55732e312ecf00166956,
0x15976c99ef2c911bd3a72c9613b7fe9e66b03dd8963bfed705c96e3e88fdb1af
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x0745a77052dc66afc61163ec3737651e5b846ca7ec7fae1853515d0f10a51bd9,
0x2bd27ecf4fb7f5053cc6de3ddb7a969fac5150a6fb5555ca917d16a7836e4c0a
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x2787aea173d07508083893b02ea962be71c3b628d1da7d7c4db0def49f73ad8f,
0x22fdc951a97dc2ac7d8292a6c263898022f4623c643a56b9265b33c72e628886
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x0aafe35c49634858e44e9af259cac47a6f8402eb870f9f95217dcb8a33a73e64,
0x1b47a7641a7c918784e84fc2494bfd8014ebc77069b94650d25cb5e25fbb7003
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x11cfc3fe28dfd5d663d53ceacc5ec620da85ae5aa971f0f003f57e75cd05bf9f,
0x28b325f30984634fc46c6750f402026d4ff43e5325cbe34d35bf8ac4fc9cc533
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x2ada816636b9447def36e35dd3ab0e3f7a8bbe3ae32a5a4904dee3fc26e58015,
0x2cd12d1a50aaadef4e19e1b1955c932e992e688c2883da862bd7fad17aae66f6
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x20cc506f273be4d114cbf2807c14a769d03169168892e2855cdfa78c3095c89d,
0x08f99d338aee985d780d036473c624de9fd7960b2a4a7ad361c8c125cf11899e
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x01260265d3b1167eac1030f3d04326f08a1f2bb1e026e54afec844e3729386e2,
0x16d75b53ec2552c63e84ea5f4bfe1507c3198045875457c1d9295d6699f39d56
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x1f4d73c63d163c3f5ef1b5caa41988cacbdbca38334e8f54d7ee9bbbb622e200,
0x2f48f5f93d9845526ef0348f1c3def63cfc009645eb2a95d1746c7941e888a78
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x1dbd386fe258366222becc570a7f6405b25ff52818b93bdd54eaa20a6b22025a,
0x2b2b4e978ac457d752f50b02609bd7d2054286b963821b2ec7cd3dd1507479fa
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated18() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 33554432;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0d94d63997367c97a8ed16c17adaae39262b9af83acb9e003f94c217303dd160);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x0eab7c0217fbc357eb9e2622da6e5df9a99e5fa8dbaaf6b45a7136bbc49704c0,
0x00199f1c9e2ef5efbec5e3792cb6db0d6211e2da57e2e5a7cf91fb4037bd0013
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x020c5ecdbb37b9f99b131cdfd0fec8c5565985599093db03d85a9bcd75a8a186,
0x0be3b767834382739f1309adedb540ce5261b7038c168d32619a6e6333974b1b
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x092fc8636803f28250ac33b8ea688b37cf0718f83c82a1ce7bca70e7c8643b93,
0x10c907fcb34fb6e9d4e334428e8226ba84e5977a7dc1ada2509cc6cf445123ca
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x1f66b77eaae034cf3646e0c32418a1dfecb3bf090cc271aad0d64ba327758b29,
0x2b8766fbe83c45b39e274998a000cf59e7332800025e7af711368c6b7ea11cd9
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x017336a15f6e61def3ec02f139a0972c4272e126ac40d49ed10d447db6857643,
0x22cc7cb62310a031acd86dd1a9ea18ee55e1b6a4fbf1c2d64ca9a7cc6458ed7a
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x057992ff5d056557b795ab7e6964fab546fdcd8b5c1d3718e4f619e1091ef9a0,
0x026916de04486781c504fb054e0b3755dd4836b610973e0ca092b35810ed3698
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x252a53377145970214c9af5cd95c5fdd72e4d890b96d5ab31ef7736b2280aaa3,
0x2a1ccbea423d1a58325c4d0e5aa01a6a2a7c7fbaa61fb8f3669f720dfb4dfd4d
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x17da1e8102c91916c778e89d737bdc8a14f4dfcf14fc89896f921dfc81e98556,
0x1b9571239471b65bc5d4bcc3b1b3831bcc6986ad4d1417292dc3067ae632b796
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x242b5b8848746eb790629cf0853e256249d83cad8e189d474ed3a5c56b5a92be,
0x2ca4e4882f0d7408ba134458945a2dd7cbced64e735fd42c9204eaf8608c58cc
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x281ccb20cea7001ae0d3ef5deedc46db687f1493cd77631dc2c16275b96f677a,
0x24bede6b53ee4762939dbabb5947023d3ab31b00a1d14bcb6a5da69d7ce0d67e
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x1e72df4c2223fb15e72862350f51994b7f381a829a00b21535b04e8c342c15e7,
0x22b7bb45c2e3b957952824beee1145bfcb5d2c575636266ad44032c1ae24e1ea
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x0059ea736670b355b3b6479db53d9b19727aa128514dee7d6c6788e80233452f,
0x24718998fb0ff667c66457f6558ff028352b2d55cb86a07a0c11fc3c2753df38
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x0bee5ac3770c7603b2ccbc9e10a0ceafa231e77dde3fd6b9d514958ae7c200e8,
0x11339336bbdafda32635c143b7bd0c4cdb7b7948489d75240c89ca2a440ef39c
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkVerifierOld is VerifierWithDeserializeOld {
function getVkExit() internal pure returns(VerificationKeyOld memory vk) {
vk.domain_size = 262144;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x1775efa56023e26c6298b2775481c0add1d64120dd242eb7e66cfebe43a8689d,
0x0adc370e09dc4bfcd73bf48ac1735363d2801dc50b903b950c2259cfec908422
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x1af5b8c0863df35aa93be8f75480bb8c4ad103993c05408856365dce2151cf72,
0x2aa95351d73b68ca33f9a8451cafeca8d9b66b9a5253b1196714d2d55f18c74e
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x1a83514953af1d12f597ae8e159a69efdb4a19bc448f9bc3c100a5d27ab66467,
0x2e739d3240d665dba7ba612ca8548a2817ef3b26a5e31afd66121179860fb367
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x10fdde5088f9df8c2af09166c3e1d2aaf5bedaaf14095a81680285a7ea9a3207,
0x03cb4d015d2c8ab50e6e15c59aaeb0cc6f9dba3731c06513df9c3f77dcc7a75b
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x2e5f67efb618542c634c0cfef443d3ae7d57621fcc487e643d9174b1982ca106,
0x2a7761839026029cb215da80cfe536a4d6f7e993a749e21a0c430a455a6f6477
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x14ee91feb802eea1204e0b4faf96bd000d03e03a253e68f5e44e46880327eaa3,
0x1adfa909fe1008687d3867162b18aa895eed7a5dd10eeeee8d93876f9972f794
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x218b439287375a3f3cc2cad85805b47be7a0c5e8dd43c8c42305f7cb3d153fea,
0x1f94bb4131aee078b207615def18b0f2e94a966ce230fb1837df244657b06b60
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x0dc7db7aea2ef0f5d3b072faeaaee44bb1a79715e977bf87321d210140f4b443,
0x2ceb58346301f008a7553fe2851524e613d8060f309def3239494c2ac4722b99
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x1d4ee99264d715b08b84286e6c979c47446b2cab86f6bb06d937e1d64814a322,
0x2cf40326362bbc1531e3d32e844e2986484ad74fac2b7e5c10bc5375f39dd271
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x20ffb570ec9e40ec87c2df09ec417e301d44db21323e2440134844a0d6aa18cf,
0x2d45d5f1e6fcfed9239d8f464c02a815498261b9a3edec9f4e1cd2058425aa96
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x28f43e5e320de920d29b0eabd68b6b93ea8beb12f35310b96b63ece18b8d99d3,
0x206324d60731845d125e4869c90ae15be2d160886b91bf3c316ac59af0688b6e
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkExitLp() internal pure returns(VerificationKeyOld memory vk) {
vk.domain_size = 262144;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x15a418864253e30d92e0af8f44c45679ab52bb172c65bd1ca649bd352c55eb2f,
0x25d9ce8e852566a5a460653a634708f768f61da8bd3b986ac022cff0067011c2
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x2a7b4444d1b2eaad9dbd93c6bbae7d133fbaf0f71e3e769d35a379e63be37a97,
0x1420d2079a52ce83ee6b498e8a3fa498ec3bd48b92894a17996dfd23fbab90e3
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x17ad336a0139401277e75660ef40b0f07347f6d72d6b143e485953fc896cce9a,
0x227fcdd90c6dfc955c796e544e8bf0ea243e2ce0022e563716a5153260ceea6d
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x2c115c4700fc64f25ac77ba471b1dd5128c439163555331e1078cd6ee5627ba0,
0x2066980b107e6f2fa8160aaa88cb90113d2fd94ad62cd3366848c6746afa6acf
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x256677a67eca0e07a491e652e8e529e9d61e8833a7f90e8c2f1cdb6872260115,
0x0d1f62a5228c35e872a1146944c383d2d2d16dca4e8875bbf70f4d4b8834b6f5
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x1b041e5c782b57147cdfc17aad8b5881ebf895b75cf9d97f45c592f4dcfe640d,
0x01fbc948fd4701103a10bd5fee07fae81481e4f9ca90e36bd12c2ecfb1768b71
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x24d84ac5c820acc4ee6b6062092adc108c640a5750d837b28e5044bf992b45ef,
0x1faacb531160847bb4712202ee2b15a102084c24a2a8da1b687df5de8b2b6dd1
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x28b25ca568d481180c47ff7f7beb6fa426c033c201a140c71cc5bbd090a69474,
0x0bc1b33a8d4a834cdb5b40ba275e2b33089120239abf4f9ffce983d1cfc9a85a
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x11012d815b96d6f9c95a50dd658f45d443472ee0432045f980f2c2745e4c3847,
0x235e2e22940391f97fcedda2690f3265ec813a964f95475f282c0f16602c1fb4
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x2d7bb392ede616e3832f054a5ef35562522585563f1e978cbd3732069bcf4a24,
0x2b97bf5dd09f2765a35f1eeb2936767c20095d03666c1a5948544a74289a51df
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x0c3808600cf3d62ade4d2bb6cb856117f717ccd2a5cd2d549cdae1ad86bbb12b,
0x20827819d88e1dac7cd8f7cd1abce9eff8e9c936dbd305c364f0337298daa5b9
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
pragma solidity >=0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
library PairingsBn254 {
uint256 constant q_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint256 constant bn254_b_coeff = 3;
struct G1Point {
uint256 X;
uint256 Y;
}
struct Fr {
uint256 value;
}
function new_fr(uint256 fr) internal pure returns (Fr memory) {
require(fr < r_mod);
return Fr({value: fr});
}
function copy(Fr memory self) internal pure returns (Fr memory n) {
n.value = self.value;
}
function assign(Fr memory self, Fr memory other) internal pure {
self.value = other.value;
}
function inverse(Fr memory fr) internal view returns (Fr memory) {
require(fr.value != 0);
return pow(fr, r_mod - 2);
}
function add_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, other.value, r_mod);
}
function sub_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, r_mod - other.value, r_mod);
}
function mul_assign(Fr memory self, Fr memory other) internal pure {
self.value = mulmod(self.value, other.value, r_mod);
}
function pow(Fr memory self, uint256 power) internal view returns (Fr memory) {
uint256[6] memory input = [32, 32, 32, self.value, power, r_mod];
uint256[1] memory result;
bool success;
assembly {
success := staticcall(gas(), 0x05, input, 0xc0, result, 0x20)
}
require(success);
return Fr({value: result[0]});
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint256[2] X;
uint256[2] Y;
}
function P1() internal pure returns (G1Point memory) {
return G1Point(1, 2);
}
function new_g1(uint256 x, uint256 y) internal pure returns (G1Point memory) {
return G1Point(x, y);
}
function new_g1_checked(uint256 x, uint256 y) internal pure returns (G1Point memory) {
if (x == 0 && y == 0) {
// point of infinity is (0,0)
return G1Point(x, y);
}
// check encoding
require(x < q_mod);
require(y < q_mod);
// check on curve
uint256 lhs = mulmod(y, y, q_mod); // y^2
uint256 rhs = mulmod(x, x, q_mod); // x^2
rhs = mulmod(rhs, x, q_mod); // x^3
rhs = addmod(rhs, bn254_b_coeff, q_mod); // x^3 + b
require(lhs == rhs);
return G1Point(x, y);
}
function new_g2(uint256[2] memory x, uint256[2] memory y) internal pure returns (G2Point memory) {
return G2Point(x, y);
}
function copy_g1(G1Point memory self) internal pure returns (G1Point memory result) {
result.X = self.X;
result.Y = self.Y;
}
function P2() internal pure returns (G2Point memory) {
// for some reason ethereum expects to have c1*v + c0 form
return
G2Point(
[
0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2,
0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed
],
[
0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b,
0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa
]
);
}
function negate(G1Point memory self) internal pure {
// The prime q in the base field F_q for G1
if (self.Y == 0) {
require(self.X == 0);
return;
}
self.Y = q_mod - self.Y;
}
function point_add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) {
point_add_into_dest(p1, p2, r);
return r;
}
function point_add_assign(G1Point memory p1, G1Point memory p2) internal view {
point_add_into_dest(p1, p2, p1);
}
function point_add_into_dest(
G1Point memory p1,
G1Point memory p2,
G1Point memory dest
) internal view {
if (p2.X == 0 && p2.Y == 0) {
// we add zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we add into zero, and we add non-zero point
dest.X = p2.X;
dest.Y = p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_sub_assign(G1Point memory p1, G1Point memory p2) internal view {
point_sub_into_dest(p1, p2, p1);
}
function point_sub_into_dest(
G1Point memory p1,
G1Point memory p2,
G1Point memory dest
) internal view {
if (p2.X == 0 && p2.Y == 0) {
// we subtracted zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we subtract from zero, and we subtract non-zero point
dest.X = p2.X;
dest.Y = q_mod - p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = q_mod - p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_mul(G1Point memory p, Fr memory s) internal view returns (G1Point memory r) {
point_mul_into_dest(p, s, r);
return r;
}
function point_mul_assign(G1Point memory p, Fr memory s) internal view {
point_mul_into_dest(p, s, p);
}
function point_mul_into_dest(
G1Point memory p,
Fr memory s,
G1Point memory dest
) internal view {
uint256[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s.value;
bool success;
assembly {
success := staticcall(gas(), 7, input, 0x60, dest, 0x40)
}
require(success);
}
function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) {
require(p1.length == p2.length);
uint256 elements = p1.length;
uint256 inputSize = elements * 6;
uint256[] memory input = new uint256[](inputSize);
for (uint256 i = 0; i < elements; i++) {
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint256[1] memory out;
bool success;
assembly {
success := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
}
require(success);
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(
G1Point memory a1,
G2Point memory a2,
G1Point memory b1,
G2Point memory b2
) internal view returns (bool) {
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
}
library TranscriptLibrary {
// flip 0xe000000000000000000000000000000000000000000000000000000000000000;
uint256 constant FR_MASK = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint32 constant DST_0 = 0;
uint32 constant DST_1 = 1;
uint32 constant DST_CHALLENGE = 2;
struct Transcript {
bytes32 state_0;
bytes32 state_1;
uint32 challenge_counter;
}
function new_transcript() internal pure returns (Transcript memory t) {
t.state_0 = bytes32(0);
t.state_1 = bytes32(0);
t.challenge_counter = 0;
}
function update_with_u256(Transcript memory self, uint256 value) internal pure {
bytes32 old_state_0 = self.state_0;
self.state_0 = keccak256(abi.encodePacked(DST_0, old_state_0, self.state_1, value));
self.state_1 = keccak256(abi.encodePacked(DST_1, old_state_0, self.state_1, value));
}
function update_with_fr(Transcript memory self, PairingsBn254.Fr memory value) internal pure {
update_with_u256(self, value.value);
}
function update_with_g1(Transcript memory self, PairingsBn254.G1Point memory p) internal pure {
update_with_u256(self, p.X);
update_with_u256(self, p.Y);
}
function get_challenge(Transcript memory self) internal pure returns (PairingsBn254.Fr memory challenge) {
bytes32 query = keccak256(abi.encodePacked(DST_CHALLENGE, self.state_0, self.state_1, self.challenge_counter));
self.challenge_counter += 1;
challenge = PairingsBn254.Fr({value: uint256(query) & FR_MASK});
}
}
contract Plonk4VerifierWithAccessToDNext {
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant ZERO = 0;
uint256 constant ONE = 1;
uint256 constant TWO = 2;
uint256 constant THREE = 3;
uint256 constant FOUR = 4;
uint256 constant STATE_WIDTH = 4;
uint256 constant NUM_DIFFERENT_GATES = 2;
uint256 constant NUM_SETUP_POLYS_FOR_MAIN_GATE = 7;
uint256 constant NUM_SETUP_POLYS_RANGE_CHECK_GATE = 0;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1;
uint256 constant NUM_GATE_SELECTORS_OPENED_EXPLICITLY = 1;
uint256 constant RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK =
0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant LIMB_WIDTH = 68;
struct VerificationKey {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[NUM_SETUP_POLYS_FOR_MAIN_GATE + NUM_SETUP_POLYS_RANGE_CHECK_GATE] gate_setup_commitments;
PairingsBn254.G1Point[NUM_DIFFERENT_GATES] gate_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH] copy_permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH - 1] copy_permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct Proof {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH] wire_commitments;
PairingsBn254.G1Point copy_permutation_grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega;
PairingsBn254.Fr[NUM_GATE_SELECTORS_OPENED_EXPLICITLY] gate_selector_values_at_z;
PairingsBn254.Fr copy_grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH - 1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierState {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function batch_evaluate_lagrange_poly_out_of_domain(
uint256[] memory poly_nums,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr[] memory res) {
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size);
PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size);
vanishing_at_z.sub_assign(one);
// we can not have random point z be in domain
require(vanishing_at_z.value != 0);
PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length);
PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length);
// numerators in a form omega^i * (z^n - 1)
// denoms in a form (z - omega^i) * N
for (uint256 i = 0; i < poly_nums.length; i++) {
tmp_1 = omega.pow(poly_nums[i]); // power of omega
nums[i].assign(vanishing_at_z);
nums[i].mul_assign(tmp_1);
dens[i].assign(at); // (X - omega^i) * N
dens[i].sub_assign(tmp_1);
dens[i].mul_assign(tmp_2); // mul by domain size
}
PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length);
partial_products[0].assign(PairingsBn254.new_fr(1));
for (uint256 i = 1; i < dens.length ; i++) {
partial_products[i].assign(dens[i - 1]);
partial_products[i].mul_assign(partial_products[i-1]);
}
tmp_2.assign(partial_products[partial_products.length - 1]);
tmp_2.mul_assign(dens[dens.length - 1]);
tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one)
for (uint256 i = dens.length - 1; i < dens.length; i--) {
tmp_1.assign(tmp_2); // all inversed
tmp_1.mul_assign(partial_products[i]); // clear lowest terms
tmp_2.mul_assign(dens[i]);
dens[i].assign(tmp_1);
}
for (uint256 i = 0; i < nums.length; i++) {
nums[i].mul_assign(dens[i]);
}
return nums;
}
function evaluate_vanishing(uint256 domain_size, PairingsBn254.Fr memory at)
internal
view
returns (PairingsBn254.Fr memory res)
{
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
inputs_term.add_assign(tmp);
}
inputs_term.mul_assign(proof.gate_selector_values_at_z[0]);
rhs.add_assign(inputs_term);
// now we need 5th power
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function add_contribution_from_range_constraint_gates(
PartialVerifierState memory state,
Proof memory proof,
PairingsBn254.Fr memory current_alpha
) internal pure returns (PairingsBn254.Fr memory res) {
// now add contribution from range constraint gate
// we multiply selector commitment by all the factors (alpha*(c - 4d)(c - 4d - 1)(..-2)(..-3) + alpha^2 * (4b - c)()()() + {} + {})
PairingsBn254.Fr memory one_fr = PairingsBn254.new_fr(ONE);
PairingsBn254.Fr memory two_fr = PairingsBn254.new_fr(TWO);
PairingsBn254.Fr memory three_fr = PairingsBn254.new_fr(THREE);
PairingsBn254.Fr memory four_fr = PairingsBn254.new_fr(FOUR);
res = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t0 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t2 = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < 3; i++) {
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[3 - i]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
}
// now also d_next - 4a
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[0]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z_omega[0]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
return res;
}
function reconstruct_linearization_commitment(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^{6} * (selector(x) - selector(z))
// + v^{7..9} * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^10 (z(x) - z(z*omega)) <- we need this power
// + v^11 * (d(x) - d(z*omega))
// ]
//
// we reconstruct linearization polynomial virtual selector
// for that purpose we first linearize over main gate (over all it's selectors)
// and multiply them by value(!) of the corresponding main gate selector
res = PairingsBn254.copy_g1(vk.gate_setup_commitments[STATE_WIDTH + 1]); // index of q_const(x)
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH; i++) {
tmp_g1 = vk.gate_setup_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH + 2].point_mul(proof.wire_values_at_z_omega[0]); // index of q_d_next(x)
res.point_add_assign(tmp_g1);
// multiply by main gate selector(z)
res.point_mul_assign(proof.gate_selector_values_at_z[0]); // these is only one explicitly opened selector
PairingsBn254.Fr memory current_alpha = PairingsBn254.new_fr(ONE);
// calculate scalar contribution from the range check gate
tmp_fr = add_contribution_from_range_constraint_gates(state, proof, current_alpha);
tmp_g1 = vk.gate_selector_commitments[1].point_mul(tmp_fr); // selector commitment for range constraint gate * scalar
res.point_add_assign(tmp_g1);
// proceed as normal to copy permutation
current_alpha.mul_assign(state.alpha); // alpha^5
PairingsBn254.Fr memory alpha_for_grand_product = PairingsBn254.copy(current_alpha);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.copy_permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.copy_permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i + 1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(alpha_for_grand_product);
// alpha^n & L_{0}(z), and we bump current_alpha
current_alpha.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(current_alpha);
grand_product_part_at_z.add_assign(tmp_fr);
// prefactor for grand_product(x) is complete
// add to the linearization a part from the term
// - (a(z) + beta*perm_a + gamma)*()*()*z(z*omega) * beta * perm_d(X)
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.copy_grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(alpha_for_grand_product); // we multiply by the power of alpha from the argument
// actually multiply prefactors by z(x) and perm_d(x) and combine them
tmp_g1 = proof.copy_permutation_grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.copy_permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
// multiply them by v immedately as linearization has a factor of v^1
res.point_mul_assign(state.v);
// res now contains contribution from the gates linearization and
// copy permutation part
// now we need to add a part that is the rest
// for z(x*omega):
// - (a(z) + beta*perm_a + gamma)*()*()*(d(z) + gamma) * z(x*omega)
}
function aggregate_commitments(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point[2] memory res) {
PairingsBn254.G1Point memory d = reconstruct_linearization_commitment(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.gate_selector_commitments[0].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < vk.copy_permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.copy_permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
// now do prefactor for grand_product(x*omega)
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
commitment_aggregation.point_add_assign(proof.copy_permutation_grand_product_commitment.point_mul(tmp_fr));
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.gate_selector_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.copy_grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
res[0] = pair_with_generator;
res[1] = pair_with_x;
return res;
}
function verify_initial(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs >= 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.copy_permutation_grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs);
for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) {
lagrange_poly_numbers[i] = i;
}
state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain(
lagrange_poly_numbers,
vk.domain_size,
vk.omega,
state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
transcript.update_with_fr(proof.gate_selector_values_at_z[0]);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.copy_grand_product_at_z_omega);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function aggregate_for_verification(Proof memory proof, VerificationKey memory vk)
internal
view
returns (bool valid, PairingsBn254.G1Point[2] memory part)
{
PartialVerifierState memory state;
valid = verify_initial(state, proof, vk);
if (valid == false) {
return (valid, part);
}
part = aggregate_commitments(state, proof, vk);
(valid, part);
}
function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) {
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
valid = PairingsBn254.pairingProd2(
recursive_proof_part[0],
PairingsBn254.P2(),
recursive_proof_part[1],
vk.g2_x
);
return valid;
}
function verify_recursive(
Proof memory proof,
VerificationKey memory vk,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_limbs
) internal view returns (bool) {
(uint256 recursive_input, PairingsBn254.G1Point[2] memory aggregated_g1s) =
reconstruct_recursive_public_input(
recursive_vks_root,
max_valid_index,
recursive_vks_indexes,
individual_vks_inputs,
subproofs_limbs
);
assert(recursive_input == proof.input_values[0]);
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
// aggregated_g1s = inner
// recursive_proof_part = outer
PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part);
valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x);
return valid;
}
function combine_inner_and_outer(PairingsBn254.G1Point[2] memory inner, PairingsBn254.G1Point[2] memory outer)
internal
view
returns (PairingsBn254.G1Point[2] memory result)
{
// reuse the transcript primitive
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
transcript.update_with_g1(inner[0]);
transcript.update_with_g1(inner[1]);
transcript.update_with_g1(outer[0]);
transcript.update_with_g1(outer[1]);
PairingsBn254.Fr memory challenge = transcript.get_challenge();
// 1 * inner + challenge * outer
result[0] = PairingsBn254.copy_g1(inner[0]);
result[1] = PairingsBn254.copy_g1(inner[1]);
PairingsBn254.G1Point memory tmp = outer[0].point_mul(challenge);
result[0].point_add_assign(tmp);
tmp = outer[1].point_mul(challenge);
result[1].point_add_assign(tmp);
return result;
}
function reconstruct_recursive_public_input(
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_aggregated
) internal pure returns (uint256 recursive_input, PairingsBn254.G1Point[2] memory reconstructed_g1s) {
assert(recursive_vks_indexes.length == individual_vks_inputs.length);
bytes memory concatenated = abi.encodePacked(recursive_vks_root);
uint8 index;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
index = recursive_vks_indexes[i];
assert(index <= max_valid_index);
concatenated = abi.encodePacked(concatenated, index);
}
uint256 input;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
input = individual_vks_inputs[i];
assert(input < r_mod);
concatenated = abi.encodePacked(concatenated, input);
}
concatenated = abi.encodePacked(concatenated, subproofs_aggregated);
bytes32 commitment = sha256(concatenated);
recursive_input = uint256(commitment) & RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK;
reconstructed_g1s[0] = PairingsBn254.new_g1_checked(
subproofs_aggregated[0] +
(subproofs_aggregated[1] << LIMB_WIDTH) +
(subproofs_aggregated[2] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[3] << (3 * LIMB_WIDTH)),
subproofs_aggregated[4] +
(subproofs_aggregated[5] << LIMB_WIDTH) +
(subproofs_aggregated[6] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[7] << (3 * LIMB_WIDTH))
);
reconstructed_g1s[1] = PairingsBn254.new_g1_checked(
subproofs_aggregated[8] +
(subproofs_aggregated[9] << LIMB_WIDTH) +
(subproofs_aggregated[10] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[11] << (3 * LIMB_WIDTH)),
subproofs_aggregated[12] +
(subproofs_aggregated[13] << LIMB_WIDTH) +
(subproofs_aggregated[14] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[15] << (3 * LIMB_WIDTH))
);
return (recursive_input, reconstructed_g1s);
}
}
contract VerifierWithDeserialize is Plonk4VerifierWithAccessToDNext {
uint256 constant SERIALIZED_PROOF_LENGTH = 34;
function deserialize_proof(uint256[] memory public_inputs, uint256[] memory serialized_proof)
internal
pure
returns (Proof memory proof)
{
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
}
proof.copy_permutation_grand_product_commitment = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) {
proof.gate_selector_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.copy_grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
}
function verify_serialized_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid = verify(proof, vk);
return valid;
}
function verify_serialized_proof_with_recursion(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_limbs,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid =
verify_recursive(
proof,
vk,
recursive_vks_root,
max_valid_index,
recursive_vks_indexes,
individual_vks_inputs,
subproofs_limbs
);
return valid;
}
}
contract Plonk4VerifierWithAccessToDNextOld {
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant STATE_WIDTH_OLD = 4;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD = 1;
struct VerificationKeyOld {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[STATE_WIDTH_OLD + 2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant
PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] next_step_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH_OLD] permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct ProofOld {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH_OLD] wire_commitments;
PairingsBn254.G1Point grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH_OLD] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH_OLD] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] wire_values_at_z_omega;
PairingsBn254.Fr grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierStateOld {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain_old(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function batch_evaluate_lagrange_poly_out_of_domain_old(
uint256[] memory poly_nums,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr[] memory res) {
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size);
PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size);
vanishing_at_z.sub_assign(one);
// we can not have random point z be in domain
require(vanishing_at_z.value != 0);
PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length);
PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length);
// numerators in a form omega^i * (z^n - 1)
// denoms in a form (z - omega^i) * N
for (uint256 i = 0; i < poly_nums.length; i++) {
tmp_1 = omega.pow(poly_nums[i]); // power of omega
nums[i].assign(vanishing_at_z);
nums[i].mul_assign(tmp_1);
dens[i].assign(at); // (X - omega^i) * N
dens[i].sub_assign(tmp_1);
dens[i].mul_assign(tmp_2); // mul by domain size
}
PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length);
partial_products[0].assign(PairingsBn254.new_fr(1));
for (uint256 i = 1; i < dens.length ; i++) {
partial_products[i].assign(dens[i - 1]);
partial_products[i].mul_assign(partial_products[i-1]);
}
tmp_2.assign(partial_products[partial_products.length - 1]);
tmp_2.mul_assign(dens[dens.length - 1]);
tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one)
for (uint256 i = dens.length - 1; i < dens.length; i--) {
tmp_1.assign(tmp_2); // all inversed
tmp_1.mul_assign(partial_products[i]); // clear lowest terms
tmp_2.mul_assign(dens[i]);
dens[i].assign(tmp_1);
}
for (uint256 i = 0; i < nums.length; i++) {
nums[i].mul_assign(dens[i]);
}
return nums;
}
function evaluate_vanishing_old(uint256 domain_size, PairingsBn254.Fr memory at)
internal
view
returns (PairingsBn254.Fr memory res)
{
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing_old(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
rhs.add_assign(tmp);
}
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH_OLD - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function reconstruct_d(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^(6..8) * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^9 (z(x) - z(z*omega)) <- we need this power
// + v^10 * (d(x) - d(z*omega))
// ]
//
// we pay a little for a few arithmetic operations to not introduce another constant
uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH_OLD + STATE_WIDTH_OLD - 1;
res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH_OLD + 1]);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.selector_commitments[STATE_WIDTH_OLD].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.next_step_selector_commitments[0].point_mul(proof.wire_values_at_z_omega[0]);
res.point_add_assign(tmp_g1);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i + 1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(state.alpha);
tmp_fr.mul_assign(state.alpha);
grand_product_part_at_z.add_assign(tmp_fr);
PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening);
grand_product_part_at_z_omega.mul_assign(state.u);
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(state.alpha);
// add to the linearization
tmp_g1 = proof.grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH_OLD - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
res.point_mul_assign(state.v);
res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega));
}
function verify_commitments(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
PairingsBn254.G1Point memory d = reconstruct_d(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < vk.permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH_OLD - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
return PairingsBn254.pairingProd2(pair_with_generator, PairingsBn254.P2(), pair_with_x, vk.g2_x);
}
function verify_initial(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs >= 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs);
for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) {
lagrange_poly_numbers[i] = i;
}
state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain_old(
lagrange_poly_numbers,
vk.domain_size,
vk.omega,
state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
transcript.update_with_fr(proof.grand_product_at_z_omega);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function verify_old(ProofOld memory proof, VerificationKeyOld memory vk) internal view returns (bool) {
PartialVerifierStateOld memory state;
bool valid = verify_initial(state, proof, vk);
if (valid == false) {
return false;
}
valid = verify_commitments(state, proof, vk);
return valid;
}
}
contract VerifierWithDeserializeOld is Plonk4VerifierWithAccessToDNextOld {
uint256 constant SERIALIZED_PROOF_LENGTH_OLD = 33;
function deserialize_proof_old(uint256[] memory public_inputs, uint256[] memory serialized_proof)
internal
pure
returns (ProofOld memory proof)
{
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH_OLD);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
}
proof.grand_product_commitment = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
}
}
pragma solidity ^0.7.0;
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
contract UniswapV2Pair is UniswapV2ERC20 {
using UniswapSafeMath for uint;
using UQ112x112 for uint224;
address public factory;
address public token0;
address public token1;
uint256 private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
constructor() {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
function mint(address to, uint256 amount) external lock {
require(msg.sender == factory, 'mt1');
_mint(to, amount);
}
function burn(address to, uint256 amount) external lock {
require(msg.sender == factory, 'br1');
_burn(to, amount);
}
}
pragma solidity ^0.7.0;
import './libraries/UniswapSafeMath.sol';
contract UniswapV2ERC20 {
using UniswapSafeMath for uint;
string public constant name = 'EdgeSwap V1';
string public constant symbol = 'Edge-V1';
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint256 value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint256 value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) external returns (bool) {
if (allowance[from][msg.sender] != uint256(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
}
pragma solidity ^0.7.0;
// a library for performing various math operations
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
pragma solidity ^0.7.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
pragma solidity ^0.7.0;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library UniswapSafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Interface of the upgradeable contract
/// @author Matter Labs
interface Upgradeable {
/// @notice Upgrades target of upgradeable contract
/// @param newTarget New target
/// @param newTargetInitializationParameters New target initialization parameters
function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external;
}
|
Interface of the ERC20 standard as defined in the EIP. Does not include the optional functions; to access them see {ERC20Detailed}./
|
interface IERC20 {
function symbol() external pure returns (string memory);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 72,361 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "../interfaces/IStrategy.sol";
import "../interfaces/IVault.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
abstract contract ReaperBaseStrategy is
IStrategy,
UUPSUpgradeable,
AccessControlEnumerableUpgradeable,
PausableUpgradeable
{
uint256 public constant PERCENT_DIVISOR = 10_000;
uint256 public constant ONE_YEAR = 365 days;
uint256 public constant UPGRADE_TIMELOCK = 1 hours; // minimum 48 hours for RF
struct Harvest {
uint256 timestamp;
uint256 vaultSharePrice;
}
Harvest[] public harvestLog;
uint256 public harvestLogCadence;
uint256 public lastHarvestTimestamp;
/**
* Reaper Roles
*/
bytes32 public constant STRATEGIST = keccak256("STRATEGIST");
bytes32 public constant STRATEGIST_MULTISIG = keccak256("STRATEGIST_MULTISIG");
/**
* @dev Reaper contracts:
* {treasury} - Address of the Reaper treasury
* {vault} - Address of the vault that controls the strategy's funds.
* {strategistRemitter} - Address where strategist fee is remitted to.
*/
address public treasury;
address public vault;
address public strategistRemitter;
/**
* Fee related constants:
* {MAX_FEE} - Maximum fee allowed by the strategy. Hard-capped at 10%.
* {STRATEGIST_MAX_FEE} - Maximum strategist fee allowed by the strategy (as % of treasury fee).
* Hard-capped at 50%
* {MAX_SECURITY_FEE} - Maximum security fee charged on withdrawal to prevent
* flash deposit/harvest attacks.
*/
uint256 public constant MAX_FEE = 1000;
uint256 public constant STRATEGIST_MAX_FEE = 5000;
uint256 public constant MAX_SECURITY_FEE = 10;
/**
* @dev Distribution of fees earned, expressed as % of the profit from each harvest.
* {totalFee} - divided by 10,000 to determine the % fee. Set to 4.5% by default and
* lowered as necessary to provide users with the most competitive APY.
*
* {callFee} - Percent of the totalFee reserved for the harvester (1000 = 10% of total fee: 0.45% by default)
* {treasuryFee} - Percent of the totalFee taken by maintainers of the software (9000 = 90% of total fee: 4.05% by default)
* {strategistFee} - Percent of the treasuryFee taken by strategist (2500 = 25% of treasury fee: 1.0125% by default)
*
* {securityFee} - Fee taxed when a user withdraws funds. Taken to prevent flash deposit/harvest attacks.
* These funds are redistributed to stakers in the pool.
*/
uint256 public totalFee;
uint256 public callFee;
uint256 public treasuryFee;
uint256 public strategistFee;
uint256 public securityFee;
/**
* {TotalFeeUpdated} Event that is fired each time the total fee is updated.
* {FeesUpdated} Event that is fired each time callFee+treasuryFee+strategistFee are updated.
* {StratHarvest} Event that is fired each time the strategy gets harvested.
* {StrategistRemitterUpdated} Event that is fired each time the strategistRemitter address is updated.
*/
event TotalFeeUpdated(uint256 newFee);
event FeesUpdated(uint256 newCallFee, uint256 newTreasuryFee, uint256 newStrategistFee);
event StratHarvest(address indexed harvester);
event StrategistRemitterUpdated(address newStrategistRemitter);
uint256 public upgradeProposalTime;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function __ReaperBaseStrategy_init(
address _vault,
address[] memory _feeRemitters,
address[] memory _strategists
) internal onlyInitializing {
__UUPSUpgradeable_init();
__AccessControlEnumerable_init();
__Pausable_init_unchained();
harvestLogCadence = 1 hours;
totalFee = 450;
callFee = 1000;
treasuryFee = 9000;
strategistFee = 2500;
securityFee = 10;
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
clearUpgradeCooldown();
vault = _vault;
treasury = _feeRemitters[0];
strategistRemitter = _feeRemitters[1];
for (uint256 i = 0; i < _strategists.length; i++) {
_grantRole(STRATEGIST, _strategists[i]);
}
harvestLog.push(Harvest({timestamp: block.timestamp, vaultSharePrice: IVault(_vault).getPricePerFullShare()}));
}
/**
* @dev harvest() function that takes care of logging. Subcontracts should
* override _harvestCore() and implement their specific logic in it.
*/
function harvest() external override whenNotPaused {
_harvestCore();
if (block.timestamp >= harvestLog[harvestLog.length - 1].timestamp + harvestLogCadence) {
harvestLog.push(
Harvest({timestamp: block.timestamp, vaultSharePrice: IVault(vault).getPricePerFullShare()})
);
}
lastHarvestTimestamp = block.timestamp;
emit StratHarvest(msg.sender);
}
function harvestLogLength() external view returns (uint256) {
return harvestLog.length;
}
/**
* @dev Returns a slice of the harvest log containing the _n latest harvests.
*/
function latestHarvestLogSlice(uint256 _n) external view returns (Harvest[] memory slice) {
slice = new Harvest[](_n);
uint256 sliceCounter = 0;
for (uint256 i = harvestLog.length - _n; i < harvestLog.length; i++) {
slice[sliceCounter++] = harvestLog[i];
}
}
/**
* @dev Traverses the harvest log backwards until it hits _timestamp,
* and returns the average APR calculated across all the included
* log entries. APR is multiplied by PERCENT_DIVISOR to retain precision.
*/
function averageAPRSince(uint256 _timestamp) external view returns (int256) {
require(harvestLog.length >= 2, "need at least 2 log entries");
int256 runningAPRSum;
int256 numLogsProcessed;
for (uint256 i = harvestLog.length - 1; i > 0 && harvestLog[i].timestamp >= _timestamp; i--) {
runningAPRSum += calculateAPRUsingLogs(i - 1, i);
numLogsProcessed++;
}
return runningAPRSum / numLogsProcessed;
}
/**
* @dev Traverses the harvest log backwards _n items,
* and returns the average APR calculated across all the included
* log entries. APR is multiplied by PERCENT_DIVISOR to retain precision.
*/
function averageAPRAcrossLastNHarvests(int256 _n) external view returns (int256) {
require(harvestLog.length >= 2, "need at least 2 log entries");
int256 runningAPRSum;
int256 numLogsProcessed;
for (uint256 i = harvestLog.length - 1; i > 0 && numLogsProcessed < _n; i--) {
runningAPRSum += calculateAPRUsingLogs(i - 1, i);
numLogsProcessed++;
}
return runningAPRSum / numLogsProcessed;
}
/**
* @dev Only strategist or owner can edit the log cadence.
*/
function updateHarvestLogCadence(uint256 _newCadenceInSeconds) external {
_onlyStrategistOrOwner();
harvestLogCadence = _newCadenceInSeconds;
}
/**
* @dev updates the total fee, capped at 5%; only owner.
*/
function updateTotalFee(uint256 _totalFee) external override onlyRole(DEFAULT_ADMIN_ROLE) {
require(_totalFee <= MAX_FEE, "Fee Too High");
totalFee = _totalFee;
emit TotalFeeUpdated(totalFee);
}
/**
* @dev updates the call fee, treasury fee, and strategist fee
* call Fee + treasury Fee must add up to PERCENT_DIVISOR
*
* strategist fee is expressed as % of the treasury fee and
* must be no more than STRATEGIST_MAX_FEE
*
* only owner
*/
function updateFees(
uint256 _callFee,
uint256 _treasuryFee,
uint256 _strategistFee
) external onlyRole(DEFAULT_ADMIN_ROLE) returns (bool) {
require(_callFee + _treasuryFee == PERCENT_DIVISOR, "sum != PERCENT_DIVISOR");
require(_strategistFee <= STRATEGIST_MAX_FEE, "strategist fee > STRATEGIST_MAX_FEE");
callFee = _callFee;
treasuryFee = _treasuryFee;
strategistFee = _strategistFee;
emit FeesUpdated(callFee, treasuryFee, strategistFee);
return true;
}
function updateSecurityFee(uint256 _securityFee) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_securityFee <= MAX_SECURITY_FEE, "fee to high!");
securityFee = _securityFee;
}
/**
* @dev only owner can update treasury address.
*/
function updateTreasury(address newTreasury) external onlyRole(DEFAULT_ADMIN_ROLE) returns (bool) {
treasury = newTreasury;
return true;
}
/**
* @dev Updates the current strategistRemitter.
* If there is only one strategist this function may be called by
* that strategist. However if there are multiple strategists
* this function may only be called by the STRATEGIST_MULTISIG role.
*/
function updateStrategistRemitter(address _newStrategistRemitter) external {
if (getRoleMemberCount(STRATEGIST) == 1) {
_checkRole(STRATEGIST, msg.sender);
} else {
_checkRole(STRATEGIST_MULTISIG, msg.sender);
}
require(_newStrategistRemitter != address(0), "!0");
strategistRemitter = _newStrategistRemitter;
emit StrategistRemitterUpdated(_newStrategistRemitter);
}
/**
* @dev DEFAULT_ADMIN_ROLE must call this function prior to upgrading the implementation
* and wait UPGRADE_TIMELOCK seconds before executing the upgrade.
*/
function initiateUpgradeCooldown() external onlyRole(DEFAULT_ADMIN_ROLE) {
upgradeProposalTime = block.timestamp;
}
/**
* @dev This function is called:
* - in initialize()
* - as part of a successful upgrade
* - manually by DEFAULT_ADMIN_ROLE to clear the upgrade cooldown.
*/
function clearUpgradeCooldown() public onlyRole(DEFAULT_ADMIN_ROLE) {
upgradeProposalTime = block.timestamp + (ONE_YEAR * 100);
}
/**
* @dev Only allow access to strategist or owner
*/
function _onlyStrategistOrOwner() internal view {
require(hasRole(STRATEGIST, msg.sender) || hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized");
}
function calculateAPRUsingLogs(uint256 _startIndex, uint256 _endIndex) public view returns (int256) {
Harvest storage start = harvestLog[_startIndex];
Harvest storage end = harvestLog[_endIndex];
bool increasing = true;
if (end.vaultSharePrice < start.vaultSharePrice) {
increasing = false;
}
uint256 unsignedSharePriceChange;
if (increasing) {
unsignedSharePriceChange = end.vaultSharePrice - start.vaultSharePrice;
} else {
unsignedSharePriceChange = start.vaultSharePrice - end.vaultSharePrice;
}
uint256 unsignedPercentageChange = (unsignedSharePriceChange * 1e18) / start.vaultSharePrice;
uint256 timeDifference = end.timestamp - start.timestamp;
uint256 yearlyUnsignedPercentageChange = (unsignedPercentageChange * ONE_YEAR) / timeDifference;
yearlyUnsignedPercentageChange /= 1e14; // restore basis points precision
if (increasing) {
return int256(yearlyUnsignedPercentageChange);
}
return -int256(yearlyUnsignedPercentageChange);
}
/**
* @dev Returns the approx amount of profit from harvesting plus fee that
* would be returned to harvest caller.
*/
function estimateHarvest() external view virtual returns (uint256 profit, uint256 callFeeToUser);
function balanceOf() public view virtual override returns (uint256);
/**
* @dev subclasses should add their custom harvesting logic in this function
* including charging any fees.
*/
function _harvestCore() internal virtual;
/**
* @dev This function must be overriden simply for access control purposes.
* Only DEFAULT_ADMIN_ROLE can upgrade the implementation once the timelock
* has passed.
*/
function _authorizeUpgrade(address) internal override onlyRole(DEFAULT_ADMIN_ROLE) {
require(upgradeProposalTime + UPGRADE_TIMELOCK < block.timestamp, "cooldown not initiated or still active");
clearUpgradeCooldown();
}
}
|
harvest() function that takes care of logging. Subcontracts should override _harvestCore() and implement their specific logic in it./
|
function harvest() external override whenNotPaused {
_harvestCore();
if (block.timestamp >= harvestLog[harvestLog.length - 1].timestamp + harvestLogCadence) {
harvestLog.push(
);
}
lastHarvestTimestamp = block.timestamp;
emit StratHarvest(msg.sender);
}
| 6,344,748 |
./partial_match/4/0xF559B56a101f3120CB811E571a8c1fA77F640015/sources/LexLocker.sol
|
get total resolutions passed by LXL `resolver`s
|
function resolutionCount() external view returns (uint256) {
| 8,601,420 |
./full_match/1/0x51aD7fE22a4a7Cef856F655cd2FF8E1D492fB8b0/sources/src/contracts/onft/OmniseaUniversalONFT721.sol
|
not enough gas to complete transfers, store to be cleared in another tx
|
function _nonblockingLzReceive(
uint16 _srcChainId,
bytes memory _srcAddress,
uint64, /*_nonce*/
bytes memory _payload
) internal virtual override {
(bytes memory toAddressBytes, uint[] memory tokenIds, BasicCollectionParams memory _collectionParams, bytes32 _collectionId) = abi.decode(_payload, (bytes, uint[], BasicCollectionParams, bytes32));
address toAddress;
assembly {
toAddress := mload(add(toAddressBytes, 20))
}
address collection = idToCollection[_collectionId];
if (collection == address(0)) {
OmniseaERC721Proxy proxy = new OmniseaERC721Proxy();
collection = address(proxy);
IOmniseaRemoteERC721(collection).initialize(_collectionParams);
idToCollection[_collectionId] = collection;
collectionToId[collection] = _collectionId;
}
uint nextIndex = _creditTill(_srcChainId, collection, toAddress, 0, tokenIds);
if (nextIndex < tokenIds.length) {
bytes32 hashedPayload = keccak256(_payload);
storedCredits[hashedPayload] = StoredCredit(_srcChainId, collection, toAddress, nextIndex, true);
emit CreditStored(hashedPayload, _payload);
}
emit ReceiveFromChain(_srcChainId, _srcAddress, toAddress, tokenIds);
}
| 17,045,295 |
./full_match/5/0x295193366E9dA65fB198A3c88AE01BF64E284AAc/sources/contracts/CrowdFunding.sol
|
is everything okay?
|
function createCampaign(address _owner, string memory _title, string memory _description,
uint256 _target, uint256 _deadline, string memory _image) public returns (uint256) {
Campaign storage campaign = campaigns[numberOfCampaigns];
require(campaign.deadline < block.timestamp, "The deadline should be a date in the future.");
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
numberOfCampaigns++;
return numberOfCampaigns - 1;
}
| 1,958,089 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
library EnumerableCardNFT {
struct CardEntry {
bytes32 _tokenId;
uint256 _star;
// 剩余粉尘
uint256 _tokenVal;
uint256[] _cardType;
// 词条
uint256[] _cardEntrys;
string _uri;
address _ownerAddress;
}
struct CardMap {
// Storage of map keys and values
CardEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
function _all(CardMap storage map) private view returns (uint256[] memory) {
uint256[] memory tokenIds = new uint256[](map._entries.length);
for (uint256 i = 0; i < map._entries.length; ++i) {
tokenIds[i] = uint256(map._entries[i]._tokenId);
}
return tokenIds;
}
/**
* @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(
CardMap storage map,
bytes32 tokenId,
uint256 star,
// 剩余粉尘
uint256 tokenVal,
uint256[] memory cardType,
// 词条
uint256[] memory cardEntrys,
string memory uri,
address ownerAddress
) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[tokenId];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map._entries.push(
CardEntry({
_tokenId: tokenId,
_star: star,
_tokenVal: tokenVal,
_cardType: cardType,
_cardEntrys: cardEntrys,
_uri: uri,
_ownerAddress: ownerAddress
})
);
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[tokenId] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._tokenId = tokenId;
map._entries[keyIndex - 1]._star = star;
map._entries[keyIndex - 1]._tokenVal = tokenVal;
map._entries[keyIndex - 1]._cardType = cardType;
map._entries[keyIndex - 1]._cardEntrys = cardEntrys;
map._entries[keyIndex - 1]._uri = uri;
map._entries[keyIndex - 1]._ownerAddress = ownerAddress;
return false;
}
}
function _setTokenTo(
CardMap storage map,
bytes32 tokenId,
address ownerAddress
) private returns (bool) {
uint256 keyIndex = map._indexes[tokenId];
if (keyIndex == 0) {
return false;
}
map._entries[keyIndex - 1]._ownerAddress = ownerAddress;
return true;
}
/**
* @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(CardMap storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
CardEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._tokenId] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(CardMap storage map, bytes32 key)
private
view
returns (bool)
{
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(CardMap storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(CardMap storage map, uint256 index)
private
view
returns (
bytes32,
uint256,
uint256,
uint256[] memory,
uint256[] memory,
string memory,
address
)
{
require(
map._entries.length > index,
"EnumerableMap: index out of bounds"
);
CardEntry storage entry = map._entries[index];
return (
entry._tokenId,
entry._star,
entry._tokenVal,
entry._cardType,
entry._cardEntrys,
entry._uri,
entry._ownerAddress
);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(CardMap storage map, bytes32 tokenId)
private
view
returns (CardEntry memory)
{
return _get(map, tokenId, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(
CardMap storage map,
bytes32 tokenId,
string memory errorMessage
) private view returns (CardEntry memory) {
uint256 keyIndex = map._indexes[tokenId];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _getOwnerAddress(
CardMap storage map,
bytes32 tokenId,
string memory errorMessage
) private view returns (address) {
uint256 keyIndex = map._indexes[tokenId];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return (map._entries[keyIndex - 1]._ownerAddress); // All indexes are 1-based
}
// UintToAddressMap
// 主要的数据存储
struct UintToAddressMap {
CardMap _inner;
}
function setTokenTo(
UintToAddressMap storage map,
uint256 tokenId,
address toOwner
) internal returns (bool) {
return _setTokenTo(map._inner, bytes32(tokenId), toOwner);
}
/**
* @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 tokenId,
uint256 star,
// 剩余粉尘
uint256 tokenVal,
uint256[] memory cardType,
// 词条
uint256[] memory cardEntrys,
string memory uri,
address owner
) internal returns (bool) {
return
_set(
map._inner,
bytes32(tokenId),
star,
tokenVal,
cardType,
cardEntrys,
uri,
owner
);
}
/**
* @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 tokenId)
internal
returns (bool)
{
return _remove(map._inner, bytes32(tokenId));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 tokenId)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(tokenId));
}
/**
* @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,
uint256,
uint256,
uint256[] memory,
uint256[] memory,
string memory,
address
)
{
(
bytes32 _tokenId,
uint256 _star,
// 剩余粉尘
uint256 _tokenVal,
uint256[] memory _cardType,
// 词条
uint256[] memory _cardEntrys,
string memory _uri,
address _ownerAddress
) = _at(map._inner, index);
return (
uint256(_tokenId),
_star,
_tokenVal,
_cardType,
_cardEntrys,
_uri,
_ownerAddress
);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (CardEntry memory) {
return _get(map._inner, bytes32(key), errorMessage);
}
function getOwner(
UintToAddressMap storage map,
uint256 tokenId,
string memory errorMessage
) internal view returns (address) {
return _getOwnerAddress(map._inner, bytes32(tokenId), errorMessage);
}
function allTokenIds(UintToAddressMap storage map)
internal
view
returns (uint256[] memory)
{
return _all(map._inner);
}
}
|
Returns true if the key is in the map. O(1)./
|
function _contains(CardMap storage map, bytes32 key)
private
view
returns (bool)
{
return map._indexes[key] != 0;
}
| 907,733 |
./full_match/44787/0xc7f5366f1255e50FFA5F6cDC9959adEF5E312715/sources/contracts/CarbonPathToken.sol
|
See {ERC20-_beforeTokenTransfer}. Requirements: - the contract must not be paused./
|
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), 'CarbonPathToken: token transfer while paused');
}
| 13,291,661 |
./full_match/2222/0xB5fa77E3929fe198a86Aa40fd6c77886785bCd0e/sources/contracts/libraries/Allowance.sol
|
Sets the allowed amount and expiry of the spender's permissions on owner's token. Nonce does not need to be incremented. If the inputted expiration is 0, the allowance only lasts the duration of the block.
|
function updateAmountAndExpiration(
IAllowanceTransfer.PackedAllowance storage allowed,
uint160 amount,
uint48 expiration
) internal {
allowed.expiration = expiration == 0 ? uint48(block.timestamp) : expiration;
allowed.amount = amount;
}
| 7,102,796 |
pragma solidity ^0.4.24;
//-----------------------------------------------------------------------------
/// @title TOY Ownership
/// @notice defines TOY Token ownership-tracking structures and view functions.
//-----------------------------------------------------------------------------
contract ToyOwnership {
struct ToyToken {
// owner ID list
address owner;
// unique identifier
uint uid;
// timestamp
uint timestamp;
// exp
uint exp;
// toy data
bytes toyData;
}
struct ExternalNft{
// Contract address
address nftContractAddress;
// Token Identifier
uint nftId;
}
// Array containing all TOY Tokens. The first element in toyArray returns
// as invalid
ToyToken[] toyArray;
// Mapping containing all UIDs tracked by this contract. Valid UIDs map to
// index numbers, invalid UIDs map to 0.
mapping (uint => uint) uidToToyIndex;
// Mapping containing linked external NFTs. Linked TOY Tokens always map to
// non-zero numbers, invalid TOY Tokens map to 0.
mapping (uint => ExternalNft) uidToExternalNft;
// Mapping containing tokens IDs for tokens created by an external contract
// and whether or not it is linked to a TOY Token
mapping (address => mapping (uint => bool)) linkedExternalNfts;
//-------------------------------------------------------------------------
/// @dev Throws if TOY Token #`_tokenId` isn't tracked by the toyArray.
//-------------------------------------------------------------------------
modifier mustExist(uint _tokenId) {
require (uidToToyIndex[_tokenId] != 0, "Invalid TOY Token UID");
_;
}
//-------------------------------------------------------------------------
/// @dev Throws if TOY Token #`_tokenId` isn't owned by sender.
//-------------------------------------------------------------------------
modifier mustOwn(uint _tokenId) {
require
(
ownerOf(_tokenId) == msg.sender,
"Must be owner of this TOY Token"
);
_;
}
//-------------------------------------------------------------------------
/// @dev Throws if parameter is zero
//-------------------------------------------------------------------------
modifier notZero(uint _param) {
require(_param != 0, "Parameter cannot be zero");
_;
}
//-------------------------------------------------------------------------
/// @dev Creates an empty TOY Token as a [0] placeholder for invalid TOY
/// Token queries.
//-------------------------------------------------------------------------
constructor () public {
toyArray.push(ToyToken(0,0,0,0,""));
}
//-------------------------------------------------------------------------
/// @notice Find the owner of TOY Token #`_tokenId`
/// @dev throws if `_owner` is the zero address.
/// @param _tokenId The identifier for a TOY Token
/// @return The address of the owner of the TOY Token
//-------------------------------------------------------------------------
function ownerOf(uint256 _tokenId)
public
view
mustExist(_tokenId)
returns (address)
{
// owner must not be the zero address
require (
toyArray[uidToToyIndex[_tokenId]].owner != 0,
"TOY Token has no owner"
);
return toyArray[uidToToyIndex[_tokenId]].owner;
}
//-------------------------------------------------------------------------
/// @notice Count all TOY Tokens assigned to an owner
/// @dev throws if `_owner` is the zero address.
/// @param _owner An address to query
/// @return The number of TOY Tokens owned by `_owner`, possibly zero
//-------------------------------------------------------------------------
function balanceOf(address _owner)
public
view
notZero(uint(_owner))
returns (uint256)
{
uint owned;
for (uint i = 1; i < toyArray.length; ++i) {
if(toyArray[i].owner == _owner) {
++owned;
}
}
return owned;
}
//-------------------------------------------------------------------------
/// @notice Get a list of TOY Tokens assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid TOY Tokens.
/// @param _owner Address to query for TOY Tokens.
/// @return The complete list of Unique Indentifiers for TOY Tokens
/// assigned to `_owner`
//-------------------------------------------------------------------------
function tokensOfOwner(address _owner) external view returns (uint[]) {
uint toysOwned = balanceOf(_owner);
require(toysOwned > 0, "No owned TOY Tokens");
uint counter = 0;
uint[] memory result = new uint[](toysOwned);
for (uint i = 0; i < toyArray.length; i++) {
if(toyArray[i].owner == _owner) {
result[counter] = toyArray[i].uid;
counter++;
}
}
return result;
}
//-------------------------------------------------------------------------
/// @notice Get number of TOY Tokens tracked by this contract
/// @return A count of valid TOY Tokens tracked by this contract, where
/// each one has an assigned and queryable owner.
//-------------------------------------------------------------------------
function totalSupply() external view returns (uint256) {
return (toyArray.length - 1);
}
//-------------------------------------------------------------------------
/// @notice Get the UID of TOY Token with index number `index`.
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The UID for the #`_index` TOY Token in the TOY Token array.
//-------------------------------------------------------------------------
function tokenByIndex(uint256 _index) external view returns (uint256) {
// index must correspond to an existing TOY Token
require (_index > 0 && _index < toyArray.length, "Invalid index");
return (toyArray[_index].uid);
}
//-------------------------------------------------------------------------
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner Address to query for TOY Tokens.
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The Unique Indentifier for the #`_index` TOY Token assigned to
/// `_owner`, (sort order not specified)
//-------------------------------------------------------------------------
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
) external view notZero(uint(_owner)) returns (uint256) {
uint toysOwned = balanceOf(_owner);
require(toysOwned > 0, "No owned TOY Tokens");
require(_index < toysOwned, "Invalid index");
uint counter = 0;
for (uint i = 0; i < toyArray.length; i++) {
if (toyArray[i].owner == _owner) {
if (counter == _index) {
return(toyArray[i].uid);
} else {
counter++;
}
}
}
}
}
//-----------------------------------------------------------------------------
/// @title Token Receiver Interface
//-----------------------------------------------------------------------------
interface TokenReceiverInterface {
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
) external returns(bytes4);
}
//-----------------------------------------------------------------------------
/// @title ERC721 Interface
//-----------------------------------------------------------------------------
interface ERC721 {
function transferFrom (
address _from,
address _to,
uint256 _tokenId
) external payable;
function ownerOf(uint _tokenId) external returns(address);
function getApproved(uint256 _tokenId) external view returns (address);
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
//-----------------------------------------------------------------------------
/// @title TOY Transfers
/// @notice Defines transfer functionality for TOY Tokens to transfer ownership.
/// Defines approval functionality for 3rd parties to enable transfers on
/// owners' behalf.
//-----------------------------------------------------------------------------
contract ToyTransfers is ToyOwnership {
//-------------------------------------------------------------------------
/// @dev Transfer emits when ownership of a TOY Token changes by any
/// mechanism. This event emits when TOY Tokens are created ('from' == 0).
/// At the time of any transfer, the approved address for that TOY Token
/// (if any) is reset to address(0).
//-------------------------------------------------------------------------
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
//-------------------------------------------------------------------------
/// @dev Approval emits when the approved address for a TOY Token is
/// changed or reaffirmed. The zero address indicates there is no approved
/// address. When a Transfer event emits, this also indicates that the
/// approved address for that TOY Token (if any) is reset to none.
//-------------------------------------------------------------------------
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
//-------------------------------------------------------------------------
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all TOY Tokens of the owner.
//-------------------------------------------------------------------------
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
// Mapping from token ID to approved address
mapping (uint => address) idToApprovedAddress;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) operatorApprovals;
//-------------------------------------------------------------------------
/// @dev Throws if called by any account other than token owner, approved
/// address, or authorized operator.
//-------------------------------------------------------------------------
modifier canOperate(uint _uid) {
// sender must be owner of TOY Token #uid, or sender must be the
// approved address of TOY Token #uid, or an authorized operator for
// TOY Token owner
require (
msg.sender == toyArray[uidToToyIndex[_uid]].owner ||
msg.sender == idToApprovedAddress[_uid] ||
operatorApprovals[toyArray[uidToToyIndex[_uid]].owner][msg.sender],
"Not authorized to operate for this TOY Token"
);
_;
}
//-------------------------------------------------------------------------
/// @notice Change or reaffirm the approved address for TOY Token #`_tokenId`.
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved TOY Token controller
/// @param _tokenId The TOY Token to approve
//-------------------------------------------------------------------------
function approve(address _approved, uint256 _tokenId) external payable {
address owner = ownerOf(_tokenId);
// msg.sender must be the current NFT owner, or an authorized operator
// of the current owner.
require (
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"Not authorized to approve for this TOY Token"
);
idToApprovedAddress[_tokenId] = _approved;
emit Approval(owner, _approved, _tokenId);
}
//-------------------------------------------------------------------------
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if
/// there is none
//-------------------------------------------------------------------------
function getApproved(
uint256 _tokenId
) external view mustExist(_tokenId) returns (address) {
return idToApprovedAddress[_tokenId];
}
//-------------------------------------------------------------------------
/// @notice Enable or disable approval for a third party ("operator") to
/// manage all of sender's TOY Tokens
/// @dev Emits the ApprovalForAll event. The contract MUST allow multiple
/// operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke
/// approval
//-------------------------------------------------------------------------
function setApprovalForAll(address _operator, bool _approved) external {
require(_operator != msg.sender, "Operator cannot be sender");
operatorApprovals[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
//-------------------------------------------------------------------------
/// @notice Get whether '_operator' is approved to manage all of '_owner's
/// TOY Tokens
/// @param _owner TOY Token Owner.
/// @param _operator Address to check for approval.
/// @return True if '_operator' is approved to manage all of '_owner's' TOY
/// Tokens.
//-------------------------------------------------------------------------
function isApprovedForAll(
address _owner,
address _operator
) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
//-------------------------------------------------------------------------
/// @notice Transfers ownership of TOY Token #`_tokenId` from `_from` to
/// `_to`
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, checks if
/// `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `0x150b7a02`. If TOY Token is linked to an external NFT, this function
/// calls TransferFrom from the external address. Throws if this contract
/// is not an approved operator for the external NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
//-------------------------------------------------------------------------
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
external
payable
mustExist(_tokenId)
canOperate(_tokenId)
notZero(uint(_to))
{
address owner = ownerOf(_tokenId);
// _from address must be current owner of the TOY Token
require (
_from == owner,
"TOY Token not owned by '_from'"
);
// if TOY Token has a linked external NFT, call TransferFrom on the
// external NFT contract
ExternalNft memory externalNft = uidToExternalNft[_tokenId];
if (externalNft.nftContractAddress != 0) {
// initialize external NFT contract
ERC721 externalContract = ERC721(externalNft.nftContractAddress);
// call TransferFrom
externalContract.transferFrom(_from, _to, externalNft.nftId);
}
// clear approval
idToApprovedAddress[_tokenId] = 0;
// transfer ownership
toyArray[uidToToyIndex[_tokenId]].owner = _to;
emit Transfer(_from, _to, _tokenId);
// check and call onERC721Received. Throws and rolls back the transfer
// if _to does not implement the expected interface
uint size;
assembly { size := extcodesize(_to) }
if (size > 0) {
bytes4 retval = TokenReceiverInterface(_to).onERC721Received(msg.sender, _from, _tokenId, "");
require(
retval == 0x150b7a02,
"Destination contract not equipped to receive TOY Tokens"
);
}
}
//-------------------------------------------------------------------------
/// @notice Transfers ownership of TOY Token #`_tokenId` from `_from` to
/// `_to`
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. If TOY Token is linked to an external
/// NFT, this function calls TransferFrom from the external address.
/// Throws if this contract is not an approved operator for the external
/// NFT. When transfer is complete, checks if `_to` is a smart contract
/// (code size > 0). If so, it calls `onERC721Received` on `_to` and
/// throws if the return value is not `0x150b7a02`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param _data Additional data with no pre-specified format
//-------------------------------------------------------------------------
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
external
payable
mustExist(_tokenId)
canOperate(_tokenId)
notZero(uint(_to))
{
address owner = ownerOf(_tokenId);
// _from address must be current owner of the TOY Token
require (
_from == owner,
"TOY Token not owned by '_from'"
);
// if TOY Token has a linked external NFT, call TransferFrom on the
// external NFT contract
ExternalNft memory externalNft = uidToExternalNft[_tokenId];
if (externalNft.nftContractAddress != 0) {
// initialize external NFT contract
ERC721 externalContract = ERC721(externalNft.nftContractAddress);
// call TransferFrom
externalContract.transferFrom(_from, _to, externalNft.nftId);
}
// clear approval
idToApprovedAddress[_tokenId] = 0;
// transfer ownership
toyArray[uidToToyIndex[_tokenId]].owner = _to;
emit Transfer(_from, _to, _tokenId);
// check and call onERC721Received. Throws and rolls back the transfer
// if _to does not implement the expected interface
uint size;
assembly { size := extcodesize(_to) }
if (size > 0) {
bytes4 retval = TokenReceiverInterface(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(
retval == 0x150b7a02,
"Destination contract not equipped to receive TOY Tokens"
);
}
}
//-------------------------------------------------------------------------
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. If TOY Token is linked to an external
/// NFT, this function calls TransferFrom from the external address.
/// Throws if this contract is not an approved operator for the external
/// NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
//-------------------------------------------------------------------------
function transferFrom(address _from, address _to, uint256 _tokenId)
external
payable
mustExist(_tokenId)
canOperate(_tokenId)
notZero(uint(_to))
{
address owner = ownerOf(_tokenId);
// _from address must be current owner of the TOY Token
require (
_from == owner && _from != 0,
"TOY Token not owned by '_from'"
);
// if TOY Token has a linked external NFT, call TransferFrom on the
// external NFT contract
ExternalNft memory externalNft = uidToExternalNft[_tokenId];
if (externalNft.nftContractAddress != 0) {
// initialize external NFT contract
ERC721 externalContract = ERC721(externalNft.nftContractAddress);
// call TransferFrom
externalContract.transferFrom(_from, _to, externalNft.nftId);
}
// clear approval
idToApprovedAddress[_tokenId] = 0;
// transfer ownership
toyArray[uidToToyIndex[_tokenId]].owner = _to;
emit Transfer(_from, _to, _tokenId);
}
}
//-----------------------------------------------------------------------------
///@title ERC-20 function declarations
//-----------------------------------------------------------------------------
interface ERC20 {
function transfer (
address to,
uint tokens
) external returns (bool success);
function transferFrom (
address from,
address to,
uint tokens
) external returns (bool success);
}
//-----------------------------------------------------------------------------
/// @title External Token Handler
/// @notice Defines depositing and withdrawal of Ether and ERC-20-compliant
/// tokens into TOY Tokens.
//-----------------------------------------------------------------------------
contract ExternalTokenHandler is ToyTransfers {
// handles the balances of TOY Tokens for every ERC20 token address
mapping (address => mapping(uint => uint)) externalTokenBalances;
// UID value is 7 bytes. Max value is 2**56 - 1
uint constant UID_MAX = 0xFFFFFFFFFFFFFF;
//-------------------------------------------------------------------------
/// @notice Deposit Ether from sender to approved TOY Token
/// @dev Throws if Ether to deposit is zero. Throws if sender is not
/// approved to operate TOY Token #`toUid`. Throws if TOY Token #`toUid`
/// is unlinked. Throws if sender has insufficient balance for deposit.
/// @param _toUid the TOY Token to deposit the Ether into
//-------------------------------------------------------------------------
function depositEther(uint _toUid)
external
payable
canOperate(_toUid)
notZero(msg.value)
{
// TOY Token must be linked
require (
_toUid < UID_MAX,
"Invalid TOY Token. TOY Token not yet linked"
);
// add amount to TOY Token's balance
externalTokenBalances[address(this)][_toUid] += msg.value;
}
//-------------------------------------------------------------------------
/// @notice Withdraw Ether from approved TOY Token to TOY Token's owner
/// @dev Throws if Ether to withdraw is zero. Throws if sender is not an
/// approved operator for TOY Token #`_fromUid`. Throws if TOY Token
/// #`_fromUid` has insufficient balance to withdraw.
/// @param _fromUid the TOY Token to withdraw the Ether from
/// @param _amount the amount of Ether to withdraw (in Wei)
//-------------------------------------------------------------------------
function withdrawEther(
uint _fromUid,
uint _amount
) external canOperate(_fromUid) notZero(_amount) {
// TOY Token must have sufficient Ether balance
require (
externalTokenBalances[address(this)][_fromUid] >= _amount,
"Insufficient Ether to withdraw"
);
// subtract amount from TOY Token's balance
externalTokenBalances[address(this)][_fromUid] -= _amount;
// call transfer function
ownerOf(_fromUid).transfer(_amount);
}
//-------------------------------------------------------------------------
/// @notice Withdraw Ether from approved TOY Token and send to '_to'
/// @dev Throws if Ether to transfer is zero. Throws if sender is not an
/// approved operator for TOY Token #`to_fromUidUid`. Throws if TOY Token
/// #`_fromUid` has insufficient balance to withdraw.
/// @param _fromUid the TOY Token to withdraw and send the Ether from
/// @param _to the address to receive the transferred Ether
/// @param _amount the amount of Ether to withdraw (in Wei)
//-------------------------------------------------------------------------
function transferEther(
uint _fromUid,
address _to,
uint _amount
) external canOperate(_fromUid) notZero(_amount) {
// TOY Token must have sufficient Ether balance
require (
externalTokenBalances[address(this)][_fromUid] >= _amount,
"Insufficient Ether to transfer"
);
// subtract amount from TOY Token's balance
externalTokenBalances[address(this)][_fromUid] -= _amount;
// call transfer function
_to.transfer(_amount);
}
//-------------------------------------------------------------------------
/// @notice Deposit ERC-20 tokens from sender to approved TOY Token
/// @dev This contract address must be an authorized spender for sender.
/// Throws if tokens to deposit is zero. Throws if sender is not an
/// approved operator for TOY Token #`toUid`. Throws if TOY Token #`toUid`
/// is unlinked. Throws if this contract address has insufficient
/// allowance for transfer. Throws if sender has insufficient balance for
/// deposit. Throws if tokenAddress has no transferFrom function.
/// @param _tokenAddress the ERC-20 contract address
/// @param _toUid the TOY Token to deposit the ERC-20 tokens into
/// @param _tokens the number of tokens to deposit
//-------------------------------------------------------------------------
function depositERC20 (
address _tokenAddress,
uint _toUid,
uint _tokens
) external canOperate(_toUid) notZero(_tokens) {
// TOY Token must be linked
require (_toUid < UID_MAX, "Invalid TOY Token. TOY Token not yet linked");
// initialize token contract
ERC20 tokenContract = ERC20(_tokenAddress);
// add amount to TOY Token's balance
externalTokenBalances[_tokenAddress][_toUid] += _tokens;
// call transferFrom function from token contract
tokenContract.transferFrom(msg.sender, address(this), _tokens);
}
//-------------------------------------------------------------------------
/// @notice Deposit ERC-20 tokens from '_to' to approved TOY Token
/// @dev This contract address must be an authorized spender for '_from'.
/// Throws if tokens to deposit is zero. Throws if sender is not an
/// approved operator for TOY Token #`toUid`. Throws if TOY Token #`toUid`
/// is unlinked. Throws if this contract address has insufficient
/// allowance for transfer. Throws if sender has insufficient balance for
/// deposit. Throws if tokenAddress has no transferFrom function.
/// @param _tokenAddress the ERC-20 contract address
/// @param _from the address sending ERC-21 tokens to deposit
/// @param _toUid the TOY Token to deposit the ERC-20 tokens into
/// @param _tokens the number of tokens to deposit
//-------------------------------------------------------------------------
function depositERC20From (
address _tokenAddress,
address _from,
uint _toUid,
uint _tokens
) external canOperate(_toUid) notZero(_tokens) {
// TOY Token must be linked
require (
_toUid < UID_MAX,
"Invalid TOY Token. TOY Token not yet linked"
);
// initialize token contract
ERC20 tokenContract = ERC20(_tokenAddress);
// add amount to TOY Token's balance
externalTokenBalances[_tokenAddress][_toUid] += _tokens;
// call transferFrom function from token contract
tokenContract.transferFrom(_from, address(this), _tokens);
}
//-------------------------------------------------------------------------
/// @notice Withdraw ERC-20 tokens from approved TOY Token to TOY Token's
/// owner
/// @dev Throws if tokens to withdraw is zero. Throws if sender is not an
/// approved operator for TOY Token #`_fromUid`. Throws if TOY Token
/// #`_fromUid` has insufficient balance to withdraw. Throws if
/// tokenAddress has no transfer function.
/// @param _tokenAddress the ERC-20 contract address
/// @param _fromUid the TOY Token to withdraw the ERC-20 tokens from
/// @param _tokens the number of tokens to withdraw
//-------------------------------------------------------------------------
function withdrawERC20 (
address _tokenAddress,
uint _fromUid,
uint _tokens
) external canOperate(_fromUid) notZero(_tokens) {
// TOY Token must have sufficient token balance
require (
externalTokenBalances[_tokenAddress][_fromUid] >= _tokens,
"insufficient tokens to withdraw"
);
// initialize token contract
ERC20 tokenContract = ERC20(_tokenAddress);
// subtract amount from TOY Token's balance
externalTokenBalances[_tokenAddress][_fromUid] -= _tokens;
// call transfer function from token contract
tokenContract.transfer(ownerOf(_fromUid), _tokens);
}
//-------------------------------------------------------------------------
/// @notice Transfer ERC-20 tokens from your TOY Token to `_to`
/// @dev Throws if tokens to transfer is zero. Throws if sender is not an
/// approved operator for TOY Token #`_fromUid`. Throws if TOY Token
/// #`_fromUid` has insufficient balance to transfer. Throws if
/// tokenAddress has no transfer function.
/// @param _tokenAddress the ERC-20 contract address
/// @param _fromUid the TOY Token to withdraw the ERC-20 tokens from
/// @param _to the wallet address to send the ERC-20 tokens
/// @param _tokens the number of tokens to withdraw
//-------------------------------------------------------------------------
function transferERC20 (
address _tokenAddress,
uint _fromUid,
address _to,
uint _tokens
) external canOperate(_fromUid) notZero(_tokens) {
// TOY Token must have sufficient token balance
require (
externalTokenBalances[_tokenAddress][_fromUid] >= _tokens,
"insufficient tokens to withdraw"
);
// initialize token contract
ERC20 tokenContract = ERC20(_tokenAddress);
// subtract amount from TOY Token's balance
externalTokenBalances[_tokenAddress][_fromUid] -= _tokens;
// call transfer function from token contract
tokenContract.transfer(_to, _tokens);
}
//-------------------------------------------------------------------------
/// @notice Get external token balance for tokens deposited into TOY Token
/// #`_uid`.
/// @dev To query Ether, use THIS CONTRACT'S address as '_tokenAddress'.
/// @param _uid Owner of the tokens to query
/// @param _tokenAddress Token creator contract address
//-------------------------------------------------------------------------
function getExternalTokenBalance(
uint _uid,
address _tokenAddress
) external view returns (uint) {
return externalTokenBalances[_tokenAddress][_uid];
}
}
//-----------------------------------------------------------------------------
/// @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 {
//-------------------------------------------------------------------------
/// @dev Emits when owner address changes by any mechanism.
//-------------------------------------------------------------------------
event OwnershipTransfer (address previousOwner, address newOwner);
// Wallet address that can sucessfully execute onlyOwner functions
address owner;
//-------------------------------------------------------------------------
/// @dev Sets the owner of the contract to the sender account.
//-------------------------------------------------------------------------
constructor() public {
owner = msg.sender;
emit OwnershipTransfer(address(0), owner);
}
//-------------------------------------------------------------------------
/// @dev Throws if called by any account other than `owner`.
//-------------------------------------------------------------------------
modifier onlyOwner() {
require(
msg.sender == owner,
"Function can only be called by contract owner"
);
_;
}
//-------------------------------------------------------------------------
/// @notice Transfer control of the contract to a newOwner.
/// @dev Throws if `_newOwner` is zero address.
/// @param _newOwner The address to transfer ownership to.
//-------------------------------------------------------------------------
function transferOwnership(address _newOwner) public onlyOwner {
// for safety, new owner parameter must not be 0
require (
_newOwner != address(0),
"New owner address cannot be zero"
);
// define local variable for old owner
address oldOwner = owner;
// set owner to new owner
owner = _newOwner;
// emit ownership transfer event
emit OwnershipTransfer(oldOwner, _newOwner);
}
}
//-----------------------------------------------------------------------------
/// @title TOY Token Interface Support
/// @notice Defines supported interfaces for ERC-721 wallets to query
//-----------------------------------------------------------------------------
contract ToyInterfaceSupport {
// mapping of all possible interfaces to whether they are supported
mapping (bytes4 => bool) interfaceIdToIsSupported;
//-------------------------------------------------------------------------
/// @notice ToyInterfaceSupport constructor. Sets to true interfaces
/// supported at launch.
//-------------------------------------------------------------------------
constructor () public {
// supports ERC-165
interfaceIdToIsSupported[0x01ffc9a7] = true;
// supports ERC-721
interfaceIdToIsSupported[0x80ac58cd] = true;
// supports ERC-721 Enumeration
interfaceIdToIsSupported[0x780e9d63] = true;
// supports ERC-721 Metadata
interfaceIdToIsSupported[0x5b5e139f] = true;
}
//-------------------------------------------------------------------------
/// @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.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
//-------------------------------------------------------------------------
function supportsInterface(
bytes4 interfaceID
) external view returns (bool) {
if(interfaceID == 0xffffffff) {
return false;
} else {
return interfaceIdToIsSupported[interfaceID];
}
}
}
//-----------------------------------------------------------------------------
/// @title PLAY Token Interface
//-----------------------------------------------------------------------------
interface PlayInterface {
//-------------------------------------------------------------------------
/// @notice Get the number of PLAY tokens owned by `tokenOwner`.
/// @dev Throws if trying to query the zero address.
/// @param tokenOwner The PLAY token owner.
/// @return The number of PLAY tokens owned by `tokenOwner` (in pWei).
//-------------------------------------------------------------------------
function balanceOf(address tokenOwner) external view returns (uint);
//-------------------------------------------------------------------------
/// @notice Lock `(tokens/1000000000000000000).fixed(0,18)` PLAY from
/// `from` for `numberOfYears` years.
/// @dev Throws if amount to lock is zero. Throws if numberOfYears is zero
/// or greater than maximumLockYears. Throws if `msg.sender` has
/// insufficient allowance to lock. Throws if `from` has insufficient
/// balance to lock.
/// @param from The token owner whose PLAY is being locked. Sender must be
/// an approved spender.
/// @param numberOfYears The number of years the tokens will be locked.
/// @param tokens The number of tokens to lock (in pWei).
//-------------------------------------------------------------------------
function lockFrom(address from, uint numberOfYears, uint tokens)
external
returns(bool);
}
//-----------------------------------------------------------------------------
/// @title TOY Token Creation
/// @notice Defines new TOY Token creation (minting) and TOY Token linking to
/// RFID-enabled physical objects.
//-----------------------------------------------------------------------------
contract ToyCreation is Ownable, ExternalTokenHandler, ToyInterfaceSupport {
//-------------------------------------------------------------------------
/// @dev Link emits when an empty TOY Token gets assigned to a valid RFID.
//-------------------------------------------------------------------------
event Link(uint _oldUid, uint _newUid);
// PLAY needed to mint one TOY Token (in pWei)
uint public priceToMint = 1000 * 10**18;
// Buffer added to the front of every TOY Token at time of creation. TOY
// Tokens with a uid greater than the buffer are unlinked.
uint constant uidBuffer = 0x0100000000000000; // 14 zeroes
// PLAY Token Contract object to interface with.
PlayInterface play = PlayInterface(0xe2427cfEB5C330c007B8599784B97b65b4a3A819);
//-------------------------------------------------------------------------
/// @notice Update PLAY Token contract variable with new contract address.
/// @dev Throws if `_newAddress` is the zero address.
/// @param _newAddress Updated contract address.
//-------------------------------------------------------------------------
function updatePlayTokenContract(address _newAddress) external onlyOwner {
play = PlayInterface(_newAddress);
}
//-------------------------------------------------------------------------
/// @notice Change the number of PLAY tokens needed to mint a new TOY Token
/// (in pWei).
/// @dev Throws if `_newPrice` is zero.
/// @param _newPrice The new price to mint (in pWei)
//-------------------------------------------------------------------------
function changeToyPrice(uint _newPrice) external onlyOwner {
priceToMint = _newPrice;
}
//-------------------------------------------------------------------------
/// @notice Send and lock PLAY to mint a new empty TOY Token for yourself.
/// @dev Sender must have approved this contract address as an authorized
/// spender with at least "priceToMint" PLAY. Throws if the sender has
/// insufficient PLAY. Throws if sender has not granted this contract's
/// address sufficient allowance.
//-------------------------------------------------------------------------
function mint() external {
play.lockFrom (msg.sender, 2, priceToMint);
uint uid = uidBuffer + toyArray.length;
uint index = toyArray.push(ToyToken(msg.sender, uid, 0, 0, ""));
uidToToyIndex[uid] = index - 1;
emit Transfer(0, msg.sender, uid);
}
//-------------------------------------------------------------------------
/// @notice Send and lock PLAY to mint a new empty TOY Token for 'to'.
/// @dev Sender must have approved this contract address as an authorized
/// spender with at least "priceToMint" PLAY. Throws if the sender has
/// insufficient PLAY. Throws if sender has not granted this contract's
/// address sufficient allowance.
/// @param _to The address to deduct PLAY Tokens from and send new TOY Token to.
//-------------------------------------------------------------------------
function mintAndSend(address _to) external {
play.lockFrom (msg.sender, 2, priceToMint);
uint uid = uidBuffer + toyArray.length;
uint index = toyArray.push(ToyToken(_to, uid, 0, 0, ""));
uidToToyIndex[uid] = index - 1;
emit Transfer(0, _to, uid);
}
//-------------------------------------------------------------------------
/// @notice Send and lock PLAY to mint `_amount` new empty TOY Tokens for
/// yourself.
/// @dev Sender must have approved this contract address as an authorized
/// spender with at least "priceToMint" x `_amount` PLAY. Throws if the
/// sender has insufficient PLAY. Throws if sender has not granted this
/// contract's address sufficient allowance.
//-------------------------------------------------------------------------
function mintBulk(uint _amount) external {
play.lockFrom (msg.sender, 2, priceToMint * _amount);
for (uint i = 0; i < _amount; ++i) {
uint uid = uidBuffer + toyArray.length;
uint index = toyArray.push(ToyToken(msg.sender, uid, 0, 0, ""));
uidToToyIndex[uid] = index - 1;
emit Transfer(0, msg.sender, uid);
}
}
//-------------------------------------------------------------------------
/// @notice Change TOY Token #`_toyId` to TOY Token #`_newUid`. Writes any
/// data passed through '_data' into the TOY Token's public data.
/// @dev Throws if TOY Token #`_toyId` does not exist. Throws if sender is
/// not approved to operate for TOY Token. Throws if '_toyId' is smaller
/// than 8 bytes. Throws if '_newUid' is bigger than 7 bytes. Throws if
/// '_newUid' is zero. Throws if '_newUid' is already taken.
/// @param _newUid The UID of the RFID chip to link to the TOY Token
/// @param _toyId The UID of the empty TOY Token to link
/// @param _data A byte string of data to attach to the TOY Token
//-------------------------------------------------------------------------
function link(
bytes7 _newUid,
uint _toyId,
bytes _data
) external canOperate(_toyId) {
ToyToken storage toy = toyArray[uidToToyIndex[_toyId]];
// _toyId must be an empty TOY Token
require (_toyId > uidBuffer, "TOY Token already linked");
// _newUid field cannot be empty or greater than 7 bytes
require (_newUid > 0 && uint(_newUid) < UID_MAX, "Invalid new UID");
// a TOY Token with the new UID must not currently exist
require (
uidToToyIndex[uint(_newUid)] == 0,
"TOY Token with 'newUID' already exists"
);
// set new UID's mapping to index to old UID's mapping
uidToToyIndex[uint(_newUid)] = uidToToyIndex[_toyId];
// reset old UID's mapping to index
uidToToyIndex[_toyId] = 0;
// set TOY Token's UID to new UID
toy.uid = uint(_newUid);
// set any data
toy.toyData = _data;
// reset the timestamp
toy.timestamp = now;
emit Link(_toyId, uint(_newUid));
}
//-------------------------------------------------------------------------
/// @notice Change TOY Token UIDs to new UIDs for multiple TOY Tokens.
/// Writes any data passed through '_data' into all the TOY Tokens' data.
/// @dev Throws if any TOY Token's UID does not exist. Throws if sender is
/// not approved to operate for any TOY Token. Throws if any '_toyId' is
/// smaller than 8 bytes. Throws if any '_newUid' is bigger than 7 bytes.
/// Throws if any '_newUid' is zero. Throws if '_newUid' is already taken.
/// Throws if array parameters are not the same length.
/// @param _newUid The UID of the RFID chip to link to the TOY Token
/// @param _toyId The UID of the empty TOY Token to link
/// @param _data A byte string of data to attach to the TOY Token
//-------------------------------------------------------------------------
function linkBulk(
bytes7[] _newUid,
uint[] _toyId,
bytes _data
) external {
require (_newUid.length == _toyId.length, "Array lengths not equal");
for (uint i = 0; i < _newUid.length; ++i) {
ToyToken storage toy = toyArray[uidToToyIndex[_toyId[i]]];
// sender must be authorized operator
require (
msg.sender == toy.owner ||
msg.sender == idToApprovedAddress[_toyId[i]] ||
operatorApprovals[toy.owner][msg.sender],
"Not authorized to operate for this TOY Token"
);
// _toyId must be an empty TOY Token
require (_toyId[i] > uidBuffer, "TOY Token already linked");
// _newUid field cannot be empty or greater than 7 bytes
require (_newUid[i] > 0 && uint(_newUid[i]) < UID_MAX, "Invalid new UID");
// a TOY Token with the new UID must not currently exist
require (
uidToToyIndex[uint(_newUid[i])] == 0,
"TOY Token with 'newUID' already exists"
);
// set new UID's mapping to index to old UID's mapping
uidToToyIndex[uint(_newUid[i])] = uidToToyIndex[_toyId[i]];
// reset old UID's mapping to index
uidToToyIndex[_toyId[i]] = 0;
// set TOY Token's UID to new UID
toy.uid = uint(_newUid[i]);
// set any data
toy.toyData = _data;
// reset the timestamp
toy.timestamp = now;
emit Link(_toyId[i], uint(_newUid[i]));
}
}
//-------------------------------------------------------------------------
/// @notice Set external NFT #`_externalId` as TOY Token #`_toyUid`'s
/// linked external NFT.
/// @dev Throws if sender is not authorized to operate TOY Token #`_toyUid`
/// Throws if '_toyUid' is bigger than 7 bytes. Throws if external NFT is
/// already linked. Throws if sender is not authorized to operate external
/// NFT.
/// @param _toyUid The UID of the TOY Token to link
/// @param _externalAddress The contract address of the external NFT
/// @param _externalId The UID of the external NFT to link
//-------------------------------------------------------------------------
function linkExternalNft(
uint _toyUid,
address _externalAddress,
uint _externalId
) external canOperate(_toyUid) {
require(_toyUid < UID_MAX, "TOY Token not linked to a physical toy");
require(
linkedExternalNfts[_externalAddress][_externalId] == false,
"External NFT already linked"
);
require(
msg.sender == ERC721(_externalAddress).ownerOf(_externalId),
"Sender does not own external NFT"
);
uidToExternalNft[_toyUid] = ExternalNft(_externalAddress, _externalId);
linkedExternalNfts[_externalAddress][_externalId] = true;
}
}
//-----------------------------------------------------------------------------
/// @title TOY Token Interface
/// @notice Interface for highest-level TOY Token getters
//-----------------------------------------------------------------------------
contract ToyInterface is ToyCreation {
// URL Containing TOY Token metadata
string metadataUrl = "http://52.9.230.48:8090/toy_token/";
//-------------------------------------------------------------------------
/// @notice Change old metadata URL to `_newUrl`
/// @dev Throws if new URL is empty
/// @param _newUrl The new URL containing TOY Token metadata
//-------------------------------------------------------------------------
function updateMetadataUrl(string _newUrl)
external
onlyOwner
notZero(bytes(_newUrl).length)
{
metadataUrl = _newUrl;
}
//-------------------------------------------------------------------------
/// @notice Gets all public info for TOY Token #`_uid`.
/// @dev Throws if TOY Token #`_uid` does not exist.
/// @param _uid the UID of the TOY Token to view.
/// @return TOY Token owner, TOY Token UID, Creation Timestamp, Experience,
/// and Public Data.
//-------------------------------------------------------------------------
function changeToyData(uint _uid, bytes _data)
external
mustExist(_uid)
canOperate(_uid)
returns (address, uint, uint, uint, bytes)
{
require(_uid < UID_MAX, "TOY Token must be linked");
toyArray[uidToToyIndex[_uid]].toyData = _data;
}
//-------------------------------------------------------------------------
/// @notice Gets all public info for TOY Token #`_uid`.
/// @dev Throws if TOY Token #`_uid` does not exist.
/// @param _uid the UID of the TOY Token to view.
/// @return TOY Token owner, TOY Token UID, Creation Timestamp, Experience,
/// and Public Data.
//-------------------------------------------------------------------------
function getToy(uint _uid)
external
view
mustExist(_uid)
returns (address, uint, uint, uint, bytes)
{
ToyToken memory toy = toyArray[uidToToyIndex[_uid]];
return(toy.owner, toy.uid, toy.timestamp, toy.exp, toy.toyData);
}
//-------------------------------------------------------------------------
/// @notice Gets all info for TOY Token #`_uid`'s linked NFT.
/// @dev Throws if TOY Token #`_uid` does not exist.
/// @param _uid the UID of the TOY Token to view.
/// @return NFT contract address, External NFT ID.
//-------------------------------------------------------------------------
function getLinkedNft(uint _uid)
external
view
mustExist(_uid)
returns (address, uint)
{
ExternalNft memory nft = uidToExternalNft[_uid];
return (nft.nftContractAddress, nft.nftId);
}
//-------------------------------------------------------------------------
/// @notice Gets whether NFT #`_externalId` is linked to a TOY Token.
/// @param _externalAddress the contract address for the external NFT
/// @param _externalId the UID of the external NFT to view.
/// @return NFT contract address, External NFT ID.
//-------------------------------------------------------------------------
function externalNftIsLinked(address _externalAddress, uint _externalId)
external
view
returns(bool)
{
return linkedExternalNfts[_externalAddress][_externalId];
}
//-------------------------------------------------------------------------
/// @notice A descriptive name for a collection of NFTs in this contract
//-------------------------------------------------------------------------
function name() external pure returns (string) {
return "TOY Tokens";
}
//-------------------------------------------------------------------------
/// @notice An abbreviated name for NFTs in this contract
//-------------------------------------------------------------------------
function symbol() external pure returns (string) { return "TOY"; }
//-------------------------------------------------------------------------
/// @notice A distinct URL for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT.
/// If:
/// * The URI is a URL
/// * The URL is accessible
/// * The URL points to a valid JSON file format (ECMA-404 2nd ed.)
/// * The JSON base element is an object
/// then these names of the base element SHALL have special meaning:
/// * "name": A string identifying the item to which `_tokenId` grants
/// ownership
/// * "description": A string detailing the item to which `_tokenId`
/// grants ownership
/// * "image": A URI pointing to a file of image/* mime type representing
/// the item to which `_tokenId` grants ownership
/// Wallets and exchanges MAY display this to the end user.
/// Consider making any images at a width between 320 and 1080 pixels and
/// aspect ratio between 1.91:1 and 4:5 inclusive.
/// @param _tokenId The TOY Token whose metadata address is being queried
//-------------------------------------------------------------------------
function tokenURI(uint _tokenId)
external
view
returns (string)
{
// convert TOY Token UID to a 14 character long string of character bytes
bytes memory uidString = intToBytes(_tokenId);
// declare new string of bytes with combined length of url and uid
bytes memory fullUrlBytes = new bytes(bytes(metadataUrl).length + uidString.length);
// copy URL string and uid string into new string
uint counter = 0;
for (uint i = 0; i < bytes(metadataUrl).length; i++) {
fullUrlBytes[counter++] = bytes(metadataUrl)[i];
}
for (i = 0; i < uidString.length; i++) {
fullUrlBytes[counter++] = uidString[i];
}
// return full URL
return string(fullUrlBytes);
}
//-------------------------------------------------------------------------
/// @notice Convert int to 14 character bytes
//-------------------------------------------------------------------------
function intToBytes(uint _tokenId)
private
pure
returns (bytes)
{
// convert int to bytes32
bytes32 x = bytes32(_tokenId);
// convert each byte into two, and assign each byte a hex digit
bytes memory uidBytes64 = new bytes(64);
for (uint i = 0; i < 32; i++) {
byte b = byte(x[i]);
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
uidBytes64[i*2] = char(hi);
uidBytes64[i*2+1] = char(lo);
}
// reduce size to last 14 chars (7 bytes)
bytes memory uidBytes = new bytes(14);
for (i = 0; i < 14; ++i) {
uidBytes[i] = uidBytes64[i + 50];
}
return uidBytes;
}
//-------------------------------------------------------------------------
/// @notice Convert byte to UTF-8-encoded hex character
//-------------------------------------------------------------------------
function char(byte b) private pure returns (byte c) {
if (b < 10) return byte(uint8(b) + 0x30);
else return byte(uint8(b) + 0x57);
}
}
|
------------------------------------------------------------------------- Withdraw Ether from approved TOY Token to TOY Token's owner Throws if Ether to withdraw is zero. Throws if sender is not an approved operator for TOY Token `_fromUid`. Throws if TOY Token `_fromUid` has insufficient balance to withdraw. _fromUid the TOY Token to withdraw the Ether from _amount the amount of Ether to withdraw (in Wei)------------------------------------------------------------------------- TOY Token must have sufficient Ether balance subtract amount from TOY Token's balance call transfer function
|
function withdrawEther(
uint _fromUid,
uint _amount
) external canOperate(_fromUid) notZero(_amount) {
require (
externalTokenBalances[address(this)][_fromUid] >= _amount,
"Insufficient Ether to withdraw"
);
externalTokenBalances[address(this)][_fromUid] -= _amount;
ownerOf(_fromUid).transfer(_amount);
}
| 935,254 |
./full_match/43114/0x21a5e0Fc127C246030Fe12fd8bad711a06601A9b/sources/contracts/Hayden2V3Staker.sol
|
@inheritdoc IUniswapV3Staker
|
function withdrawToken(
uint256 tokenId,
address to,
bytes memory data
) external override {
require(to != address(this), 'Hayden2V3Staker::withdrawToken: cannot withdraw to staker');
Deposit memory deposit = deposits[tokenId];
require(deposit.numberOfStakes == 0, 'Hayden2V3Staker::withdrawToken: cannot withdraw token while staked');
require(deposit.owner == msg.sender, 'Hayden2V3Staker::withdrawToken: only owner can withdraw token');
delete deposits[tokenId];
emit DepositTransferred(tokenId, deposit.owner, address(0));
nonfungiblePositionManager.safeTransferFrom(address(this), to, tokenId, data);
}
| 4,602,583 |
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// 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: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event 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/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: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
hasMintPermission
canMint
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: contracts/ZUR.sol
/**
* Holders of ZUR can claim COE as it is mined using the claimTokens()
* function. This contract will be fed COE automatically by the COE ERC20
* contract.
*/
contract ZUR is MintableToken {
using SafeMath for uint;
string public constant name = "ZUR Cheque by Zurcoin Core";
string public constant symbol = "ZUR";
uint8 public constant decimals = 0;
address public admin;
uint public cap = 35*10**13;
uint public totalEthReleased = 0;
mapping(address => uint) public ethReleased;
address[] public trackedTokens;
mapping(address => bool) public isTokenTracked;
mapping(address => uint) public totalTokensReleased;
mapping(address => mapping(address => uint)) public tokensReleased;
constructor() public {
owner = this;
admin = msg.sender;
}
function () public payable {}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
function changeAdmin(address _receiver) onlyAdmin public {
admin = _receiver;
}
/**
* Claim your eth.
*/
function claimEth() public {
claimEthFor(msg.sender);
}
// Claim eth for address
function claimEthFor(address payee) public {
require(balances[payee] > 0);
uint totalReceived = address(this).balance.add(totalEthReleased);
uint payment = totalReceived.mul(
balances[payee]).div(
cap).sub(
ethReleased[payee]
);
require(payment != 0);
require(address(this).balance >= payment);
ethReleased[payee] = ethReleased[payee].add(payment);
totalEthReleased = totalEthReleased.add(payment);
payee.transfer(payment);
}
// Claim your tokens
function claimMyTokens() public {
claimTokensFor(msg.sender);
}
// Claim on behalf of payee address
function claimTokensFor(address payee) public {
require(balances[payee] > 0);
for (uint16 i = 0; i < trackedTokens.length; i++) {
claimToken(trackedTokens[i], payee);
}
}
/**
* Transfers the unclaimed token amount for the given token and address
* @param _tokenAddr The address of the ERC20 token
* @param _payee The address of the payee (ZUR holder)
*/
function claimToken(address _tokenAddr, address _payee) public {
require(balances[_payee] > 0);
require(isTokenTracked[_tokenAddr]);
uint payment = getUnclaimedTokenAmount(_tokenAddr, _payee);
if (payment == 0) {
return;
}
ERC20 Token = ERC20(_tokenAddr);
require(Token.balanceOf(address(this)) >= payment);
tokensReleased[address(Token)][_payee] = tokensReleased[address(Token)][_payee].add(payment);
totalTokensReleased[address(Token)] = totalTokensReleased[address(Token)].add(payment);
Token.transfer(_payee, payment);
}
/**
* Returns the amount of a token (tokenAddr) that payee can claim
* @param tokenAddr The address of the ERC20 token
* @param payee The address of the payee
*/
function getUnclaimedTokenAmount(address tokenAddr, address payee) public view returns (uint) {
ERC20 Token = ERC20(tokenAddr);
uint totalReceived = Token.balanceOf(address(this)).add(totalTokensReleased[address(Token)]);
uint payment = totalReceived.mul(
balances[payee]).div(
cap).sub(
tokensReleased[address(Token)][payee]
);
return payment;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(msg.sender != _to);
uint startingBalance = balances[msg.sender];
require(super.transfer(_to, _value));
transferCheques(msg.sender, _to, _value, startingBalance);
return true;
}
function transferCheques(address from, address to, uint cheques, uint startingBalance) internal {
// proportional amount of eth released already
uint claimedEth = ethReleased[from].mul(
cheques).div(
startingBalance
);
// increment to's released eth
ethReleased[to] = ethReleased[to].add(claimedEth);
// decrement from's released eth
ethReleased[from] = ethReleased[from].sub(claimedEth);
for (uint16 i = 0; i < trackedTokens.length; i++) {
address tokenAddr = trackedTokens[i];
// proportional amount of token released already
uint claimed = tokensReleased[tokenAddr][from].mul(
cheques).div(
startingBalance
);
// increment to's released token
tokensReleased[tokenAddr][to] = tokensReleased[tokenAddr][to].add(claimed);
// decrement from's released token
tokensReleased[tokenAddr][from] = tokensReleased[tokenAddr][from].sub(claimed);
}
}
/**
* @dev Add a new payee to the contract.
* @param _payees The addresses of the payees to add.
* @param _cheques The array of number of cheques owned by the payee.
*/
function addPayees(address[] _payees, uint[] _cheques) onlyAdmin external {
require(_payees.length == _cheques.length);
require(_payees.length > 0);
for (uint i = 0; i < _payees.length; i++) {
addPayee(_payees[i], _cheques[i]);
}
}
/**
* @dev Add a new payee to the contract.
* @param _payee The address of the payee to add.
* @param _cheques The number of _cheques owned by the payee.
*/
function addPayee(address _payee, uint _cheques) onlyAdmin canMint public {
require(_payee != address(0));
require(_cheques > 0);
require(balances[_payee] == 0);
MintableToken(this).mint(_payee, _cheques);
}
// irreversibly close the adding of cheques
function finishedLoading() onlyAdmin canMint public {
MintableToken(this).finishMinting();
}
function trackToken(address _addr) onlyAdmin public {
require(_addr != address(0));
require(!isTokenTracked[_addr]);
trackedTokens.push(_addr);
isTokenTracked[_addr] = true;
}
/*
* However unlikely, it is possible that the number of tracked tokens
* reaches the point that would make the gas cost of transferring ZUR
* exceed the block gas limit. This function allows the admin to remove
* a token from the tracked token list thus reducing the number of loops
* required in transferCheques, lowering the gas cost of transfer. The
* remaining balance of this token is sent back to the token's contract.
*
* Removal is irreversible.
*
* @param _addr The address of the ERC token to untrack
* @param _position The index of the _addr in the trackedTokens array.
* Use web3 to cycle through and find the index position.
*/
function unTrackToken(address _addr, uint16 _position) onlyAdmin public {
require(isTokenTracked[_addr]);
require(trackedTokens[_position] == _addr);
ERC20(_addr).transfer(_addr, ERC20(_addr).balanceOf(address(this)));
trackedTokens[_position] = trackedTokens[trackedTokens.length-1];
delete trackedTokens[trackedTokens.length-1];
trackedTokens.length--;
}
}
|
Add a new payee to the contract. _payee The address of the payee to add. _cheques The number of _cheques owned by the payee./
|
function addPayee(address _payee, uint _cheques) onlyAdmin canMint public {
require(_payee != address(0));
require(_cheques > 0);
require(balances[_payee] == 0);
MintableToken(this).mint(_payee, _cheques);
}
| 1,224,430 |
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
pragma experimental ABIEncoderV2;
// ============ Internal Imports ============
import {Home} from "../Home.sol";
import {Version0} from "../Version0.sol";
import {XAppConnectionManager, TypeCasts} from "../XAppConnectionManager.sol";
import {IMessageRecipient} from "../../interfaces/IMessageRecipient.sol";
import {GovernanceMessage} from "./GovernanceMessage.sol";
// ============ External Imports ============
import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol";
contract GovernanceRouter is Version0, Initializable, IMessageRecipient {
// ============ Libraries ============
using SafeMath for uint256;
using TypedMemView for bytes;
using TypedMemView for bytes29;
using GovernanceMessage for bytes29;
// ============ Immutables ============
uint32 public immutable localDomain;
// number of seconds before recovery can be activated
uint256 public immutable recoveryTimelock;
// ============ Public Storage ============
// timestamp when recovery timelock expires; 0 if timelock has not been initiated
uint256 public recoveryActiveAt;
// the address of the recovery manager multisig
address public recoveryManager;
// the local entity empowered to call governance functions, set to 0x0 on non-Governor chains
address public governor;
// domain of Governor chain -- for accepting incoming messages from Governor
uint32 public governorDomain;
// xAppConnectionManager contract which stores Replica addresses
XAppConnectionManager public xAppConnectionManager;
// domain -> remote GovernanceRouter contract address
mapping(uint32 => bytes32) public routers;
// array of all domains with registered GovernanceRouter
uint32[] public domains;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[43] private __GAP;
// ============ Events ============
/**
* @notice Emitted a remote GovernanceRouter address is added, removed, or changed
* @param domain the domain of the remote Router
* @param previousRouter the previously registered router; 0 if router is being added
* @param newRouter the new registered router; 0 if router is being removed
*/
event SetRouter(
uint32 indexed domain,
bytes32 previousRouter,
bytes32 newRouter
);
/**
* @notice Emitted when the Governor role is transferred
* @param previousGovernorDomain the domain of the previous Governor
* @param newGovernorDomain the domain of the new Governor
* @param previousGovernor the address of the previous Governor; 0 if the governor was remote
* @param newGovernor the address of the new Governor; 0 if the governor is remote
*/
event TransferGovernor(
uint32 previousGovernorDomain,
uint32 newGovernorDomain,
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @notice Emitted when the RecoveryManager role is transferred
* @param previousRecoveryManager the address of the previous RecoveryManager
* @param newRecoveryManager the address of the new RecoveryManager
*/
event TransferRecoveryManager(
address indexed previousRecoveryManager,
address indexed newRecoveryManager
);
/**
* @notice Emitted when recovery state is initiated by the RecoveryManager
* @param recoveryManager the address of the current RecoveryManager who initiated the transition
* @param recoveryActiveAt the block at which recovery state will be active
*/
event InitiateRecovery(
address indexed recoveryManager,
uint256 recoveryActiveAt
);
/**
* @notice Emitted when recovery state is exited by the RecoveryManager
* @param recoveryManager the address of the current RecoveryManager who initiated the transition
*/
event ExitRecovery(address recoveryManager);
modifier typeAssert(bytes29 _view, GovernanceMessage.Types _type) {
_view.assertType(uint40(_type));
_;
}
// ============ Modifiers ============
modifier onlyReplica() {
require(xAppConnectionManager.isReplica(msg.sender), "!replica");
_;
}
modifier onlyGovernorRouter(uint32 _domain, bytes32 _address) {
require(_isGovernorRouter(_domain, _address), "!governorRouter");
_;
}
modifier onlyGovernor() {
require(msg.sender == governor, "! called by governor");
_;
}
modifier onlyRecoveryManager() {
require(msg.sender == recoveryManager, "! called by recovery manager");
_;
}
modifier onlyInRecovery() {
require(inRecovery(), "! in recovery");
_;
}
modifier onlyNotInRecovery() {
require(!inRecovery(), "in recovery");
_;
}
modifier onlyGovernorOrRecoveryManager() {
if (!inRecovery()) {
require(msg.sender == governor, "! called by governor");
} else {
require(
msg.sender == recoveryManager,
"! called by recovery manager"
);
}
_;
}
// ============ Constructor ============
constructor(uint32 _localDomain, uint256 _recoveryTimelock) {
localDomain = _localDomain;
recoveryTimelock = _recoveryTimelock;
}
// ============ Initializer ============
function initialize(
address _xAppConnectionManager,
address _recoveryManager
) public initializer {
// initialize governor
address _governorAddr = msg.sender;
bool _isLocalGovernor = true;
_transferGovernor(localDomain, _governorAddr, _isLocalGovernor);
// initialize recovery manager
recoveryManager = _recoveryManager;
// initialize XAppConnectionManager
setXAppConnectionManager(_xAppConnectionManager);
require(
xAppConnectionManager.localDomain() == localDomain,
"XAppConnectionManager bad domain"
);
}
// ============ External Functions ============
/**
* @notice Handle Optics messages
* For all non-Governor chains to handle messages
* sent from the Governor chain via Optics.
* Governor chain should never receive messages,
* because non-Governor chains are not able to send them
* @param _origin The domain (of the Governor Router)
* @param _sender The message sender (must be the Governor Router)
* @param _message The message
*/
function handle(
uint32 _origin,
bytes32 _sender,
bytes memory _message
) external override onlyReplica onlyGovernorRouter(_origin, _sender) {
bytes29 _msg = _message.ref(0);
if (_msg.isValidCall()) {
_handleCall(_msg.tryAsCall());
} else if (_msg.isValidTransferGovernor()) {
_handleTransferGovernor(_msg.tryAsTransferGovernor());
} else if (_msg.isValidSetRouter()) {
_handleSetRouter(_msg.tryAsSetRouter());
} else {
require(false, "!valid message type");
}
}
/**
* @notice Dispatch calls locally
* @param _calls The calls
*/
function callLocal(GovernanceMessage.Call[] calldata _calls)
external
onlyGovernorOrRecoveryManager
{
for (uint256 i = 0; i < _calls.length; i++) {
_dispatchCall(_calls[i]);
}
}
/**
* @notice Dispatch calls on a remote chain via the remote GovernanceRouter
* @param _destination The domain of the remote chain
* @param _calls The calls
*/
function callRemote(
uint32 _destination,
GovernanceMessage.Call[] calldata _calls
) external onlyGovernor onlyNotInRecovery {
// ensure that destination chain has enrolled router
bytes32 _router = _mustHaveRouter(_destination);
// format call message
bytes memory _msg = GovernanceMessage.formatCalls(_calls);
// dispatch call message using Optics
Home(xAppConnectionManager.home()).dispatch(
_destination,
_router,
_msg
);
}
/**
* @notice Transfer governorship
* @param _newDomain The domain of the new governor
* @param _newGovernor The address of the new governor
*/
function transferGovernor(uint32 _newDomain, address _newGovernor)
external
onlyGovernor
onlyNotInRecovery
{
bool _isLocalGovernor = _isLocalDomain(_newDomain);
// transfer the governor locally
_transferGovernor(_newDomain, _newGovernor, _isLocalGovernor);
// if the governor domain is local, we only need to change the governor address locally
// no need to message remote routers; they should already have the same domain set and governor = bytes32(0)
if (_isLocalGovernor) {
return;
}
// format transfer governor message
bytes memory _transferGovernorMessage = GovernanceMessage
.formatTransferGovernor(
_newDomain,
TypeCasts.addressToBytes32(_newGovernor)
);
// send transfer governor message to all remote routers
// note: this assumes that the Router is on the global GovernorDomain;
// this causes a process error when relinquishing governorship
// on a newly deployed domain which is not the GovernorDomain
_sendToAllRemoteRouters(_transferGovernorMessage);
}
/**
* @notice Transfer recovery manager role
* @dev callable by the recoveryManager at any time to transfer the role
* @param _newRecoveryManager The address of the new recovery manager
*/
function transferRecoveryManager(address _newRecoveryManager)
external
onlyRecoveryManager
{
emit TransferRecoveryManager(recoveryManager, _newRecoveryManager);
recoveryManager = _newRecoveryManager;
}
/**
* @notice Set the router address for a given domain and
* dispatch the change to all remote routers
* @param _domain The domain
* @param _router The address of the new router
*/
function setRouter(uint32 _domain, bytes32 _router)
external
onlyGovernor
onlyNotInRecovery
{
// set the router locally
_setRouter(_domain, _router);
// format message to set the router on all remote routers
bytes memory _setRouterMessage = GovernanceMessage.formatSetRouter(
_domain,
_router
);
_sendToAllRemoteRouters(_setRouterMessage);
}
/**
* @notice Set the router address *locally only*
* for the deployer to setup the router mapping locally
* before transferring governorship to the "true" governor
* @dev External helper for contract setup
* @param _domain The domain
* @param _router The new router
*/
function setRouterLocal(uint32 _domain, bytes32 _router)
external
onlyGovernorOrRecoveryManager
{
// set the router locally
_setRouter(_domain, _router);
}
/**
* @notice Set the address of the XAppConnectionManager
* @dev Domain/address validation helper
* @param _xAppConnectionManager The address of the new xAppConnectionManager
*/
function setXAppConnectionManager(address _xAppConnectionManager)
public
onlyGovernorOrRecoveryManager
{
xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager);
}
/**
* @notice Initiate the recovery timelock
* @dev callable by the recovery manager
*/
function initiateRecoveryTimelock()
external
onlyNotInRecovery
onlyRecoveryManager
{
require(recoveryActiveAt == 0, "recovery already initiated");
// set the time that recovery will be active
recoveryActiveAt = block.timestamp.add(recoveryTimelock);
emit InitiateRecovery(recoveryManager, recoveryActiveAt);
}
/**
* @notice Exit recovery mode
* @dev callable by the recovery manager to end recovery mode
*/
function exitRecovery() external onlyRecoveryManager {
require(recoveryActiveAt != 0, "recovery not initiated");
delete recoveryActiveAt;
emit ExitRecovery(recoveryManager);
}
// ============ Public Functions ============
/**
* @notice Check if the contract is in recovery mode currently
* @return TRUE iff the contract is actively in recovery mode currently
*/
function inRecovery() public view returns (bool) {
uint256 _recoveryActiveAt = recoveryActiveAt;
bool _recoveryInitiated = _recoveryActiveAt != 0;
bool _recoveryActive = _recoveryActiveAt <= block.timestamp;
return _recoveryInitiated && _recoveryActive;
}
// ============ Internal Functions ============
/**
* @notice Handle message dispatching calls locally
* @param _msg The message
*/
function _handleCall(bytes29 _msg)
internal
typeAssert(_msg, GovernanceMessage.Types.Call)
{
GovernanceMessage.Call[] memory _calls = _msg.getCalls();
for (uint256 i = 0; i < _calls.length; i++) {
_dispatchCall(_calls[i]);
}
}
/**
* @notice Handle message transferring governorship to a new Governor
* @param _msg The message
*/
function _handleTransferGovernor(bytes29 _msg)
internal
typeAssert(_msg, GovernanceMessage.Types.TransferGovernor)
{
uint32 _newDomain = _msg.domain();
address _newGovernor = TypeCasts.bytes32ToAddress(_msg.governor());
bool _isLocalGovernor = _isLocalDomain(_newDomain);
_transferGovernor(_newDomain, _newGovernor, _isLocalGovernor);
}
/**
* @notice Handle message setting the router address for a given domain
* @param _msg The message
*/
function _handleSetRouter(bytes29 _msg)
internal
typeAssert(_msg, GovernanceMessage.Types.SetRouter)
{
uint32 _domain = _msg.domain();
bytes32 _router = _msg.router();
_setRouter(_domain, _router);
}
/**
* @notice Dispatch message to all remote routers
* @param _msg The message
*/
function _sendToAllRemoteRouters(bytes memory _msg) internal {
Home _home = Home(xAppConnectionManager.home());
for (uint256 i = 0; i < domains.length; i++) {
if (domains[i] != uint32(0)) {
_home.dispatch(domains[i], routers[domains[i]], _msg);
}
}
}
/**
* @notice Dispatch call locally
* @param _call The call
* @return _ret
*/
function _dispatchCall(GovernanceMessage.Call memory _call)
internal
returns (bytes memory _ret)
{
address _toContract = TypeCasts.bytes32ToAddress(_call.to);
// attempt to dispatch using low-level call
bool _success;
(_success, _ret) = _toContract.call(_call.data);
// revert if the call failed
require(_success, "call failed");
}
/**
* @notice Transfer governorship within this contract's state
* @param _newDomain The domain of the new governor
* @param _newGovernor The address of the new governor
* @param _isLocalGovernor True if the newDomain is the localDomain
*/
function _transferGovernor(
uint32 _newDomain,
address _newGovernor,
bool _isLocalGovernor
) internal {
// require that the governor domain has a valid router
if (!_isLocalGovernor) {
_mustHaveRouter(_newDomain);
}
// Governor is 0x0 unless the governor is local
address _newGov = _isLocalGovernor ? _newGovernor : address(0);
// emit event before updating state variables
emit TransferGovernor(governorDomain, _newDomain, governor, _newGov);
// update state
governorDomain = _newDomain;
governor = _newGov;
}
/**
* @notice Set the router for a given domain
* @param _domain The domain
* @param _newRouter The new router
*/
function _setRouter(uint32 _domain, bytes32 _newRouter) internal {
bytes32 _previousRouter = routers[_domain];
// emit event at beginning in case return after remove
emit SetRouter(_domain, _previousRouter, _newRouter);
// if the router is being removed, remove the domain
if (_newRouter == bytes32(0)) {
_removeDomain(_domain);
return;
}
// if the router is being added, add the domain
if (_previousRouter == bytes32(0)) {
_addDomain(_domain);
}
// update state with new router
routers[_domain] = _newRouter;
}
/**
* @notice Add a domain that has a router
* @param _domain The domain
*/
function _addDomain(uint32 _domain) internal {
domains.push(_domain);
}
/**
* @notice Remove a domain and its associated router
* @param _domain The domain
*/
function _removeDomain(uint32 _domain) internal {
delete routers[_domain];
// find the index of the domain to remove & delete it from domains[]
for (uint256 i = 0; i < domains.length; i++) {
if (domains[i] == _domain) {
delete domains[i];
return;
}
}
}
/**
* @notice Determine if a given domain and address is the Governor Router
* @param _domain The domain
* @param _address The address of the domain's router
* @return _ret True if the given domain/address is the
* Governor Router.
*/
function _isGovernorRouter(uint32 _domain, bytes32 _address)
internal
view
returns (bool)
{
return _domain == governorDomain && _address == routers[_domain];
}
/**
* @notice Determine if a given domain is the local domain
* @param _domain The domain
* @return _ret - True if the given domain is the local domain
*/
function _isLocalDomain(uint32 _domain) internal view returns (bool) {
return _domain == localDomain;
}
/**
* @notice Require that a domain has a router and returns the router
* @param _domain The domain
* @return _router - The domain's router
*/
function _mustHaveRouter(uint32 _domain)
internal
view
returns (bytes32 _router)
{
_router = routers[_domain];
require(_router != bytes32(0), "!router");
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {Version0} from "./Version0.sol";
import {Common} from "./Common.sol";
import {QueueLib} from "../libs/Queue.sol";
import {MerkleLib} from "../libs/Merkle.sol";
import {Message} from "../libs/Message.sol";
import {MerkleTreeManager} from "./Merkle.sol";
import {QueueManager} from "./Queue.sol";
import {IUpdaterManager} from "../interfaces/IUpdaterManager.sol";
// ============ External Imports ============
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
/**
* @title Home
* @author Celo Labs Inc.
* @notice Accepts messages to be dispatched to remote chains,
* constructs a Merkle tree of the messages,
* and accepts signatures from a bonded Updater
* which notarize the Merkle tree roots.
* Accepts submissions of fraudulent signatures
* by the Updater and slashes the Updater in this case.
*/
contract Home is
Version0,
QueueManager,
MerkleTreeManager,
Common,
OwnableUpgradeable
{
// ============ Libraries ============
using QueueLib for QueueLib.Queue;
using MerkleLib for MerkleLib.Tree;
// ============ Constants ============
// Maximum bytes per message = 2 KiB
// (somewhat arbitrarily set to begin)
uint256 public constant MAX_MESSAGE_BODY_BYTES = 2 * 2**10;
// ============ Public Storage Variables ============
// domain => next available nonce for the domain
mapping(uint32 => uint32) public nonces;
// contract responsible for Updater bonding, slashing and rotation
IUpdaterManager public updaterManager;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[48] private __GAP;
// ============ Events ============
/**
* @notice Emitted when a new message is dispatched via Optics
* @param leafIndex Index of message's leaf in merkle tree
* @param destinationAndNonce Destination and destination-specific
* nonce combined in single field ((destination << 32) & nonce)
* @param messageHash Hash of message; the leaf inserted to the Merkle tree for the message
* @param committedRoot the latest notarized root submitted in the last signed Update
* @param message Raw bytes of message
*/
event Dispatch(
bytes32 indexed messageHash,
uint256 indexed leafIndex,
uint64 indexed destinationAndNonce,
bytes32 committedRoot,
bytes message
);
/**
* @notice Emitted when proof of an improper update is submitted,
* which sets the contract to FAILED state
* @param oldRoot Old root of the improper update
* @param newRoot New root of the improper update
* @param signature Signature on `oldRoot` and `newRoot
*/
event ImproperUpdate(bytes32 oldRoot, bytes32 newRoot, bytes signature);
/**
* @notice Emitted when the Updater is slashed
* (should be paired with ImproperUpdater or DoubleUpdate event)
* @param updater The address of the updater
* @param reporter The address of the entity that reported the updater misbehavior
*/
event UpdaterSlashed(address indexed updater, address indexed reporter);
/**
* @notice Emitted when Updater is rotated by the UpdaterManager
* @param updater The address of the new updater
*/
event NewUpdater(address updater);
/**
* @notice Emitted when the UpdaterManager contract is changed
* @param updaterManager The address of the new updaterManager
*/
event NewUpdaterManager(address updaterManager);
// ============ Constructor ============
constructor(uint32 _localDomain) Common(_localDomain) {} // solhint-disable-line no-empty-blocks
// ============ Initializer ============
function initialize(IUpdaterManager _updaterManager) public initializer {
// initialize owner & queue
__Ownable_init();
__QueueManager_initialize();
// set Updater Manager contract and initialize Updater
_setUpdaterManager(_updaterManager);
address _updater = updaterManager.updater();
__Common_initialize(_updater);
emit NewUpdater(_updater);
}
// ============ Modifiers ============
/**
* @notice Ensures that function is called by the UpdaterManager contract
*/
modifier onlyUpdaterManager() {
require(msg.sender == address(updaterManager), "!updaterManager");
_;
}
// ============ External: Updater & UpdaterManager Configuration ============
/**
* @notice Set a new Updater
* @param _updater the new Updater
*/
function setUpdater(address _updater) external onlyUpdaterManager {
_setUpdater(_updater);
}
/**
* @notice Set a new UpdaterManager contract
* @dev Home(s) will initially be initialized using a trusted UpdaterManager contract;
* we will progressively decentralize by swapping the trusted contract with a new implementation
* that implements Updater bonding & slashing, and rules for Updater selection & rotation
* @param _updaterManager the new UpdaterManager contract
*/
function setUpdaterManager(address _updaterManager) external onlyOwner {
_setUpdaterManager(IUpdaterManager(_updaterManager));
}
// ============ External Functions ============
/**
* @notice Dispatch the message it to the destination domain & recipient
* @dev Format the message, insert its hash into Merkle tree,
* enqueue the new Merkle root, and emit `Dispatch` event with message information.
* @param _destinationDomain Domain of destination chain
* @param _recipientAddress Address of recipient on destination chain as bytes32
* @param _messageBody Raw bytes content of message
*/
function dispatch(
uint32 _destinationDomain,
bytes32 _recipientAddress,
bytes memory _messageBody
) external notFailed {
require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, "msg too long");
// get the next nonce for the destination domain, then increment it
uint32 _nonce = nonces[_destinationDomain];
nonces[_destinationDomain] = _nonce + 1;
// format the message into packed bytes
bytes memory _message = Message.formatMessage(
localDomain,
bytes32(uint256(uint160(msg.sender))),
_nonce,
_destinationDomain,
_recipientAddress,
_messageBody
);
// insert the hashed message into the Merkle tree
bytes32 _messageHash = keccak256(_message);
tree.insert(_messageHash);
// enqueue the new Merkle root after inserting the message
queue.enqueue(root());
// Emit Dispatch event with message information
// note: leafIndex is count() - 1 since new leaf has already been inserted
emit Dispatch(
_messageHash,
count() - 1,
_destinationAndNonce(_destinationDomain, _nonce),
committedRoot,
_message
);
}
/**
* @notice Submit a signature from the Updater "notarizing" a root,
* which updates the Home contract's `committedRoot`,
* and publishes the signature which will be relayed to Replica contracts
* @dev emits Update event
* @dev If _newRoot is not contained in the queue,
* the Update is a fraudulent Improper Update, so
* the Updater is slashed & Home is set to FAILED state
* @param _committedRoot Current updated merkle root which the update is building off of
* @param _newRoot New merkle root to update the contract state to
* @param _signature Updater signature on `_committedRoot` and `_newRoot`
*/
function update(
bytes32 _committedRoot,
bytes32 _newRoot,
bytes memory _signature
) external notFailed {
// check that the update is not fraudulent;
// if fraud is detected, Updater is slashed & Home is set to FAILED state
if (improperUpdate(_committedRoot, _newRoot, _signature)) return;
// clear all of the intermediate roots contained in this update from the queue
while (true) {
bytes32 _next = queue.dequeue();
if (_next == _newRoot) break;
}
// update the Home state with the latest signed root & emit event
committedRoot = _newRoot;
emit Update(localDomain, _committedRoot, _newRoot, _signature);
}
/**
* @notice Suggest an update for the Updater to sign and submit.
* @dev If queue is empty, null bytes returned for both
* (No update is necessary because no messages have been dispatched since the last update)
* @return _committedRoot Latest root signed by the Updater
* @return _new Latest enqueued Merkle root
*/
function suggestUpdate()
external
view
returns (bytes32 _committedRoot, bytes32 _new)
{
if (queue.length() != 0) {
_committedRoot = committedRoot;
_new = queue.lastItem();
}
}
// ============ Public Functions ============
/**
* @notice Hash of Home domain concatenated with "OPTICS"
*/
function homeDomainHash() public view override returns (bytes32) {
return _homeDomainHash(localDomain);
}
/**
* @notice Check if an Update is an Improper Update;
* if so, slash the Updater and set the contract to FAILED state.
*
* An Improper Update is an update building off of the Home's `committedRoot`
* for which the `_newRoot` does not currently exist in the Home's queue.
* This would mean that message(s) that were not truly
* dispatched on Home were falsely included in the signed root.
*
* An Improper Update will only be accepted as valid by the Replica
* If an Improper Update is attempted on Home,
* the Updater will be slashed immediately.
* If an Improper Update is submitted to the Replica,
* it should be relayed to the Home contract using this function
* in order to slash the Updater with an Improper Update.
*
* An Improper Update submitted to the Replica is only valid
* while the `_oldRoot` is still equal to the `committedRoot` on Home;
* if the `committedRoot` on Home has already been updated with a valid Update,
* then the Updater should be slashed with a Double Update.
* @dev Reverts (and doesn't slash updater) if signature is invalid or
* update not current
* @param _oldRoot Old merkle tree root (should equal home's committedRoot)
* @param _newRoot New merkle tree root
* @param _signature Updater signature on `_oldRoot` and `_newRoot`
* @return TRUE if update was an Improper Update (implying Updater was slashed)
*/
function improperUpdate(
bytes32 _oldRoot,
bytes32 _newRoot,
bytes memory _signature
) public notFailed returns (bool) {
require(
_isUpdaterSignature(_oldRoot, _newRoot, _signature),
"!updater sig"
);
require(_oldRoot == committedRoot, "not a current update");
// if the _newRoot is not currently contained in the queue,
// slash the Updater and set the contract to FAILED state
if (!queue.contains(_newRoot)) {
_fail();
emit ImproperUpdate(_oldRoot, _newRoot, _signature);
return true;
}
// if the _newRoot is contained in the queue,
// this is not an improper update
return false;
}
// ============ Internal Functions ============
/**
* @notice Set the UpdaterManager
* @param _updaterManager Address of the UpdaterManager
*/
function _setUpdaterManager(IUpdaterManager _updaterManager) internal {
require(
Address.isContract(address(_updaterManager)),
"!contract updaterManager"
);
updaterManager = IUpdaterManager(_updaterManager);
emit NewUpdaterManager(address(_updaterManager));
}
/**
* @notice Set the Updater
* @param _updater Address of the Updater
*/
function _setUpdater(address _updater) internal {
updater = _updater;
emit NewUpdater(_updater);
}
/**
* @notice Slash the Updater and set contract state to FAILED
* @dev Called when fraud is proven (Improper Update or Double Update)
*/
function _fail() internal override {
// set contract to FAILED
_setFailed();
// slash Updater
updaterManager.slashUpdater(msg.sender);
emit UpdaterSlashed(updater, msg.sender);
}
/**
* @notice Internal utility function that combines
* `_destination` and `_nonce`.
* @dev Both destination and nonce should be less than 2^32 - 1
* @param _destination Domain of destination chain
* @param _nonce Current nonce for given destination chain
* @return Returns (`_destination` << 32) & `_nonce`
*/
function _destinationAndNonce(uint32 _destination, uint32 _nonce)
internal
pure
returns (uint64)
{
return (uint64(_destination) << 32) | _nonce;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
/**
* @title Version0
* @notice Version getter for contracts
**/
contract Version0 {
uint8 public constant VERSION = 0;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {Home} from "./Home.sol";
import {Replica} from "./Replica.sol";
import {TypeCasts} from "../libs/TypeCasts.sol";
// ============ External Imports ============
import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title XAppConnectionManager
* @author Celo Labs Inc.
* @notice Manages a registry of local Replica contracts
* for remote Home domains. Accepts Watcher signatures
* to un-enroll Replicas attached to fraudulent remote Homes
*/
contract XAppConnectionManager is Ownable {
// ============ Public Storage ============
// Home contract
Home public home;
// local Replica address => remote Home domain
mapping(address => uint32) public replicaToDomain;
// remote Home domain => local Replica address
mapping(uint32 => address) public domainToReplica;
// watcher address => replica remote domain => has/doesn't have permission
mapping(address => mapping(uint32 => bool)) private watcherPermissions;
// ============ Events ============
/**
* @notice Emitted when a new Replica is enrolled / added
* @param domain the remote domain of the Home contract for the Replica
* @param replica the address of the Replica
*/
event ReplicaEnrolled(uint32 indexed domain, address replica);
/**
* @notice Emitted when a new Replica is un-enrolled / removed
* @param domain the remote domain of the Home contract for the Replica
* @param replica the address of the Replica
*/
event ReplicaUnenrolled(uint32 indexed domain, address replica);
/**
* @notice Emitted when Watcher permissions are changed
* @param domain the remote domain of the Home contract for the Replica
* @param watcher the address of the Watcher
* @param access TRUE if the Watcher was given permissions, FALSE if permissions were removed
*/
event WatcherPermissionSet(
uint32 indexed domain,
address watcher,
bool access
);
// ============ Modifiers ============
modifier onlyReplica() {
require(isReplica(msg.sender), "!replica");
_;
}
// ============ Constructor ============
// solhint-disable-next-line no-empty-blocks
constructor() Ownable() {}
// ============ External Functions ============
/**
* @notice Un-Enroll a replica contract
* in the case that fraud was detected on the Home
* @dev in the future, if fraud occurs on the Home contract,
* the Watcher will submit their signature directly to the Home
* and it can be relayed to all remote chains to un-enroll the Replicas
* @param _domain the remote domain of the Home contract for the Replica
* @param _updater the address of the Updater for the Home contract (also stored on Replica)
* @param _signature signature of watcher on (domain, replica address, updater address)
*/
function unenrollReplica(
uint32 _domain,
bytes32 _updater,
bytes memory _signature
) external {
// ensure that the replica is currently set
address _replica = domainToReplica[_domain];
require(_replica != address(0), "!replica exists");
// ensure that the signature is on the proper updater
require(
Replica(_replica).updater() == TypeCasts.bytes32ToAddress(_updater),
"!current updater"
);
// get the watcher address from the signature
// and ensure that the watcher has permission to un-enroll this replica
address _watcher = _recoverWatcherFromSig(
_domain,
TypeCasts.addressToBytes32(_replica),
_updater,
_signature
);
require(watcherPermissions[_watcher][_domain], "!valid watcher");
// remove the replica from mappings
_unenrollReplica(_replica);
}
/**
* @notice Set the address of the local Home contract
* @param _home the address of the local Home contract
*/
function setHome(address _home) external onlyOwner {
home = Home(_home);
}
/**
* @notice Allow Owner to enroll Replica contract
* @param _replica the address of the Replica
* @param _domain the remote domain of the Home contract for the Replica
*/
function ownerEnrollReplica(address _replica, uint32 _domain)
external
onlyOwner
{
// un-enroll any existing replica
_unenrollReplica(_replica);
// add replica and domain to two-way mapping
replicaToDomain[_replica] = _domain;
domainToReplica[_domain] = _replica;
emit ReplicaEnrolled(_domain, _replica);
}
/**
* @notice Allow Owner to un-enroll Replica contract
* @param _replica the address of the Replica
*/
function ownerUnenrollReplica(address _replica) external onlyOwner {
_unenrollReplica(_replica);
}
/**
* @notice Allow Owner to set Watcher permissions for a Replica
* @param _watcher the address of the Watcher
* @param _domain the remote domain of the Home contract for the Replica
* @param _access TRUE to give the Watcher permissions, FALSE to remove permissions
*/
function setWatcherPermission(
address _watcher,
uint32 _domain,
bool _access
) external onlyOwner {
watcherPermissions[_watcher][_domain] = _access;
emit WatcherPermissionSet(_domain, _watcher, _access);
}
/**
* @notice Query local domain from Home
* @return local domain
*/
function localDomain() external view returns (uint32) {
return home.localDomain();
}
/**
* @notice Get access permissions for the watcher on the domain
* @param _watcher the address of the watcher
* @param _domain the domain to check for watcher permissions
* @return TRUE iff _watcher has permission to un-enroll replicas on _domain
*/
function watcherPermission(address _watcher, uint32 _domain)
external
view
returns (bool)
{
return watcherPermissions[_watcher][_domain];
}
// ============ Public Functions ============
/**
* @notice Check whether _replica is enrolled
* @param _replica the replica to check for enrollment
* @return TRUE iff _replica is enrolled
*/
function isReplica(address _replica) public view returns (bool) {
return replicaToDomain[_replica] != 0;
}
// ============ Internal Functions ============
/**
* @notice Remove the replica from the two-way mappings
* @param _replica replica to un-enroll
*/
function _unenrollReplica(address _replica) internal {
uint32 _currentDomain = replicaToDomain[_replica];
domainToReplica[_currentDomain] = address(0);
replicaToDomain[_replica] = 0;
emit ReplicaUnenrolled(_currentDomain, _replica);
}
/**
* @notice Get the Watcher address from the provided signature
* @return address of watcher that signed
*/
function _recoverWatcherFromSig(
uint32 _domain,
bytes32 _replica,
bytes32 _updater,
bytes memory _signature
) internal view returns (address) {
bytes32 _homeDomainHash = Replica(TypeCasts.bytes32ToAddress(_replica))
.homeDomainHash();
bytes32 _digest = keccak256(
abi.encodePacked(_homeDomainHash, _domain, _updater)
);
_digest = ECDSA.toEthSignedMessageHash(_digest);
return ECDSA.recover(_digest, _signature);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
interface IMessageRecipient {
function handle(
uint32 _origin,
bytes32 _sender,
bytes memory _message
) external;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
pragma experimental ABIEncoderV2;
// ============ External Imports ============
import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol";
library GovernanceMessage {
using TypedMemView for bytes;
using TypedMemView for bytes29;
uint256 private constant CALL_PREFIX_LEN = 64;
uint256 private constant MSG_PREFIX_NUM_ITEMS = 2;
uint256 private constant MSG_PREFIX_LEN = 2;
uint256 private constant GOV_ACTION_LEN = 37;
enum Types {
Invalid, // 0
Call, // 1
TransferGovernor, // 2
SetRouter, // 3
Data // 4
}
struct Call {
bytes32 to;
bytes data;
}
modifier typeAssert(bytes29 _view, Types _t) {
_view.assertType(uint40(_t));
_;
}
// Types.Call
function data(bytes29 _view) internal view returns (bytes memory _data) {
_data = TypedMemView.clone(
_view.slice(CALL_PREFIX_LEN, dataLen(_view), uint40(Types.Data))
);
}
function formatCalls(Call[] memory _calls)
internal
view
returns (bytes memory _msg)
{
uint256 _numCalls = _calls.length;
bytes29[] memory _encodedCalls = new bytes29[](
_numCalls + MSG_PREFIX_NUM_ITEMS
);
// Add Types.Call identifier
_encodedCalls[0] = abi.encodePacked(Types.Call).ref(0);
// Add number of calls
_encodedCalls[1] = abi.encodePacked(uint8(_numCalls)).ref(0);
for (uint256 i = 0; i < _numCalls; i++) {
Call memory _call = _calls[i];
bytes29 _callMsg = abi
.encodePacked(_call.to, _call.data.length, _call.data)
.ref(0);
_encodedCalls[i + MSG_PREFIX_NUM_ITEMS] = _callMsg;
}
_msg = TypedMemView.join(_encodedCalls);
}
function formatTransferGovernor(uint32 _domain, bytes32 _governor)
internal
view
returns (bytes memory _msg)
{
_msg = TypedMemView.clone(
mustBeTransferGovernor(
abi
.encodePacked(Types.TransferGovernor, _domain, _governor)
.ref(0)
)
);
}
function formatSetRouter(uint32 _domain, bytes32 _router)
internal
view
returns (bytes memory _msg)
{
_msg = TypedMemView.clone(
mustBeSetRouter(
abi.encodePacked(Types.SetRouter, _domain, _router).ref(0)
)
);
}
function getCalls(bytes29 _msg) internal view returns (Call[] memory) {
uint8 _numCalls = uint8(_msg.indexUint(1, 1));
// Skip message prefix
bytes29 _msgPtr = _msg.slice(
MSG_PREFIX_LEN,
_msg.len() - MSG_PREFIX_LEN,
uint40(Types.Call)
);
Call[] memory _calls = new Call[](_numCalls);
uint256 counter = 0;
while (_msgPtr.len() > 0) {
_calls[counter].to = to(_msgPtr);
_calls[counter].data = data(_msgPtr);
_msgPtr = nextCall(_msgPtr);
counter++;
}
return _calls;
}
function nextCall(bytes29 _view)
internal
pure
typeAssert(_view, Types.Call)
returns (bytes29)
{
uint256 lastCallLen = CALL_PREFIX_LEN + dataLen(_view);
return
_view.slice(
lastCallLen,
_view.len() - lastCallLen,
uint40(Types.Call)
);
}
function messageType(bytes29 _view) internal pure returns (Types) {
return Types(uint8(_view.typeOf()));
}
/*
Message fields
*/
// All Types
function identifier(bytes29 _view) internal pure returns (uint8) {
return uint8(_view.indexUint(0, 1));
}
// Types.Call
function to(bytes29 _view) internal pure returns (bytes32) {
return _view.index(0, 32);
}
// Types.Call
function dataLen(bytes29 _view) internal pure returns (uint256) {
return uint256(_view.index(32, 32));
}
// Types.TransferGovernor & Types.EnrollRemote
function domain(bytes29 _view) internal pure returns (uint32) {
return uint32(_view.indexUint(1, 4));
}
// Types.EnrollRemote
function router(bytes29 _view) internal pure returns (bytes32) {
return _view.index(5, 32);
}
// Types.TransferGovernor
function governor(bytes29 _view) internal pure returns (bytes32) {
return _view.index(5, 32);
}
/*
Message Type: CALL
struct Call {
identifier, // message ID -- 1 byte
numCalls, // number of calls -- 1 byte
calls[], {
to, // address to call -- 32 bytes
dataLen, // call data length -- 32 bytes,
data // call data -- 0+ bytes (length unknown)
}
}
*/
function isValidCall(bytes29 _view) internal pure returns (bool) {
return
identifier(_view) == uint8(Types.Call) &&
_view.len() >= CALL_PREFIX_LEN;
}
function isCall(bytes29 _view) internal pure returns (bool) {
return isValidCall(_view) && messageType(_view) == Types.Call;
}
function tryAsCall(bytes29 _view) internal pure returns (bytes29) {
if (isValidCall(_view)) {
return _view.castTo(uint40(Types.Call));
}
return TypedMemView.nullView();
}
function mustBeCalls(bytes29 _view) internal pure returns (bytes29) {
return tryAsCall(_view).assertValid();
}
/*
Message Type: TRANSFER GOVERNOR
struct TransferGovernor {
identifier, // message ID -- 1 byte
domain, // domain of new governor -- 4 bytes
addr // address of new governor -- 32 bytes
}
*/
function isValidTransferGovernor(bytes29 _view)
internal
pure
returns (bool)
{
return
identifier(_view) == uint8(Types.TransferGovernor) &&
_view.len() == GOV_ACTION_LEN;
}
function isTransferGovernor(bytes29 _view) internal pure returns (bool) {
return
isValidTransferGovernor(_view) &&
messageType(_view) == Types.TransferGovernor;
}
function tryAsTransferGovernor(bytes29 _view)
internal
pure
returns (bytes29)
{
if (isValidTransferGovernor(_view)) {
return _view.castTo(uint40(Types.TransferGovernor));
}
return TypedMemView.nullView();
}
function mustBeTransferGovernor(bytes29 _view)
internal
pure
returns (bytes29)
{
return tryAsTransferGovernor(_view).assertValid();
}
/*
Message Type: ENROLL ROUTER
struct SetRouter {
identifier, // message ID -- 1 byte
domain, // domain of new router -- 4 bytes
addr // address of new router -- 32 bytes
}
*/
function isValidSetRouter(bytes29 _view) internal pure returns (bool) {
return
identifier(_view) == uint8(Types.SetRouter) &&
_view.len() == GOV_ACTION_LEN;
}
function isSetRouter(bytes29 _view) internal pure returns (bool) {
return isValidSetRouter(_view) && messageType(_view) == Types.SetRouter;
}
function tryAsSetRouter(bytes29 _view) internal pure returns (bytes29) {
if (isValidSetRouter(_view)) {
return _view.castTo(uint40(Types.SetRouter));
}
return TypedMemView.nullView();
}
function mustBeSetRouter(bytes29 _view) internal pure returns (bytes29) {
return tryAsSetRouter(_view).assertValid();
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/Address.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 !Address.isContract(address(this));
}
}
// 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 OR Apache-2.0
pragma solidity >=0.5.10;
import {SafeMath} from "./SafeMath.sol";
library TypedMemView {
using SafeMath for uint256;
// Why does this exist?
// the solidity `bytes memory` type has a few weaknesses.
// 1. You can't index ranges effectively
// 2. You can't slice without copying
// 3. The underlying data may represent any type
// 4. Solidity never deallocates memory, and memory costs grow
// superlinearly
// By using a memory view instead of a `bytes memory` we get the following
// advantages:
// 1. Slices are done on the stack, by manipulating the pointer
// 2. We can index arbitrary ranges and quickly convert them to stack types
// 3. We can insert type info into the pointer, and typecheck at runtime
// This makes `TypedMemView` a useful tool for efficient zero-copy
// algorithms.
// Why bytes29?
// We want to avoid confusion between views, digests, and other common
// types so we chose a large and uncommonly used odd number of bytes
//
// Note that while bytes are left-aligned in a word, integers and addresses
// are right-aligned. This means when working in assembly we have to
// account for the 3 unused bytes on the righthand side
//
// First 5 bytes are a type flag.
// - ff_ffff_fffe is reserved for unknown type.
// - ff_ffff_ffff is reserved for invalid types/errors.
// next 12 are memory address
// next 12 are len
// bottom 3 bytes are empty
// Assumptions:
// - non-modification of memory.
// - No Solidity updates
// - - wrt free mem point
// - - wrt bytes representation in memory
// - - wrt memory addressing in general
// Usage:
// - create type constants
// - use `assertType` for runtime type assertions
// - - unfortunately we can't do this at compile time yet :(
// - recommended: implement modifiers that perform type checking
// - - e.g.
// - - `uint40 constant MY_TYPE = 3;`
// - - ` modifer onlyMyType(bytes29 myView) { myView.assertType(MY_TYPE); }`
// - instantiate a typed view from a bytearray using `ref`
// - use `index` to inspect the contents of the view
// - use `slice` to create smaller views into the same memory
// - - `slice` can increase the offset
// - - `slice can decrease the length`
// - - must specify the output type of `slice`
// - - `slice` will return a null view if you try to overrun
// - - make sure to explicitly check for this with `notNull` or `assertType`
// - use `equal` for typed comparisons.
// The null view
bytes29 public constant NULL = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
uint256 constant LOW_12_MASK = 0xffffffffffffffffffffffff;
uint8 constant TWELVE_BYTES = 96;
/**
* @notice Returns the encoded hex character that represents the lower 4 bits of the argument.
* @param _b The byte
* @return char - The encoded hex character
*/
function nibbleHex(uint8 _b) internal pure returns (uint8 char) {
// This can probably be done more efficiently, but it's only in error
// paths, so we don't really care :)
uint8 _nibble = _b | 0xf0; // set top 4, keep bottom 4
if (_nibble == 0xf0) {return 0x30;} // 0
if (_nibble == 0xf1) {return 0x31;} // 1
if (_nibble == 0xf2) {return 0x32;} // 2
if (_nibble == 0xf3) {return 0x33;} // 3
if (_nibble == 0xf4) {return 0x34;} // 4
if (_nibble == 0xf5) {return 0x35;} // 5
if (_nibble == 0xf6) {return 0x36;} // 6
if (_nibble == 0xf7) {return 0x37;} // 7
if (_nibble == 0xf8) {return 0x38;} // 8
if (_nibble == 0xf9) {return 0x39;} // 9
if (_nibble == 0xfa) {return 0x61;} // a
if (_nibble == 0xfb) {return 0x62;} // b
if (_nibble == 0xfc) {return 0x63;} // c
if (_nibble == 0xfd) {return 0x64;} // d
if (_nibble == 0xfe) {return 0x65;} // e
if (_nibble == 0xff) {return 0x66;} // f
}
/**
* @notice Returns a uint16 containing the hex-encoded byte.
* @param _b The byte
* @return encoded - The hex-encoded byte
*/
function byteHex(uint8 _b) internal pure returns (uint16 encoded) {
encoded |= nibbleHex(_b >> 4); // top 4 bits
encoded <<= 8;
encoded |= nibbleHex(_b); // lower 4 bits
}
/**
* @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes.
* `second` contains the encoded lower 16 bytes.
*
* @param _b The 32 bytes as uint256
* @return first - The top 16 bytes
* @return second - The bottom 16 bytes
*/
function encodeHex(uint256 _b) internal pure returns (uint256 first, uint256 second) {
for (uint8 i = 31; i > 15; i -= 1) {
uint8 _byte = uint8(_b >> (i * 8));
first |= byteHex(_byte);
if (i != 16) {
first <<= 16;
}
}
// abusing underflow here =_=
for (uint8 i = 15; i < 255 ; i -= 1) {
uint8 _byte = uint8(_b >> (i * 8));
second |= byteHex(_byte);
if (i != 0) {
second <<= 16;
}
}
}
/**
* @notice Changes the endianness of a uint256.
* @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
* @param _b The unsigned integer to reverse
* @return v - The reversed value
*/
function reverseUint256(uint256 _b) internal pure returns (uint256 v) {
v = _b;
// swap bytes
v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
// swap 8-byte long pairs
v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
// swap 16-byte long pairs
v = (v >> 128) | (v << 128);
}
/**
* @notice Create a mask with the highest `_len` bits set.
* @param _len The length
* @return mask - The mask
*/
function leftMask(uint8 _len) private pure returns (uint256 mask) {
// ugly. redo without assembly?
assembly {
// solium-disable-previous-line security/no-inline-assembly
mask := sar(
sub(_len, 1),
0x8000000000000000000000000000000000000000000000000000000000000000
)
}
}
/**
* @notice Return the null view.
* @return bytes29 - The null view
*/
function nullView() internal pure returns (bytes29) {
return NULL;
}
/**
* @notice Check if the view is null.
* @return bool - True if the view is null
*/
function isNull(bytes29 memView) internal pure returns (bool) {
return memView == NULL;
}
/**
* @notice Check if the view is not null.
* @return bool - True if the view is not null
*/
function notNull(bytes29 memView) internal pure returns (bool) {
return !isNull(memView);
}
/**
* @notice Check if the view is of a valid type and points to a valid location
* in memory.
* @dev We perform this check by examining solidity's unallocated memory
* pointer and ensuring that the view's upper bound is less than that.
* @param memView The view
* @return ret - True if the view is valid
*/
function isValid(bytes29 memView) internal pure returns (bool ret) {
if (typeOf(memView) == 0xffffffffff) {return false;}
uint256 _end = end(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
ret := not(gt(_end, mload(0x40)))
}
}
/**
* @notice Require that a typed memory view be valid.
* @dev Returns the view for easy chaining.
* @param memView The view
* @return bytes29 - The validated view
*/
function assertValid(bytes29 memView) internal pure returns (bytes29) {
require(isValid(memView), "Validity assertion failed");
return memView;
}
/**
* @notice Return true if the memview is of the expected type. Otherwise false.
* @param memView The view
* @param _expected The expected type
* @return bool - True if the memview is of the expected type
*/
function isType(bytes29 memView, uint40 _expected) internal pure returns (bool) {
return typeOf(memView) == _expected;
}
/**
* @notice Require that a typed memory view has a specific type.
* @dev Returns the view for easy chaining.
* @param memView The view
* @param _expected The expected type
* @return bytes29 - The view with validated type
*/
function assertType(bytes29 memView, uint40 _expected) internal pure returns (bytes29) {
if (!isType(memView, _expected)) {
(, uint256 g) = encodeHex(uint256(typeOf(memView)));
(, uint256 e) = encodeHex(uint256(_expected));
string memory err = string(
abi.encodePacked(
"Type assertion failed. Got 0x",
uint80(g),
". Expected 0x",
uint80(e)
)
);
revert(err);
}
return memView;
}
/**
* @notice Return an identical view with a different type.
* @param memView The view
* @param _newType The new type
* @return newView - The new view with the specified type
*/
function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) {
// then | in the new type
assembly {
// solium-disable-previous-line security/no-inline-assembly
// shift off the top 5 bytes
newView := or(newView, shr(40, shl(40, memView)))
newView := or(newView, shl(216, _newType))
}
}
/**
* @notice Unsafe raw pointer construction. This should generally not be called
* directly. Prefer `ref` wherever possible.
* @dev Unsafe raw pointer construction. This should generally not be called
* directly. Prefer `ref` wherever possible.
* @param _type The type
* @param _loc The memory address
* @param _len The length
* @return newView - The new view with the specified type, location and length
*/
function unsafeBuildUnchecked(uint256 _type, uint256 _loc, uint256 _len) private pure returns (bytes29 newView) {
assembly {
// solium-disable-previous-line security/no-inline-assembly
newView := shl(96, or(newView, _type)) // insert type
newView := shl(96, or(newView, _loc)) // insert loc
newView := shl(24, or(newView, _len)) // empty bottom 3 bytes
}
}
/**
* @notice Instantiate a new memory view. This should generally not be called
* directly. Prefer `ref` wherever possible.
* @dev Instantiate a new memory view. This should generally not be called
* directly. Prefer `ref` wherever possible.
* @param _type The type
* @param _loc The memory address
* @param _len The length
* @return newView - The new view with the specified type, location and length
*/
function build(uint256 _type, uint256 _loc, uint256 _len) internal pure returns (bytes29 newView) {
uint256 _end = _loc.add(_len);
assembly {
// solium-disable-previous-line security/no-inline-assembly
if gt(_end, mload(0x40)) {
_end := 0
}
}
if (_end == 0) {
return NULL;
}
newView = unsafeBuildUnchecked(_type, _loc, _len);
}
/**
* @notice Instantiate a memory view from a byte array.
* @dev Note that due to Solidity memory representation, it is not possible to
* implement a deref, as the `bytes` type stores its len in memory.
* @param arr The byte array
* @param newType The type
* @return bytes29 - The memory view
*/
function ref(bytes memory arr, uint40 newType) internal pure returns (bytes29) {
uint256 _len = arr.length;
uint256 _loc;
assembly {
// solium-disable-previous-line security/no-inline-assembly
_loc := add(arr, 0x20) // our view is of the data, not the struct
}
return build(newType, _loc, _len);
}
/**
* @notice Return the associated type information.
* @param memView The memory view
* @return _type - The type associated with the view
*/
function typeOf(bytes29 memView) internal pure returns (uint40 _type) {
assembly {
// solium-disable-previous-line security/no-inline-assembly
// 216 == 256 - 40
_type := shr(216, memView) // shift out lower 24 bytes
}
}
/**
* @notice Optimized type comparison. Checks that the 5-byte type flag is equal.
* @param left The first view
* @param right The second view
* @return bool - True if the 5-byte type flag is equal
*/
function sameType(bytes29 left, bytes29 right) internal pure returns (bool) {
return (left ^ right) >> (2 * TWELVE_BYTES) == 0;
}
/**
* @notice Return the memory address of the underlying bytes.
* @param memView The view
* @return _loc - The memory address
*/
function loc(bytes29 memView) internal pure returns (uint96 _loc) {
uint256 _mask = LOW_12_MASK; // assembly can't use globals
assembly {
// solium-disable-previous-line security/no-inline-assembly
// 120 bits = 12 bytes (the encoded loc) + 3 bytes (empty low space)
_loc := and(shr(120, memView), _mask)
}
}
/**
* @notice The number of memory words this memory view occupies, rounded up.
* @param memView The view
* @return uint256 - The number of memory words
*/
function words(bytes29 memView) internal pure returns (uint256) {
return uint256(len(memView)).add(32) / 32;
}
/**
* @notice The in-memory footprint of a fresh copy of the view.
* @param memView The view
* @return uint256 - The in-memory footprint of a fresh copy of the view.
*/
function footprint(bytes29 memView) internal pure returns (uint256) {
return words(memView) * 32;
}
/**
* @notice The number of bytes of the view.
* @param memView The view
* @return _len - The length of the view
*/
function len(bytes29 memView) internal pure returns (uint96 _len) {
uint256 _mask = LOW_12_MASK; // assembly can't use globals
assembly {
// solium-disable-previous-line security/no-inline-assembly
_len := and(shr(24, memView), _mask)
}
}
/**
* @notice Returns the endpoint of `memView`.
* @param memView The view
* @return uint256 - The endpoint of `memView`
*/
function end(bytes29 memView) internal pure returns (uint256) {
return loc(memView) + len(memView);
}
/**
* @notice Safe slicing without memory modification.
* @param memView The view
* @param _index The start index
* @param _len The length
* @param newType The new type
* @return bytes29 - The new view
*/
function slice(bytes29 memView, uint256 _index, uint256 _len, uint40 newType) internal pure returns (bytes29) {
uint256 _loc = loc(memView);
// Ensure it doesn't overrun the view
if (_loc.add(_index).add(_len) > end(memView)) {
return NULL;
}
_loc = _loc.add(_index);
return build(newType, _loc, _len);
}
/**
* @notice Shortcut to `slice`. Gets a view representing the first `_len` bytes.
* @param memView The view
* @param _len The length
* @param newType The new type
* @return bytes29 - The new view
*/
function prefix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) {
return slice(memView, 0, _len, newType);
}
/**
* @notice Shortcut to `slice`. Gets a view representing the last `_len` byte.
* @param memView The view
* @param _len The length
* @param newType The new type
* @return bytes29 - The new view
*/
function postfix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) {
return slice(memView, uint256(len(memView)).sub(_len), _len, newType);
}
/**
* @notice Construct an error message for an indexing overrun.
* @param _loc The memory address
* @param _len The length
* @param _index The index
* @param _slice The slice where the overrun occurred
* @return err - The err
*/
function indexErrOverrun(
uint256 _loc,
uint256 _len,
uint256 _index,
uint256 _slice
) internal pure returns (string memory err) {
(, uint256 a) = encodeHex(_loc);
(, uint256 b) = encodeHex(_len);
(, uint256 c) = encodeHex(_index);
(, uint256 d) = encodeHex(_slice);
err = string(
abi.encodePacked(
"TypedMemView/index - Overran the view. Slice is at 0x",
uint48(a),
" with length 0x",
uint48(b),
". Attempted to index at offset 0x",
uint48(c),
" with length 0x",
uint48(d),
"."
)
);
}
/**
* @notice Load up to 32 bytes from the view onto the stack.
* @dev Returns a bytes32 with only the `_bytes` highest bytes set.
* This can be immediately cast to a smaller fixed-length byte array.
* To automatically cast to an integer, use `indexUint`.
* @param memView The view
* @param _index The index
* @param _bytes The bytes
* @return result - The 32 byte result
*/
function index(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (bytes32 result) {
if (_bytes == 0) {return bytes32(0);}
if (_index.add(_bytes) > len(memView)) {
revert(indexErrOverrun(loc(memView), len(memView), _index, uint256(_bytes)));
}
require(_bytes <= 32, "TypedMemView/index - Attempted to index more than 32 bytes");
uint8 bitLength = _bytes * 8;
uint256 _loc = loc(memView);
uint256 _mask = leftMask(bitLength);
assembly {
// solium-disable-previous-line security/no-inline-assembly
result := and(mload(add(_loc, _index)), _mask)
}
}
/**
* @notice Parse an unsigned integer from the view at `_index`.
* @dev Requires that the view have >= `_bytes` bytes following that index.
* @param memView The view
* @param _index The index
* @param _bytes The bytes
* @return result - The unsigned integer
*/
function indexUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) {
return uint256(index(memView, _index, _bytes)) >> ((32 - _bytes) * 8);
}
/**
* @notice Parse an unsigned integer from LE bytes.
* @param memView The view
* @param _index The index
* @param _bytes The bytes
* @return result - The unsigned integer
*/
function indexLEUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) {
return reverseUint256(uint256(index(memView, _index, _bytes)));
}
/**
* @notice Parse an address from the view at `_index`. Requires that the view have >= 20 bytes
* following that index.
* @param memView The view
* @param _index The index
* @return address - The address
*/
function indexAddress(bytes29 memView, uint256 _index) internal pure returns (address) {
return address(uint160(indexUint(memView, _index, 20)));
}
/**
* @notice Return the keccak256 hash of the underlying memory
* @param memView The view
* @return digest - The keccak256 hash of the underlying memory
*/
function keccak(bytes29 memView) internal pure returns (bytes32 digest) {
uint256 _loc = loc(memView);
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
digest := keccak256(_loc, _len)
}
}
/**
* @notice Return the sha2 digest of the underlying memory.
* @dev We explicitly deallocate memory afterwards.
* @param memView The view
* @return digest - The sha2 hash of the underlying memory
*/
function sha2(bytes29 memView) internal view returns (bytes32 digest) {
uint256 _loc = loc(memView);
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
let ptr := mload(0x40)
pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1
digest := mload(ptr)
}
}
/**
* @notice Implements bitcoin's hash160 (rmd160(sha2()))
* @param memView The pre-image
* @return digest - the Digest
*/
function hash160(bytes29 memView) internal view returns (bytes20 digest) {
uint256 _loc = loc(memView);
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
let ptr := mload(0x40)
pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2
pop(staticcall(gas(), 3, ptr, 0x20, ptr, 0x20)) // rmd160
digest := mload(add(ptr, 0xc)) // return value is 0-prefixed.
}
}
/**
* @notice Implements bitcoin's hash256 (double sha2)
* @param memView A view of the preimage
* @return digest - the Digest
*/
function hash256(bytes29 memView) internal view returns (bytes32 digest) {
uint256 _loc = loc(memView);
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
let ptr := mload(0x40)
pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1
pop(staticcall(gas(), 2, ptr, 0x20, ptr, 0x20)) // sha2 #2
digest := mload(ptr)
}
}
/**
* @notice Return true if the underlying memory is equal. Else false.
* @param left The first view
* @param right The second view
* @return bool - True if the underlying memory is equal
*/
function untypedEqual(bytes29 left, bytes29 right) internal pure returns (bool) {
return (loc(left) == loc(right) && len(left) == len(right)) || keccak(left) == keccak(right);
}
/**
* @notice Return false if the underlying memory is equal. Else true.
* @param left The first view
* @param right The second view
* @return bool - False if the underlying memory is equal
*/
function untypedNotEqual(bytes29 left, bytes29 right) internal pure returns (bool) {
return !untypedEqual(left, right);
}
/**
* @notice Compares type equality.
* @dev Shortcuts if the pointers are identical, otherwise compares type and digest.
* @param left The first view
* @param right The second view
* @return bool - True if the types are the same
*/
function equal(bytes29 left, bytes29 right) internal pure returns (bool) {
return left == right || (typeOf(left) == typeOf(right) && keccak(left) == keccak(right));
}
/**
* @notice Compares type inequality.
* @dev Shortcuts if the pointers are identical, otherwise compares type and digest.
* @param left The first view
* @param right The second view
* @return bool - True if the types are not the same
*/
function notEqual(bytes29 left, bytes29 right) internal pure returns (bool) {
return !equal(left, right);
}
/**
* @notice Copy the view to a location, return an unsafe memory reference
* @dev Super Dangerous direct memory access.
*
* This reference can be overwritten if anything else modifies memory (!!!).
* As such it MUST be consumed IMMEDIATELY.
* This function is private to prevent unsafe usage by callers.
* @param memView The view
* @param _newLoc The new location
* @return written - the unsafe memory reference
*/
function unsafeCopyTo(bytes29 memView, uint256 _newLoc) private view returns (bytes29 written) {
require(notNull(memView), "TypedMemView/copyTo - Null pointer deref");
require(isValid(memView), "TypedMemView/copyTo - Invalid pointer deref");
uint256 _len = len(memView);
uint256 _oldLoc = loc(memView);
uint256 ptr;
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40)
// revert if we're writing in occupied memory
if gt(ptr, _newLoc) {
revert(0x60, 0x20) // empty revert message
}
// use the identity precompile to copy
// guaranteed not to fail, so pop the success
pop(staticcall(gas(), 4, _oldLoc, _len, _newLoc, _len))
}
written = unsafeBuildUnchecked(typeOf(memView), _newLoc, _len);
}
/**
* @notice Copies the referenced memory to a new loc in memory, returning a `bytes` pointing to
* the new memory
* @dev Shortcuts if the pointers are identical, otherwise compares type and digest.
* @param memView The view
* @return ret - The view pointing to the new memory
*/
function clone(bytes29 memView) internal view returns (bytes memory ret) {
uint256 ptr;
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40) // load unused memory pointer
ret := ptr
}
unsafeCopyTo(memView, ptr + 0x20);
assembly {
// solium-disable-previous-line security/no-inline-assembly
mstore(0x40, add(add(ptr, _len), 0x20)) // write new unused pointer
mstore(ptr, _len) // write len of new array (in bytes)
}
}
/**
* @notice Join the views in memory, return an unsafe reference to the memory.
* @dev Super Dangerous direct memory access.
*
* This reference can be overwritten if anything else modifies memory (!!!).
* As such it MUST be consumed IMMEDIATELY.
* This function is private to prevent unsafe usage by callers.
* @param memViews The views
* @return unsafeView - The conjoined view pointing to the new memory
*/
function unsafeJoin(bytes29[] memory memViews, uint256 _location) private view returns (bytes29 unsafeView) {
assembly {
// solium-disable-previous-line security/no-inline-assembly
let ptr := mload(0x40)
// revert if we're writing in occupied memory
if gt(ptr, _location) {
revert(0x60, 0x20) // empty revert message
}
}
uint256 _offset = 0;
for (uint256 i = 0; i < memViews.length; i ++) {
bytes29 memView = memViews[i];
unsafeCopyTo(memView, _location + _offset);
_offset += len(memView);
}
unsafeView = unsafeBuildUnchecked(0, _location, _offset);
}
/**
* @notice Produce the keccak256 digest of the concatenated contents of multiple views.
* @param memViews The views
* @return bytes32 - The keccak256 digest
*/
function joinKeccak(bytes29[] memory memViews) internal view returns (bytes32) {
uint256 ptr;
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40) // load unused memory pointer
}
return keccak(unsafeJoin(memViews, ptr));
}
/**
* @notice Produce the sha256 digest of the concatenated contents of multiple views.
* @param memViews The views
* @return bytes32 - The sha256 digest
*/
function joinSha2(bytes29[] memory memViews) internal view returns (bytes32) {
uint256 ptr;
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40) // load unused memory pointer
}
return sha2(unsafeJoin(memViews, ptr));
}
/**
* @notice copies all views, joins them into a new bytearray.
* @param memViews The views
* @return ret - The new byte array
*/
function join(bytes29[] memory memViews) internal view returns (bytes memory ret) {
uint256 ptr;
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40) // load unused memory pointer
}
bytes29 _newView = unsafeJoin(memViews, ptr + 0x20);
uint256 _written = len(_newView);
uint256 _footprint = footprint(_newView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
// store the legnth
mstore(ptr, _written)
// new pointer is old + 0x20 + the footprint of the body
mstore(0x40, add(add(ptr, _footprint), 0x20))
ret := ptr
}
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {Message} from "../libs/Message.sol";
// ============ External Imports ============
import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title Common
* @author Celo Labs Inc.
* @notice Shared utilities between Home and Replica.
*/
abstract contract Common is Initializable {
// ============ Enums ============
// States:
// 0 - UnInitialized - before initialize function is called
// note: the contract is initialized at deploy time, so it should never be in this state
// 1 - Active - as long as the contract has not become fraudulent
// 2 - Failed - after a valid fraud proof has been submitted;
// contract will no longer accept updates or new messages
enum States {
UnInitialized,
Active,
Failed
}
// ============ Immutable Variables ============
// Domain of chain on which the contract is deployed
uint32 public immutable localDomain;
// ============ Public Variables ============
// Address of bonded Updater
address public updater;
// Current state of contract
States public state;
// The latest root that has been signed by the Updater
bytes32 public committedRoot;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[47] private __GAP;
// ============ Events ============
/**
* @notice Emitted when update is made on Home
* or unconfirmed update root is submitted on Replica
* @param homeDomain Domain of home contract
* @param oldRoot Old merkle root
* @param newRoot New merkle root
* @param signature Updater's signature on `oldRoot` and `newRoot`
*/
event Update(
uint32 indexed homeDomain,
bytes32 indexed oldRoot,
bytes32 indexed newRoot,
bytes signature
);
/**
* @notice Emitted when proof of a double update is submitted,
* which sets the contract to FAILED state
* @param oldRoot Old root shared between two conflicting updates
* @param newRoot Array containing two conflicting new roots
* @param signature Signature on `oldRoot` and `newRoot`[0]
* @param signature2 Signature on `oldRoot` and `newRoot`[1]
*/
event DoubleUpdate(
bytes32 oldRoot,
bytes32[2] newRoot,
bytes signature,
bytes signature2
);
// ============ Modifiers ============
/**
* @notice Ensures that contract state != FAILED when the function is called
*/
modifier notFailed() {
require(state != States.Failed, "failed state");
_;
}
// ============ Constructor ============
constructor(uint32 _localDomain) {
localDomain = _localDomain;
}
// ============ Initializer ============
function __Common_initialize(address _updater) internal initializer {
updater = _updater;
state = States.Active;
}
// ============ External Functions ============
/**
* @notice Called by external agent. Checks that signatures on two sets of
* roots are valid and that the new roots conflict with each other. If both
* cases hold true, the contract is failed and a `DoubleUpdate` event is
* emitted.
* @dev When `fail()` is called on Home, updater is slashed.
* @param _oldRoot Old root shared between two conflicting updates
* @param _newRoot Array containing two conflicting new roots
* @param _signature Signature on `_oldRoot` and `_newRoot`[0]
* @param _signature2 Signature on `_oldRoot` and `_newRoot`[1]
*/
function doubleUpdate(
bytes32 _oldRoot,
bytes32[2] calldata _newRoot,
bytes calldata _signature,
bytes calldata _signature2
) external notFailed {
if (
Common._isUpdaterSignature(_oldRoot, _newRoot[0], _signature) &&
Common._isUpdaterSignature(_oldRoot, _newRoot[1], _signature2) &&
_newRoot[0] != _newRoot[1]
) {
_fail();
emit DoubleUpdate(_oldRoot, _newRoot, _signature, _signature2);
}
}
// ============ Public Functions ============
/**
* @notice Hash of Home domain concatenated with "OPTICS"
*/
function homeDomainHash() public view virtual returns (bytes32);
// ============ Internal Functions ============
/**
* @notice Hash of Home domain concatenated with "OPTICS"
* @param _homeDomain the Home domain to hash
*/
function _homeDomainHash(uint32 _homeDomain)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_homeDomain, "OPTICS"));
}
/**
* @notice Set contract state to FAILED
* @dev Called when a valid fraud proof is submitted
*/
function _setFailed() internal {
state = States.Failed;
}
/**
* @notice Moves the contract into failed state
* @dev Called when fraud is proven
* (Double Update is submitted on Home or Replica,
* or Improper Update is submitted on Home)
*/
function _fail() internal virtual;
/**
* @notice Checks that signature was signed by Updater
* @param _oldRoot Old merkle root
* @param _newRoot New merkle root
* @param _signature Signature on `_oldRoot` and `_newRoot`
* @return TRUE iff signature is valid signed by updater
**/
function _isUpdaterSignature(
bytes32 _oldRoot,
bytes32 _newRoot,
bytes memory _signature
) internal view returns (bool) {
bytes32 _digest = keccak256(
abi.encodePacked(homeDomainHash(), _oldRoot, _newRoot)
);
_digest = ECDSA.toEthSignedMessageHash(_digest);
return (ECDSA.recover(_digest, _signature) == updater);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
/**
* @title QueueLib
* @author Celo Labs Inc.
* @notice Library containing queue struct and operations for queue used by
* Home and Replica.
**/
library QueueLib {
/**
* @notice Queue struct
* @dev Internally keeps track of the `first` and `last` elements through
* indices and a mapping of indices to enqueued elements.
**/
struct Queue {
uint128 first;
uint128 last;
mapping(uint256 => bytes32) queue;
}
/**
* @notice Initializes the queue
* @dev Empty state denoted by _q.first > q._last. Queue initialized
* with _q.first = 1 and _q.last = 0.
**/
function initialize(Queue storage _q) internal {
if (_q.first == 0) {
_q.first = 1;
}
}
/**
* @notice Enqueues a single new element
* @param _item New element to be enqueued
* @return _last Index of newly enqueued element
**/
function enqueue(Queue storage _q, bytes32 _item)
internal
returns (uint128 _last)
{
_last = _q.last + 1;
_q.last = _last;
if (_item != bytes32(0)) {
// saves gas if we're queueing 0
_q.queue[_last] = _item;
}
}
/**
* @notice Dequeues element at front of queue
* @dev Removes dequeued element from storage
* @return _item Dequeued element
**/
function dequeue(Queue storage _q) internal returns (bytes32 _item) {
uint128 _last = _q.last;
uint128 _first = _q.first;
require(_length(_last, _first) != 0, "Empty");
_item = _q.queue[_first];
if (_item != bytes32(0)) {
// saves gas if we're dequeuing 0
delete _q.queue[_first];
}
_q.first = _first + 1;
}
/**
* @notice Batch enqueues several elements
* @param _items Array of elements to be enqueued
* @return _last Index of last enqueued element
**/
function enqueue(Queue storage _q, bytes32[] memory _items)
internal
returns (uint128 _last)
{
_last = _q.last;
for (uint256 i = 0; i < _items.length; i += 1) {
_last += 1;
bytes32 _item = _items[i];
if (_item != bytes32(0)) {
_q.queue[_last] = _item;
}
}
_q.last = _last;
}
/**
* @notice Batch dequeues `_number` elements
* @dev Reverts if `_number` > queue length
* @param _number Number of elements to dequeue
* @return Array of dequeued elements
**/
function dequeue(Queue storage _q, uint256 _number)
internal
returns (bytes32[] memory)
{
uint128 _last = _q.last;
uint128 _first = _q.first;
// Cannot underflow unless state is corrupted
require(_length(_last, _first) >= _number, "Insufficient");
bytes32[] memory _items = new bytes32[](_number);
for (uint256 i = 0; i < _number; i++) {
_items[i] = _q.queue[_first];
delete _q.queue[_first];
_first++;
}
_q.first = _first;
return _items;
}
/**
* @notice Returns true if `_item` is in the queue and false if otherwise
* @dev Linearly scans from _q.first to _q.last looking for `_item`
* @param _item Item being searched for in queue
* @return True if `_item` currently exists in queue, false if otherwise
**/
function contains(Queue storage _q, bytes32 _item)
internal
view
returns (bool)
{
for (uint256 i = _q.first; i <= _q.last; i++) {
if (_q.queue[i] == _item) {
return true;
}
}
return false;
}
/// @notice Returns last item in queue
/// @dev Returns bytes32(0) if queue empty
function lastItem(Queue storage _q) internal view returns (bytes32) {
return _q.queue[_q.last];
}
/// @notice Returns element at front of queue without removing element
/// @dev Reverts if queue is empty
function peek(Queue storage _q) internal view returns (bytes32 _item) {
require(!isEmpty(_q), "Empty");
_item = _q.queue[_q.first];
}
/// @notice Returns true if queue is empty and false if otherwise
function isEmpty(Queue storage _q) internal view returns (bool) {
return _q.last < _q.first;
}
/// @notice Returns number of elements in queue
function length(Queue storage _q) internal view returns (uint256) {
uint128 _last = _q.last;
uint128 _first = _q.first;
// Cannot underflow unless state is corrupted
return _length(_last, _first);
}
/// @notice Returns number of elements between `_last` and `_first` (used internally)
function _length(uint128 _last, uint128 _first)
internal
pure
returns (uint256)
{
return uint256(_last + 1 - _first);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// work based on eth2 deposit contract, which is used under CC0-1.0
/**
* @title MerkleLib
* @author Celo Labs Inc.
* @notice An incremental merkle tree modeled on the eth2 deposit contract.
**/
library MerkleLib {
uint256 internal constant TREE_DEPTH = 32;
uint256 internal constant MAX_LEAVES = 2**TREE_DEPTH - 1;
/**
* @notice Struct representing incremental merkle tree. Contains current
* branch and the number of inserted leaves in the tree.
**/
struct Tree {
bytes32[TREE_DEPTH] branch;
uint256 count;
}
/**
* @notice Inserts `_node` into merkle tree
* @dev Reverts if tree is full
* @param _node Element to insert into tree
**/
function insert(Tree storage _tree, bytes32 _node) internal {
require(_tree.count < MAX_LEAVES, "merkle tree full");
_tree.count += 1;
uint256 size = _tree.count;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
if ((size & 1) == 1) {
_tree.branch[i] = _node;
return;
}
_node = keccak256(abi.encodePacked(_tree.branch[i], _node));
size /= 2;
}
// As the loop should always end prematurely with the `return` statement,
// this code should be unreachable. We assert `false` just to be safe.
assert(false);
}
/**
* @notice Calculates and returns`_tree`'s current root given array of zero
* hashes
* @param _zeroes Array of zero hashes
* @return _current Calculated root of `_tree`
**/
function rootWithCtx(Tree storage _tree, bytes32[TREE_DEPTH] memory _zeroes)
internal
view
returns (bytes32 _current)
{
uint256 _index = _tree.count;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
uint256 _ithBit = (_index >> i) & 0x01;
bytes32 _next = _tree.branch[i];
if (_ithBit == 1) {
_current = keccak256(abi.encodePacked(_next, _current));
} else {
_current = keccak256(abi.encodePacked(_current, _zeroes[i]));
}
}
}
/// @notice Calculates and returns`_tree`'s current root
function root(Tree storage _tree) internal view returns (bytes32) {
return rootWithCtx(_tree, zeroHashes());
}
/// @notice Returns array of TREE_DEPTH zero hashes
/// @return _zeroes Array of TREE_DEPTH zero hashes
function zeroHashes()
internal
pure
returns (bytes32[TREE_DEPTH] memory _zeroes)
{
_zeroes[0] = Z_0;
_zeroes[1] = Z_1;
_zeroes[2] = Z_2;
_zeroes[3] = Z_3;
_zeroes[4] = Z_4;
_zeroes[5] = Z_5;
_zeroes[6] = Z_6;
_zeroes[7] = Z_7;
_zeroes[8] = Z_8;
_zeroes[9] = Z_9;
_zeroes[10] = Z_10;
_zeroes[11] = Z_11;
_zeroes[12] = Z_12;
_zeroes[13] = Z_13;
_zeroes[14] = Z_14;
_zeroes[15] = Z_15;
_zeroes[16] = Z_16;
_zeroes[17] = Z_17;
_zeroes[18] = Z_18;
_zeroes[19] = Z_19;
_zeroes[20] = Z_20;
_zeroes[21] = Z_21;
_zeroes[22] = Z_22;
_zeroes[23] = Z_23;
_zeroes[24] = Z_24;
_zeroes[25] = Z_25;
_zeroes[26] = Z_26;
_zeroes[27] = Z_27;
_zeroes[28] = Z_28;
_zeroes[29] = Z_29;
_zeroes[30] = Z_30;
_zeroes[31] = Z_31;
}
/**
* @notice Calculates and returns the merkle root for the given leaf
* `_item`, a merkle branch, and the index of `_item` in the tree.
* @param _item Merkle leaf
* @param _branch Merkle proof
* @param _index Index of `_item` in tree
* @return _current Calculated merkle root
**/
function branchRoot(
bytes32 _item,
bytes32[TREE_DEPTH] memory _branch,
uint256 _index
) internal pure returns (bytes32 _current) {
_current = _item;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
uint256 _ithBit = (_index >> i) & 0x01;
bytes32 _next = _branch[i];
if (_ithBit == 1) {
_current = keccak256(abi.encodePacked(_next, _current));
} else {
_current = keccak256(abi.encodePacked(_current, _next));
}
}
}
// keccak256 zero hashes
bytes32 internal constant Z_0 =
hex"0000000000000000000000000000000000000000000000000000000000000000";
bytes32 internal constant Z_1 =
hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5";
bytes32 internal constant Z_2 =
hex"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30";
bytes32 internal constant Z_3 =
hex"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85";
bytes32 internal constant Z_4 =
hex"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344";
bytes32 internal constant Z_5 =
hex"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d";
bytes32 internal constant Z_6 =
hex"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968";
bytes32 internal constant Z_7 =
hex"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83";
bytes32 internal constant Z_8 =
hex"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af";
bytes32 internal constant Z_9 =
hex"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0";
bytes32 internal constant Z_10 =
hex"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5";
bytes32 internal constant Z_11 =
hex"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892";
bytes32 internal constant Z_12 =
hex"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c";
bytes32 internal constant Z_13 =
hex"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb";
bytes32 internal constant Z_14 =
hex"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc";
bytes32 internal constant Z_15 =
hex"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2";
bytes32 internal constant Z_16 =
hex"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f";
bytes32 internal constant Z_17 =
hex"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a";
bytes32 internal constant Z_18 =
hex"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0";
bytes32 internal constant Z_19 =
hex"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0";
bytes32 internal constant Z_20 =
hex"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2";
bytes32 internal constant Z_21 =
hex"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9";
bytes32 internal constant Z_22 =
hex"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377";
bytes32 internal constant Z_23 =
hex"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652";
bytes32 internal constant Z_24 =
hex"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef";
bytes32 internal constant Z_25 =
hex"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d";
bytes32 internal constant Z_26 =
hex"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0";
bytes32 internal constant Z_27 =
hex"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e";
bytes32 internal constant Z_28 =
hex"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e";
bytes32 internal constant Z_29 =
hex"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322";
bytes32 internal constant Z_30 =
hex"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735";
bytes32 internal constant Z_31 =
hex"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9";
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
import "@summa-tx/memview-sol/contracts/TypedMemView.sol";
import {
TypeCasts
} from "./TypeCasts.sol";
/**
* @title Message Library
* @author Celo Labs Inc.
* @notice Library for formatted messages used by Home and Replica.
**/
library Message {
using TypedMemView for bytes;
using TypedMemView for bytes29;
// Number of bytes in formatted message before `body` field
uint256 internal constant PREFIX_LENGTH = 76;
/**
* @notice Returns formatted (packed) message with provided fields
* @param _originDomain Domain of home chain
* @param _sender Address of sender as bytes32
* @param _nonce Destination-specific nonce
* @param _destinationDomain Domain of destination chain
* @param _recipient Address of recipient on destination chain as bytes32
* @param _messageBody Raw bytes of message body
* @return Formatted message
**/
function formatMessage(
uint32 _originDomain,
bytes32 _sender,
uint32 _nonce,
uint32 _destinationDomain,
bytes32 _recipient,
bytes memory _messageBody
) internal pure returns (bytes memory) {
return
abi.encodePacked(
_originDomain,
_sender,
_nonce,
_destinationDomain,
_recipient,
_messageBody
);
}
/**
* @notice Returns leaf of formatted message with provided fields.
* @param _origin Domain of home chain
* @param _sender Address of sender as bytes32
* @param _nonce Destination-specific nonce number
* @param _destination Domain of destination chain
* @param _recipient Address of recipient on destination chain as bytes32
* @param _body Raw bytes of message body
* @return Leaf (hash) of formatted message
**/
function messageHash(
uint32 _origin,
bytes32 _sender,
uint32 _nonce,
uint32 _destination,
bytes32 _recipient,
bytes memory _body
) internal pure returns (bytes32) {
return
keccak256(
formatMessage(
_origin,
_sender,
_nonce,
_destination,
_recipient,
_body
)
);
}
/// @notice Returns message's origin field
function origin(bytes29 _message) internal pure returns (uint32) {
return uint32(_message.indexUint(0, 4));
}
/// @notice Returns message's sender field
function sender(bytes29 _message) internal pure returns (bytes32) {
return _message.index(4, 32);
}
/// @notice Returns message's nonce field
function nonce(bytes29 _message) internal pure returns (uint32) {
return uint32(_message.indexUint(36, 4));
}
/// @notice Returns message's destination field
function destination(bytes29 _message) internal pure returns (uint32) {
return uint32(_message.indexUint(40, 4));
}
/// @notice Returns message's recipient field as bytes32
function recipient(bytes29 _message) internal pure returns (bytes32) {
return _message.index(44, 32);
}
/// @notice Returns message's recipient field as an address
function recipientAddress(bytes29 _message)
internal
pure
returns (address)
{
return TypeCasts.bytes32ToAddress(recipient(_message));
}
/// @notice Returns message's body field as bytes29 (refer to TypedMemView library for details on bytes29 type)
function body(bytes29 _message) internal pure returns (bytes29) {
return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0);
}
function leaf(bytes29 _message) internal view returns (bytes32) {
return messageHash(origin(_message), sender(_message), nonce(_message), destination(_message), recipient(_message), TypedMemView.clone(body(_message)));
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {MerkleLib} from "../libs/Merkle.sol";
/**
* @title MerkleTreeManager
* @author Celo Labs Inc.
* @notice Contains a Merkle tree instance and
* exposes view functions for the tree.
*/
contract MerkleTreeManager {
// ============ Libraries ============
using MerkleLib for MerkleLib.Tree;
MerkleLib.Tree public tree;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[49] private __GAP;
// ============ Public Functions ============
/**
* @notice Calculates and returns tree's current root
*/
function root() public view returns (bytes32) {
return tree.root();
}
/**
* @notice Returns the number of inserted leaves in the tree (current index)
*/
function count() public view returns (uint256) {
return tree.count;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {QueueLib} from "../libs/Queue.sol";
// ============ External Imports ============
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title QueueManager
* @author Celo Labs Inc.
* @notice Contains a queue instance and
* exposes view functions for the queue.
**/
contract QueueManager is Initializable {
// ============ Libraries ============
using QueueLib for QueueLib.Queue;
QueueLib.Queue internal queue;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[49] private __GAP;
// ============ Initializer ============
function __QueueManager_initialize() internal initializer {
queue.initialize();
}
// ============ Public Functions ============
/**
* @notice Returns number of elements in queue
*/
function queueLength() external view returns (uint256) {
return queue.length();
}
/**
* @notice Returns TRUE iff `_item` is in the queue
*/
function queueContains(bytes32 _item) external view returns (bool) {
return queue.contains(_item);
}
/**
* @notice Returns last item enqueued to the queue
*/
function queueEnd() external view returns (bytes32) {
return queue.lastItem();
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
interface IUpdaterManager {
function slashUpdater(address payable _reporter) external;
function updater() external view returns (address);
}
// 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;
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 Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
// 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 OR Apache-2.0
pragma solidity >=0.6.11;
import "@summa-tx/memview-sol/contracts/TypedMemView.sol";
library TypeCasts {
using TypedMemView for bytes;
using TypedMemView for bytes29;
function coerceBytes32(string memory _s)
internal
pure
returns (bytes32 _b)
{
_b = bytes(_s).ref(0).index(0, uint8(bytes(_s).length));
}
// treat it as a null-terminated string of max 32 bytes
function coerceString(bytes32 _buf)
internal
pure
returns (string memory _newStr)
{
uint8 _slen = 0;
while (_slen < 32 && _buf[_slen] != 0) {
_slen++;
}
// solhint-disable-next-line no-inline-assembly
assembly {
_newStr := mload(0x40)
mstore(0x40, add(_newStr, 0x40)) // may end up with extra
mstore(_newStr, _slen)
mstore(add(_newStr, 0x20), _buf)
}
}
// alignment preserving cast
function addressToBytes32(address _addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_addr)));
}
// alignment preserving cast
function bytes32ToAddress(bytes32 _buf) internal pure returns (address) {
return address(uint160(uint256(_buf)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.10;
/*
The MIT License (MIT)
Copyright (c) 2016 Smart Contract Solutions, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @title 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;
require(c / _a == _b, "Overflow during multiplication.");
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) {
require(_b <= _a, "Underflow during subtraction.");
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
require(c >= _a, "Overflow during addition.");
return c;
}
}
// 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 OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {Version0} from "./Version0.sol";
import {Common} from "./Common.sol";
import {MerkleLib} from "../libs/Merkle.sol";
import {Message} from "../libs/Message.sol";
import {IMessageRecipient} from "../interfaces/IMessageRecipient.sol";
// ============ External Imports ============
import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol";
/**
* @title Replica
* @author Celo Labs Inc.
* @notice Track root updates on Home,
* prove and dispatch messages to end recipients.
*/
contract Replica is Version0, Common {
// ============ Libraries ============
using MerkleLib for MerkleLib.Tree;
using TypedMemView for bytes;
using TypedMemView for bytes29;
using Message for bytes29;
// ============ Enums ============
// Status of Message:
// 0 - None - message has not been proven or processed
// 1 - Proven - message inclusion proof has been validated
// 2 - Processed - message has been dispatched to recipient
enum MessageStatus {
None,
Proven,
Processed
}
// ============ Immutables ============
// Minimum gas for message processing
uint256 public immutable PROCESS_GAS;
// Reserved gas (to ensure tx completes in case message processing runs out)
uint256 public immutable RESERVE_GAS;
// ============ Public Storage ============
// Domain of home chain
uint32 public remoteDomain;
// Number of seconds to wait before root becomes confirmable
uint256 public optimisticSeconds;
// re-entrancy guard
uint8 private entered;
// Mapping of roots to allowable confirmation times
mapping(bytes32 => uint256) public confirmAt;
// Mapping of message leaves to MessageStatus
mapping(bytes32 => MessageStatus) public messages;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[44] private __GAP;
// ============ Events ============
/**
* @notice Emitted when message is processed
* @param messageHash Hash of message that failed to process
* @param success TRUE if the call was executed successfully, FALSE if the call reverted
* @param returnData the return data from the external call
*/
event Process(
bytes32 indexed messageHash,
bool indexed success,
bytes indexed returnData
);
// ============ Constructor ============
// solhint-disable-next-line no-empty-blocks
constructor(
uint32 _localDomain,
uint256 _processGas,
uint256 _reserveGas
) Common(_localDomain) {
require(_processGas >= 850_000, "!process gas");
require(_reserveGas >= 15_000, "!reserve gas");
PROCESS_GAS = _processGas;
RESERVE_GAS = _reserveGas;
}
// ============ Initializer ============
function initialize(
uint32 _remoteDomain,
address _updater,
bytes32 _committedRoot,
uint256 _optimisticSeconds
) public initializer {
__Common_initialize(_updater);
entered = 1;
remoteDomain = _remoteDomain;
committedRoot = _committedRoot;
confirmAt[_committedRoot] = 1;
optimisticSeconds = _optimisticSeconds;
}
// ============ External Functions ============
/**
* @notice Called by external agent. Submits the signed update's new root,
* marks root's allowable confirmation time, and emits an `Update` event.
* @dev Reverts if update doesn't build off latest committedRoot
* or if signature is invalid.
* @param _oldRoot Old merkle root
* @param _newRoot New merkle root
* @param _signature Updater's signature on `_oldRoot` and `_newRoot`
*/
function update(
bytes32 _oldRoot,
bytes32 _newRoot,
bytes memory _signature
) external notFailed {
// ensure that update is building off the last submitted root
require(_oldRoot == committedRoot, "not current update");
// validate updater signature
require(
_isUpdaterSignature(_oldRoot, _newRoot, _signature),
"!updater sig"
);
// Hook for future use
_beforeUpdate();
// set the new root's confirmation timer
confirmAt[_newRoot] = block.timestamp + optimisticSeconds;
// update committedRoot
committedRoot = _newRoot;
emit Update(remoteDomain, _oldRoot, _newRoot, _signature);
}
/**
* @notice First attempts to prove the validity of provided formatted
* `message`. If the message is successfully proven, then tries to process
* message.
* @dev Reverts if `prove` call returns false
* @param _message Formatted message (refer to Common.sol Message library)
* @param _proof Merkle proof of inclusion for message's leaf
* @param _index Index of leaf in home's merkle tree
*/
function proveAndProcess(
bytes memory _message,
bytes32[32] calldata _proof,
uint256 _index
) external {
require(prove(keccak256(_message), _proof, _index), "!prove");
process(_message);
}
/**
* @notice Given formatted message, attempts to dispatch
* message payload to end recipient.
* @dev Recipient must implement a `handle` method (refer to IMessageRecipient.sol)
* Reverts if formatted message's destination domain is not the Replica's domain,
* if message has not been proven,
* or if not enough gas is provided for the dispatch transaction.
* @param _message Formatted message
* @return _success TRUE iff dispatch transaction succeeded
*/
function process(bytes memory _message) public returns (bool _success) {
bytes29 _m = _message.ref(0);
// ensure message was meant for this domain
require(_m.destination() == localDomain, "!destination");
// ensure message has been proven
bytes32 _messageHash = _m.keccak();
require(messages[_messageHash] == MessageStatus.Proven, "!proven");
// check re-entrancy guard
require(entered == 1, "!reentrant");
entered = 0;
// update message status as processed
messages[_messageHash] = MessageStatus.Processed;
// A call running out of gas TYPICALLY errors the whole tx. We want to
// a) ensure the call has a sufficient amount of gas to make a
// meaningful state change.
// b) ensure that if the subcall runs out of gas, that the tx as a whole
// does not revert (i.e. we still mark the message processed)
// To do this, we require that we have enough gas to process
// and still return. We then delegate only the minimum processing gas.
require(gasleft() >= PROCESS_GAS + RESERVE_GAS, "!gas");
// get the message recipient
address _recipient = _m.recipientAddress();
// set up for assembly call
uint256 _toCopy;
uint256 _maxCopy = 256;
uint256 _gas = PROCESS_GAS;
// allocate memory for returndata
bytes memory _returnData = new bytes(_maxCopy);
bytes memory _calldata = abi.encodeWithSignature(
"handle(uint32,bytes32,bytes)",
_m.origin(),
_m.sender(),
_m.body().clone()
);
// dispatch message to recipient
// by assembly calling "handle" function
// we call via assembly to avoid memcopying a very large returndata
// returned by a malicious contract
assembly {
_success := call(
_gas, // gas
_recipient, // recipient
0, // ether value
add(_calldata, 0x20), // inloc
mload(_calldata), // inlen
0, // outloc
0 // outlen
)
// limit our copy to 256 bytes
_toCopy := returndatasize()
if gt(_toCopy, _maxCopy) {
_toCopy := _maxCopy
}
// Store the length of the copied bytes
mstore(_returnData, _toCopy)
// copy the bytes from returndata[0:_toCopy]
returndatacopy(add(_returnData, 0x20), 0, _toCopy)
}
// emit process results
emit Process(_messageHash, _success, _returnData);
// reset re-entrancy guard
entered = 1;
}
// ============ Public Functions ============
/**
* @notice Check that the root has been submitted
* and that the optimistic timeout period has expired,
* meaning the root can be processed
* @param _root the Merkle root, submitted in an update, to check
* @return TRUE iff root has been submitted & timeout has expired
*/
function acceptableRoot(bytes32 _root) public view returns (bool) {
uint256 _time = confirmAt[_root];
if (_time == 0) {
return false;
}
return block.timestamp >= _time;
}
/**
* @notice Attempts to prove the validity of message given its leaf, the
* merkle proof of inclusion for the leaf, and the index of the leaf.
* @dev Reverts if message's MessageStatus != None (i.e. if message was
* already proven or processed)
* @dev For convenience, we allow proving against any previous root.
* This means that witnesses never need to be updated for the new root
* @param _leaf Leaf of message to prove
* @param _proof Merkle proof of inclusion for leaf
* @param _index Index of leaf in home's merkle tree
* @return Returns true if proof was valid and `prove` call succeeded
**/
function prove(
bytes32 _leaf,
bytes32[32] calldata _proof,
uint256 _index
) public returns (bool) {
// ensure that message has not been proven or processed
require(messages[_leaf] == MessageStatus.None, "!MessageStatus.None");
// calculate the expected root based on the proof
bytes32 _calculatedRoot = MerkleLib.branchRoot(_leaf, _proof, _index);
// if the root is valid, change status to Proven
if (acceptableRoot(_calculatedRoot)) {
messages[_leaf] = MessageStatus.Proven;
return true;
}
return false;
}
/**
* @notice Hash of Home domain concatenated with "OPTICS"
*/
function homeDomainHash() public view override returns (bytes32) {
return _homeDomainHash(remoteDomain);
}
// ============ Internal Functions ============
/**
* @notice Moves the contract into failed state
* @dev Called when a Double Update is submitted
*/
function _fail() internal override {
_setFailed();
}
/// @notice Hook for potential future use
// solhint-disable-next-line no-empty-blocks
function _beforeUpdate() internal {}
}
// 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 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;
}
}
|
Handle message setting the router address for a given domain _msg The message/
|
function _handleSetRouter(bytes29 _msg)
internal
typeAssert(_msg, GovernanceMessage.Types.SetRouter)
{
uint32 _domain = _msg.domain();
bytes32 _router = _msg.router();
_setRouter(_domain, _router);
}
| 9,926,142 |
./full_match/5/0xFF66BF2e58234FD609a7C2D783237999D1fAA785/sources/project_/contracts/ExchangeDeposit.sol
|
Internal function for getting the sendTo address for gathering ERC20/ETH. If the contract is dead, they will be forwarded to the adminAddress. return address payable for sending ERC20/ETH/ Use exDepositor to perform logic for finding send address If ExchangeDeposit is killed, use adminAddress, else use coldAddress
|
function getSendAddress() internal view returns (address payable) {
ExchangeDeposit exDepositor = getExchangeDepositor();
address payable coldAddr = exDepositor.coldAddress();
address payable toAddr =
coldAddr == address(0) ? exDepositor.adminAddress() : coldAddr;
return toAddr;
}
| 1,849,891 |
./full_match/137/0xDF092237F7D15B88B3C03f4836536E2B242018a8/sources/Contract_Deploy/Mainnet/boltr-audit-paladin/BoltrSwap.sol
|
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 {KRC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`./
|
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "KRC20: decreased allowance below zero")
);
return true;
}
| 4,709,670 |
./full_match/56/0x5DD9707a433ffC4bf37BFD1AA81677f50Af13dc4/sources/contracts/BSCGlyphs.sol
|
// Bids Refund the failing bid
|
function enterBidForGlyph(uint glyphIndex) payable {
require(glyphIndex<=TOKEN_LIMIT, "Invalid glyph id/index");
require(glyphIndex<=numTokens, "Glyph has not been minted yet");
require(idToOwner[glyphIndex] != msg.sender, "Cannot bid on your own glyph");
require(msg.value>0, "Send BNB along with bid");
Bid existing = glyphBids[glyphIndex];
require(msg.value > existing.value, "Someone already bid higher for this glyph");
if (existing.value > 0) {
pendingWithdrawals[existing.bidder] += existing.value;
}
glyphBids[glyphIndex] = Bid(true, glyphIndex, msg.sender, msg.value);
GlyphBidEntered(glyphIndex, msg.value, msg.sender);
}
| 3,236,691 |
./full_match/4/0xDD3B44C4e8D167D5577AaD8BaE0c1c83f0D97428/sources/CurrencyConverter.sol
|
find data feed address for your mainnet/testnet at https:docs.chain.link/docs/ethereum-addresses/
|
function getVersion() public view returns (uint256) {
AggregatorV3Interface priceFeed = AggregatorV3Interface(
0x8A753747A1Fa494EC906cE90E9f37563A8AF630e
);
return priceFeed.version();
}
| 653,483 |
pragma solidity 0.4.26;
/**
* @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;
}
}
/**
* @dev Ether Escrow legible as Bill of Sale with arbitration procedure.
*/
contract BillOfSale {
using SafeMath for uint256;
address public buyer;
address public seller;
address public arbiter;
string public descr;
uint256 public price;
uint256 private arbiterFee;
uint256 private buyerAward;
uint256 private sellerAward;
enum State { Created, Confirmed, Disputed, Resolved, Completed }
State public state;
event Confirmed(address indexed buyer, address indexed this);
event Disputed();
event Resolved(address indexed this, address indexed buyer, address indexed seller);
event Completed(address indexed this, address indexed seller);
/**
* @dev Sets the transaction values for `descr`, `price`, `buyer`, `seller`, 'arbiter', 'arbiterFee'. All six of
* these values are immutable: they can only be set once during construction and reflect essential deal terms.
*/
constructor(
string memory _descr,
uint256 _price,
address _buyer,
address _seller,
address _arbiter,
uint256 _arbiterFee)
public {
descr = _descr;
price = _price;
seller = _seller;
buyer = _buyer;
arbiter = _arbiter;
arbiterFee = _arbiterFee;
}
/**
* @dev Throws if called by any account other than buyer.
*/
modifier onlyBuyer() {
require(msg.sender == buyer);
_;
}
/**
* @dev Throws if called by any account other than buyer or seller.
*/
modifier onlyBuyerOrSeller() {
require(
msg.sender == buyer ||
msg.sender == seller);
_;
}
/**
* @dev Throws if called by any account other than arbiter.
*/
modifier onlyArbiter() {
require(msg.sender == arbiter);
_;
}
/**
* @dev Throws if contract called in State other than one associated for function.
*/
modifier inState(State _state) {
require(state == _state);
_;
}
/**
* @dev Buyer confirms transaction with Ether 'price' as message value;
* Ether is then locked for transfer to seller after buyer confirms receipt
* or ADR if dispute initiated by buyer or seller.
*/
function confirmPurchase() public payable onlyBuyer inState(State.Created) {
require(price == msg.value);
state = State.Confirmed;
emit Confirmed(buyer, address(this));
}
/**
* @dev Buyer confirms receipt from seller;
* Ether 'price' is transferred to seller.
*/
function confirmReceipt() public onlyBuyer inState(State.Confirmed) {
state = State.Completed;
seller.transfer(address(this).balance);
emit Completed(address(this), seller);
}
/**
* @dev Buyer or seller can initiate dispute related to locked Ether 'price' after buyer confirms purchase,
* placing 'price' transfer and split of value into arbiter control.
* For example, buyer might refuse or unduly delay to confirm receipt after seller transaction, or, on other hand,
* despite buyer's disatisfaction with seller transaction, seller might demand buyer confirm receipt and release 'price'.
*/
function initiateDispute() public onlyBuyerOrSeller inState(State.Confirmed) {
state = State.Disputed;
emit Disputed();
}
/**
* @dev Arbiter can resolve dispute and claim reward by entering in split of 'price' value
* minus their 'arbiter fee' set at construction.
*/
function resolveDispute(uint256 _buyerAward, uint256 _sellerAward) public onlyArbiter inState(State.Disputed) {
state = State.Resolved;
buyerAward = _buyerAward;
sellerAward = _sellerAward;
buyer.transfer(buyerAward);
seller.transfer(sellerAward);
arbiter.transfer(arbiterFee);
emit Resolved(address(this), buyer, seller);
}
}
contract BillOfSaleFactory {
// index of created contracts
mapping (address => bool) public validContracts;
address[] public contracts;
// useful to know the row count in contracts index
function getContractCount()
public
view
returns(uint contractCount)
{
return contracts.length;
}
// get all contracts
function getDeployedContracts() public view returns (address[] memory)
{
return contracts;
}
// deploy a new contract
function newBillOfSale(
string memory _descr,
uint256 _price,
address _buyer,
address _seller,
address _arbiter,
uint256 _arbiterFee)
public
returns(address)
{
BillOfSale c = new BillOfSale(
_descr,
_price,
_buyer,
_seller,
_arbiter,
_arbiterFee);
validContracts[c] = true;
contracts.push(c);
return c;
}
}
|
Buyer confirms receipt from seller; Ether 'price' is transferred to seller./
|
function confirmReceipt() public onlyBuyer inState(State.Confirmed) {
state = State.Completed;
seller.transfer(address(this).balance);
emit Completed(address(this), seller);
}
| 5,342,828 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import {Math} from '../utils/math/Math.sol';
import {Pausable} from './Pausable.sol';
import {IARTH} from '../Arth/IARTH.sol';
import {IERC20} from '../ERC20/IERC20.sol';
import {SafeMath} from '../utils/math/SafeMath.sol';
import {SafeERC20} from '../ERC20/SafeERC20.sol';
import {StringHelpers} from '../utils/StringHelpers.sol';
import {IARTHController} from '../Arth/IARTHController.sol';
import {ReentrancyGuard} from '../utils/ReentrancyGuard.sol';
import {TransferHelper} from '../Uniswap/TransferHelper.sol';
import {IStakingRewardsDual} from './IStakingRewardsDual.sol';
/**
* @title StakingRewardsDualV2
* @author MahaDAO.
*
* Original code written by:
* - Travis Moore, Jason Huan, Same Kazemian, Sam Sun.
*
* Modified originally from Synthetixio
* https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol
*/
contract StakingRewardsDualV2 is
IStakingRewardsDual,
ReentrancyGuard,
Pausable
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* State variables.
*/
struct LockedStake {
bytes32 kekId;
uint256 startTimestamp;
uint256 amount;
uint256 endingTimestamp;
uint256 multiplier; // 6 decimals of precision. 1x = 1000000
}
IERC20 public stakingToken;
IERC20 public rewardsToken0;
IERC20 public rewardsToken1;
IARTH private _ARTH;
IARTHController private _arthController;
uint256 public periodFinish;
// Max reward per second
uint256 public rewardRate0;
uint256 public rewardRate1;
// uint256 public rewardsDuration = 86400 hours;
uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days)
// This staking pool's percentage of the total ARTHX being distributed by all pools, 6 decimals of precision
uint256 public poolWeight0;
// This staking pool's percentage of the total TOKEN 2 being distributed by all pools, 6 decimals of precision
uint256 public poolWeight1;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored0 = 0;
uint256 public rewardPerTokenStored1 = 0;
uint256 public lockedStakeMinTime = 604800; // 7 * 86400 (7 days)
uint256 public lockedStakeMaxMultiplier = 2000000; // 6 decimals of precision. 1x = 1000000
uint256 public crBoostMaxMultiplier = 1000000; // 6 decimals of precision. 1x = 1000000
uint256 public lockedStakeTimeForMaxMultiplier = 3 * 365 * 86400; // 3 years
bool public migrationsOn = false; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals
bool public stakesUnlocked = false; // Release locked stakes in case of system migration or emergency
bool public token1RewardsOn = false;
bool public withdrawalsPaused = false; // For emergencies
bool public rewardsCollectionPaused = false; // For emergencies
address public ownerAddress;
address public timelockAddress; // Governance timelock address
mapping(address => bool) public greylist;
// List of valid migrators (set by governance)
mapping(address => bool) public validMigrators;
mapping(address => uint256) public rewards0;
mapping(address => uint256) public rewards1;
mapping(address => uint256) public userRewardPerTokenPaid0;
mapping(address => uint256) public userRewardPerTokenPaid1;
// Stakers set which migrator(s) they want to use
mapping(address => mapping(address => bool)) public stakerAllowedMigrators;
address[] public validMigratorsArray;
uint256 private constant _PRICE_PRECISION = 1e6;
uint256 private constant _MULTIPLIER_BASE = 1e6;
string private _lockedStakeMinTimeStr = '604800'; // 7 days on genesis
uint256 private _stakingTokenSupply = 0;
uint256 private _stakingTokenBoostedSupply = 0;
mapping(address => uint256) private _lockedBalances;
mapping(address => uint256) private _boostedBalances;
mapping(address => uint256) private _unlockedBalances;
mapping(address => LockedStake[]) private _lockedStakes;
/**
* Events.
*/
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount, address sourceAddress);
event StakeLocked(
address indexed user,
uint256 amount,
uint256 secs,
address sourceAddress
);
event Withdrawn(
address indexed user,
uint256 amount,
address destinationAddress
);
event WithdrawnLocked(
address indexed user,
uint256 amount,
bytes32 kekId,
address destinationAddress
);
event RewardPaid(
address indexed user,
uint256 reward,
address tokenAddress,
address destinationAddress
);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
event RewardsPeriodRenewed(address token);
event DefaultInitialization();
event LockedStakeMaxMultiplierUpdated(uint256 multiplier);
event LockedStakeTimeForMaxMultiplier(uint256 secs);
event LockedStakeMinTime(uint256 secs);
event MaxCRBoostMultiplier(uint256 multiplier);
/**
* Modifiers.
*/
modifier onlyByOwnerOrGovernance() {
require(
msg.sender == ownerAddress || msg.sender == timelockAddress,
'You are not the owner or the governance timelock'
);
_;
}
modifier onlyByOwnerOrGovernanceOrMigrator() {
require(
msg.sender == ownerAddress ||
msg.sender == timelockAddress ||
validMigrators[msg.sender] == true,
'You are not the owner, governance timelock, or a migrator'
);
_;
}
modifier isMigrating() {
require(migrationsOn == true, 'Contract is not in migration');
_;
}
modifier notWithdrawalsPaused() {
require(withdrawalsPaused == false, 'Withdrawals are paused');
_;
}
modifier notRewardsCollectionPaused() {
require(
rewardsCollectionPaused == false,
'Rewards collection is paused'
);
_;
}
modifier updateReward(address account) {
// Need to retro-adjust some things if the period hasn't been renewed, then start a new one
sync();
if (account != address(0)) {
(uint256 earned0, uint256 earned1) = earned(account);
rewards0[account] = earned0;
rewards1[account] = earned1;
userRewardPerTokenPaid0[account] = rewardPerTokenStored0;
userRewardPerTokenPaid1[account] = rewardPerTokenStored1;
}
_;
}
/**
* Constructor.
*/
constructor(
address _owner,
address _rewardsToken0,
address _rewardsToken1,
address _stakingToken,
address _arthAddress,
address _timelockAddress,
uint256 _poolWeight0,
uint256 _poolWeight1
) {
ownerAddress = _owner;
_ARTH = IARTH(_arthAddress);
rewardsToken0 = IERC20(_rewardsToken0);
rewardsToken1 = IERC20(_rewardsToken1);
stakingToken = IERC20(_stakingToken);
poolWeight0 = _poolWeight0;
poolWeight1 = _poolWeight1;
lastUpdateTime = block.timestamp;
timelockAddress = _timelockAddress;
// 1000 ARTHX a day
rewardRate0 = (uint256(365000e18)).div(365 * 86400);
rewardRate0 = rewardRate0.mul(poolWeight0).div(1e6);
// ??? CRVDAO a day eventually
rewardRate1 = 0;
migrationsOn = false;
stakesUnlocked = false;
rewardRate1 = rewardRate1.mul(poolWeight1).div(1e6);
}
/**
* External.
*/
// Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration)
function stake(uint256 amount) external override {
_stake(msg.sender, msg.sender, amount);
}
// Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration)
function stakeLocked(uint256 amount, uint256 secs) external override {
_stakeLocked(msg.sender, msg.sender, amount, secs);
}
// Two different withdrawer functions are needed because of delegateCall and msg.sender issues (important for migration)
function withdraw(uint256 amount) external override {
_withdraw(msg.sender, msg.sender, amount);
}
// Two different withdrawLocked functions are needed because of delegateCall and msg.sender issues (important for migration)
function withdrawLocked(bytes32 kekId) external override {
_withdrawLocked(msg.sender, msg.sender, kekId);
}
// Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders
function recoverERC20(address tokenAddress, uint256 tokenAmount)
external
onlyByOwnerOrGovernance
{
// Admin cannot withdraw the staking token from the contract unless currently migrating
if (!migrationsOn) {
require(
tokenAddress != address(stakingToken),
'Cannot withdraw staking tokens unless migration is on'
); // Only Governance / Timelock can trigger a migration
}
// Only the owner address can ever receive the recovery withdrawal
IERC20(tokenAddress).transfer(ownerAddress, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration)
external
onlyByOwnerOrGovernance
{
require(
periodFinish == 0 || block.timestamp > periodFinish,
'Previous rewards period must be complete before changing the duration for the new period'
);
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
function setMultipliers(
uint256 _lockedStakeMaxMultiplier,
uint256 _crBoostMaxMultiplier
) external onlyByOwnerOrGovernance {
require(
_lockedStakeMaxMultiplier >= 1,
'Multiplier must be greater than or equal to 1'
);
require(
_crBoostMaxMultiplier >= 1,
'Max CR Boost must be greater than or equal to 1'
);
lockedStakeMaxMultiplier = _lockedStakeMaxMultiplier;
crBoostMaxMultiplier = _crBoostMaxMultiplier;
emit MaxCRBoostMultiplier(crBoostMaxMultiplier);
emit LockedStakeMaxMultiplierUpdated(lockedStakeMaxMultiplier);
}
function setLockedStakeTimeForMinAndMaxMultiplier(
uint256 _lockedStakeTimeForMaxMultiplier,
uint256 _lockedStakeMinTime
) external onlyByOwnerOrGovernance {
require(
_lockedStakeTimeForMaxMultiplier >= 1,
'Multiplier Max Time must be greater than or equal to 1'
);
require(
_lockedStakeMinTime >= 1,
'Multiplier Min Time must be greater than or equal to 1'
);
lockedStakeTimeForMaxMultiplier = _lockedStakeTimeForMaxMultiplier;
lockedStakeMinTime = _lockedStakeMinTime;
_lockedStakeMinTimeStr = StringHelpers.uint2str(_lockedStakeMinTime);
emit LockedStakeTimeForMaxMultiplier(lockedStakeTimeForMaxMultiplier);
emit LockedStakeMinTime(_lockedStakeMinTime);
}
function initializeDefault() external onlyByOwnerOrGovernance {
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit DefaultInitialization();
}
function greylistAddress(address _address)
external
onlyByOwnerOrGovernance
{
greylist[_address] = !(greylist[_address]);
}
function unlockStakes() external onlyByOwnerOrGovernance {
stakesUnlocked = !stakesUnlocked;
}
function toggleMigrations() external onlyByOwnerOrGovernance {
migrationsOn = !migrationsOn;
}
function toggleWithdrawals() external onlyByOwnerOrGovernance {
withdrawalsPaused = !withdrawalsPaused;
}
function toggleRewardsCollection() external onlyByOwnerOrGovernance {
rewardsCollectionPaused = !rewardsCollectionPaused;
}
function setRewardRates(
uint256 _newRate,
uint256 _newRate1,
bool sync_too
) external onlyByOwnerOrGovernance {
rewardRate0 = _newRate;
rewardRate1 = _newRate1;
if (sync_too) {
sync();
}
}
// Migrator can stake for someone else (they won't be able to withdraw it back though, only stakerAddress can)
function migratorStakeFor(address stakerAddress, uint256 amount)
external
isMigrating
{
require(
migratorApprovedForStaker(stakerAddress, msg.sender),
'msg.sender is either an invalid migrator or the staker has not approved them'
);
_stake(stakerAddress, msg.sender, amount);
}
// Migrator can stake for someone else (they won't be able to withdraw it back though, only stakerAddress can).
function migratorStakeLockedFor(
address stakerAddress,
uint256 amount,
uint256 secs
) external isMigrating {
require(
migratorApprovedForStaker(stakerAddress, msg.sender),
'msg.sender is either an invalid migrator or the staker has not approved them'
);
_stakeLocked(stakerAddress, msg.sender, amount, secs);
}
// Used for migrations
function migratorWithdrawUnlocked(address stakerAddress)
external
isMigrating
{
require(
migratorApprovedForStaker(stakerAddress, msg.sender),
'msg.sender is either an invalid migrator or the staker has not approved them'
);
_withdraw(stakerAddress, msg.sender, _unlockedBalances[stakerAddress]);
}
// Used for migrations
function migratorWithdrawLocked(address stakerAddress, bytes32 kekId)
external
isMigrating
{
require(
migratorApprovedForStaker(stakerAddress, msg.sender),
'msg.sender is either an invalid migrator or the staker has not approved them'
);
_withdrawLocked(stakerAddress, msg.sender, kekId);
}
function toggleToken1Rewards() external onlyByOwnerOrGovernance {
if (token1RewardsOn) {
rewardRate1 = 0;
}
token1RewardsOn = !token1RewardsOn;
}
function setOwner(address _ownerAddress) external onlyByOwnerOrGovernance {
ownerAddress = _ownerAddress;
}
function setTimelock(address _newTimelock)
external
onlyByOwnerOrGovernance
{
timelockAddress = _newTimelock;
}
function renewIfApplicable() external {
if (block.timestamp > periodFinish) {
_retroCatchUp();
}
}
function totalSupply() external view override returns (uint256) {
return _stakingTokenSupply;
}
function totalBoostedSupply() external view returns (uint256) {
return _stakingTokenBoostedSupply;
}
function getRewardForDuration()
external
view
override
returns (uint256, uint256)
{
return (
rewardRate0.mul(rewardsDuration).mul(crBoostMultiplier()).div(
_PRICE_PRECISION
),
rewardRate1.mul(rewardsDuration)
);
}
/**
* Public.
*/
function stakingMultiplier(uint256 secs) public view returns (uint256) {
uint256 multiplier =
uint256(_MULTIPLIER_BASE).add(
secs.mul(lockedStakeMaxMultiplier.sub(_MULTIPLIER_BASE)).div(
lockedStakeTimeForMaxMultiplier
)
);
if (multiplier > lockedStakeMaxMultiplier)
multiplier = lockedStakeMaxMultiplier;
return multiplier;
}
function crBoostMultiplier() public view returns (uint256) {
uint256 multiplier =
uint256(_MULTIPLIER_BASE).add(
(
uint256(_MULTIPLIER_BASE).sub(
_arthController.getGlobalCollateralRatio()
)
)
.mul(crBoostMaxMultiplier.sub(_MULTIPLIER_BASE))
.div(_MULTIPLIER_BASE)
);
return multiplier;
}
// Total unlocked and locked liquidity tokens
function balanceOf(address account)
external
view
override
returns (uint256)
{
return (_unlockedBalances[account]).add(_lockedBalances[account]);
}
// Total unlocked liquidity tokens
function unlockedBalanceOf(address account)
external
view
returns (uint256)
{
return _unlockedBalances[account];
}
// Total locked liquidity tokens
function lockedBalanceOf(address account) public view returns (uint256) {
return _lockedBalances[account];
}
// Total 'balance' used for calculating the percent of the pool the account owns
// Takes into account the locked stake time multiplier
function boostedBalanceOf(address account) external view returns (uint256) {
return _boostedBalances[account];
}
function _lockedStakesOf(address account)
external
view
returns (LockedStake[] memory)
{
return _lockedStakes[account];
}
function stakingDecimals() external view returns (uint256) {
return stakingToken.decimals();
}
function rewardsFor(address account)
external
view
returns (uint256, uint256)
{
// You may have use earned() instead, because of the order in which the contract executes
return (rewards0[account], rewards1[account]);
}
function lastTimeRewardApplicable() public view override returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view override returns (uint256, uint256) {
if (_stakingTokenSupply == 0) {
return (rewardPerTokenStored0, rewardPerTokenStored1);
} else {
return (
// Boosted emission
rewardPerTokenStored0.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate0)
.mul(crBoostMultiplier())
.mul(1e18)
.div(_PRICE_PRECISION)
.div(_stakingTokenBoostedSupply)
),
// Flat emission
// Locked stakes will still get more weight with token1 rewards, but the CR boost will be canceled out for everyone
rewardPerTokenStored1.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate1)
.mul(1e18)
.div(_stakingTokenBoostedSupply)
)
);
}
}
function earned(address account)
public
view
override
returns (uint256, uint256)
{
(uint256 reward0, uint256 reward1) = rewardPerToken();
return (
_boostedBalances[account]
.mul(reward0.sub(userRewardPerTokenPaid0[account]))
.div(1e18)
.add(rewards0[account]),
_boostedBalances[account]
.mul(reward1.sub(userRewardPerTokenPaid1[account]))
.div(1e18)
.add(rewards1[account])
);
}
function migratorApprovedForStaker(
address stakerAddress,
address migratorAddress
) public view returns (bool) {
// Migrator is not a valid one
if (validMigrators[migratorAddress] == false) return false;
// Staker has to have approved this particular migrator
if (stakerAllowedMigrators[stakerAddress][migratorAddress] == true)
return true;
// Otherwise, return false
return false;
}
// Staker can allow a migrator
function stakerAllowMigrator(address migratorAddress) public {
require(
stakerAllowedMigrators[msg.sender][migratorAddress] == false,
'Address already exists'
);
require(validMigrators[migratorAddress], 'Invalid migrator address');
stakerAllowedMigrators[msg.sender][migratorAddress] = true;
}
// Staker can disallow a previously-allowed migrator
function stakerDisallowMigrator(address migratorAddress) public {
require(
stakerAllowedMigrators[msg.sender][migratorAddress] == true,
"Address doesn't exist already"
);
// Redundant
// require(validMigrators[migratorAddress], "Invalid migrator address");
// Delete from the mapping
delete stakerAllowedMigrators[msg.sender][migratorAddress];
}
// Two different getReward functions are needed because of delegateCall and msg.sender issues (important for migration)
function getReward() public override {
_getReward(msg.sender, msg.sender);
}
function sync() public {
if (block.timestamp > periodFinish) {
_retroCatchUp();
} else {
(uint256 reward0, uint256 reward1) = rewardPerToken();
rewardPerTokenStored0 = reward0;
rewardPerTokenStored1 = reward1;
lastUpdateTime = lastTimeRewardApplicable();
}
}
// Adds supported migrator address
function addMigrator(address migratorAddress)
public
onlyByOwnerOrGovernance
{
require(
validMigrators[migratorAddress] == false,
'address already exists'
);
validMigrators[migratorAddress] = true;
validMigratorsArray.push(migratorAddress);
}
// Remove a migrator address
function removeMigrator(address migratorAddress)
public
onlyByOwnerOrGovernance
{
require(
validMigrators[migratorAddress] == true,
"address doesn't exist already"
);
// Delete from the mapping
delete validMigrators[migratorAddress];
// 'Delete' from the array by setting the address to 0x0
for (uint256 i = 0; i < validMigratorsArray.length; i++) {
if (validMigratorsArray[i] == migratorAddress) {
validMigratorsArray[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
}
/**
* Internal.
*/
// If this were not internal, and sourceAddress had an infinite approve, this could be exploitable
// (pull funds from sourceAddress and stake for an arbitrary stakerAddress)
function _stake(
address stakerAddress,
address sourceAddress,
uint256 amount
) internal nonReentrant updateReward(stakerAddress) {
require(
(paused == false && migrationsOn == false) ||
validMigrators[msg.sender] == true,
'Staking is paused, or migration is happening'
);
require(amount > 0, 'Cannot stake 0');
require(
greylist[stakerAddress] == false,
'address has been greylisted'
);
// Pull the tokens from the sourceAddress
TransferHelper.safeTransferFrom(
address(stakingToken),
sourceAddress,
address(this),
amount
);
// Staking token supply and boosted supply
_stakingTokenSupply = _stakingTokenSupply.add(amount);
_stakingTokenBoostedSupply = _stakingTokenBoostedSupply.add(amount);
// Staking token balance and boosted balance
_unlockedBalances[stakerAddress] = _unlockedBalances[stakerAddress].add(
amount
);
_boostedBalances[stakerAddress] = _boostedBalances[stakerAddress].add(
amount
);
emit Staked(stakerAddress, amount, sourceAddress);
}
// If this were not internal, and sourceAddress had an infinite approve, this could be exploitable
// (pull funds from sourceAddress and stake for an arbitrary stakerAddress)
function _stakeLocked(
address stakerAddress,
address sourceAddress,
uint256 amount,
uint256 secs
) internal nonReentrant updateReward(stakerAddress) {
require(
(paused == false && migrationsOn == false) ||
validMigrators[msg.sender] == true,
'Staking is paused, or migration is happening'
);
require(amount > 0, 'Cannot stake 0');
require(secs > 0, 'Cannot wait for a negative number');
require(
greylist[stakerAddress] == false,
'address has been greylisted'
);
require(
secs >= lockedStakeMinTime,
StringHelpers.strConcat(
'Minimum stake time not met (',
_lockedStakeMinTimeStr,
')'
)
);
require(
secs <= lockedStakeTimeForMaxMultiplier,
'You are trying to stake for too long'
);
uint256 multiplier = stakingMultiplier(secs);
uint256 boostedAmount = amount.mul(multiplier).div(_PRICE_PRECISION);
_lockedStakes[stakerAddress].push(
LockedStake(
keccak256(
abi.encodePacked(stakerAddress, block.timestamp, amount)
),
block.timestamp,
amount,
block.timestamp.add(secs),
multiplier
)
);
// Pull the tokens from the sourceAddress
TransferHelper.safeTransferFrom(
address(stakingToken),
sourceAddress,
address(this),
amount
);
// Staking token supply and boosted supply
_stakingTokenSupply = _stakingTokenSupply.add(amount);
_stakingTokenBoostedSupply = _stakingTokenBoostedSupply.add(
boostedAmount
);
// Staking token balance and boosted balance
_lockedBalances[stakerAddress] = _lockedBalances[stakerAddress].add(
amount
);
_boostedBalances[stakerAddress] = _boostedBalances[stakerAddress].add(
boostedAmount
);
emit StakeLocked(stakerAddress, amount, secs, sourceAddress);
}
// No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper
// functions like withdraw(), migratorWithdrawUnlocked() and migratorWithdrawLocked()
function _withdraw(
address stakerAddress,
address destinationAddress,
uint256 amount
) internal nonReentrant notWithdrawalsPaused updateReward(stakerAddress) {
require(amount > 0, 'Cannot withdraw 0');
// Staking token balance and boosted balance
_unlockedBalances[stakerAddress] = _unlockedBalances[stakerAddress].sub(
amount
);
_boostedBalances[stakerAddress] = _boostedBalances[stakerAddress].sub(
amount
);
// Staking token supply and boosted supply
_stakingTokenSupply = _stakingTokenSupply.sub(amount);
_stakingTokenBoostedSupply = _stakingTokenBoostedSupply.sub(amount);
// Give the tokens to the destinationAddress
stakingToken.safeTransfer(destinationAddress, amount);
emit Withdrawn(stakerAddress, amount, destinationAddress);
}
// No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper
// functions like withdraw(), migratorWithdrawUnlocked() and migratorWithdrawLocked()
function _withdrawLocked(
address stakerAddress,
address destinationAddress,
bytes32 kekId
) internal nonReentrant notWithdrawalsPaused updateReward(stakerAddress) {
LockedStake memory thisStake;
thisStake.amount = 0;
uint256 theIndex;
for (uint256 i = 0; i < _lockedStakes[stakerAddress].length; i++) {
if (kekId == _lockedStakes[stakerAddress][i].kekId) {
thisStake = _lockedStakes[stakerAddress][i];
theIndex = i;
break;
}
}
require(thisStake.kekId == kekId, 'Stake not found');
require(
block.timestamp >= thisStake.endingTimestamp ||
stakesUnlocked == true ||
validMigrators[msg.sender] == true,
'Stake is still locked!'
);
uint256 theAmount = thisStake.amount;
uint256 boostedAmount =
theAmount.mul(thisStake.multiplier).div(_PRICE_PRECISION);
if (theAmount > 0) {
// Staking token balance and boosted balance
_lockedBalances[stakerAddress] = _lockedBalances[stakerAddress].sub(
theAmount
);
_boostedBalances[stakerAddress] = _boostedBalances[stakerAddress]
.sub(boostedAmount);
// Staking token supply and boosted supply
_stakingTokenSupply = _stakingTokenSupply.sub(theAmount);
_stakingTokenBoostedSupply = _stakingTokenBoostedSupply.sub(
boostedAmount
);
// Remove the stake from the array
delete _lockedStakes[stakerAddress][theIndex];
// Give the tokens to the destinationAddress
stakingToken.safeTransfer(destinationAddress, theAmount);
emit WithdrawnLocked(
stakerAddress,
theAmount,
kekId,
destinationAddress
);
}
}
// No withdrawer == msg.sender check needed since this is only internally callable
// This distinction is important for the migrator
function _getReward(address rewardee, address destinationAddress)
internal
nonReentrant
notRewardsCollectionPaused
updateReward(rewardee)
{
uint256 reward0 = rewards0[rewardee];
uint256 reward1 = rewards1[rewardee];
if (reward0 > 0) {
rewards0[rewardee] = 0;
rewardsToken0.transfer(destinationAddress, reward0);
emit RewardPaid(
rewardee,
reward0,
address(rewardsToken0),
destinationAddress
);
}
// if (token1RewardsOn){
if (reward1 > 0) {
rewards1[rewardee] = 0;
rewardsToken1.transfer(destinationAddress, reward1);
emit RewardPaid(
rewardee,
reward1,
address(rewardsToken1),
destinationAddress
);
}
// }
}
// If the period expired, renew it
function _retroCatchUp() internal {
// Failsafe check
require(block.timestamp > periodFinish, 'Period has not expired yet!');
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 numPeriodsElapsed =
uint256(block.timestamp.sub(periodFinish)) / rewardsDuration; // Floor division to the nearest period
uint256 balance0 = rewardsToken0.balanceOf(address(this));
uint256 balance1 = rewardsToken1.balanceOf(address(this));
require(
rewardRate0
.mul(rewardsDuration)
.mul(crBoostMultiplier())
.mul(numPeriodsElapsed + 1)
.div(_PRICE_PRECISION) <= balance0,
'Not enough ARTHX available for rewards!'
);
if (token1RewardsOn) {
require(
rewardRate1.mul(rewardsDuration).mul(numPeriodsElapsed + 1) <=
balance1,
'Not enough token1 available for rewards!'
);
}
// uint256 old_lastUpdateTime = lastUpdateTime;
// uint256 new_lastUpdateTime = block.timestamp;
// lastUpdateTime = periodFinish;
periodFinish = periodFinish.add(
(numPeriodsElapsed.add(1)).mul(rewardsDuration)
);
(uint256 reward0, uint256 reward1) = rewardPerToken();
rewardPerTokenStored0 = reward0;
rewardPerTokenStored1 = reward1;
lastUpdateTime = lastTimeRewardApplicable();
emit RewardsPeriodRenewed(address(stakingToken));
}
}
|
If this were not internal, and sourceAddress had an infinite approve, this could be exploitable (pull funds from sourceAddress and stake for an arbitrary stakerAddress) Pull the tokens from the sourceAddress Staking token supply and boosted supply Staking token balance and boosted balance
|
function _stakeLocked(
address stakerAddress,
address sourceAddress,
uint256 amount,
uint256 secs
) internal nonReentrant updateReward(stakerAddress) {
require(
(paused == false && migrationsOn == false) ||
validMigrators[msg.sender] == true,
'Staking is paused, or migration is happening'
);
require(amount > 0, 'Cannot stake 0');
require(secs > 0, 'Cannot wait for a negative number');
require(
greylist[stakerAddress] == false,
'address has been greylisted'
);
require(
secs >= lockedStakeMinTime,
StringHelpers.strConcat(
'Minimum stake time not met (',
_lockedStakeMinTimeStr,
')'
)
);
require(
secs <= lockedStakeTimeForMaxMultiplier,
'You are trying to stake for too long'
);
uint256 multiplier = stakingMultiplier(secs);
uint256 boostedAmount = amount.mul(multiplier).div(_PRICE_PRECISION);
_lockedStakes[stakerAddress].push(
LockedStake(
keccak256(
abi.encodePacked(stakerAddress, block.timestamp, amount)
),
block.timestamp,
amount,
block.timestamp.add(secs),
multiplier
)
);
TransferHelper.safeTransferFrom(
address(stakingToken),
sourceAddress,
address(this),
amount
);
_stakingTokenSupply = _stakingTokenSupply.add(amount);
_stakingTokenBoostedSupply = _stakingTokenBoostedSupply.add(
boostedAmount
);
_lockedBalances[stakerAddress] = _lockedBalances[stakerAddress].add(
amount
);
_boostedBalances[stakerAddress] = _boostedBalances[stakerAddress].add(
boostedAmount
);
emit StakeLocked(stakerAddress, amount, secs, sourceAddress);
}
| 2,546,599 |
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @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);
}
/**
* @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;
}
}
/**
* @dev Implementation of the `IERC20` interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using `_mint`.
* For a generic mechanism see `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* 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 IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
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 `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a `Transfer` event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @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 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
interface NativeTokenMigrationInterface {
// ***
// Public functions
// ***
function transferToNativeTargetAddress(uint256 amount, string calldata FETAddress) external;
function transferToNativeFromKey(uint256 amount) external;
function refund(uint256 id) external;
function requestRefund(uint256 id) external;
// ***
// Restricted functions: Owner only
// ***
// Add or remove a delegate address that is allowed to confirm and reject transactions
function setDelegate(address _address, bool isDelegate) external;
// Change the _upperTransferLimit which is the maximum threshold any single swap can be
function setUpperTransferLimit(uint256 newLimit) external;
// Change the _lowerTransferLimit which is the minimum threshold any single swap can be
function setLowerTransferLimit(uint256 newLimit) external;
// Withdraw the tokens the confirmed swaps to the owner
function withdrawToFoundation(uint256 _amount) external;
// Delete the contract after _earliestDelete timestamp is reached, transfers the remaining
function deleteContract(address payable payoutAddress) external;
// ***
// Restricted functions: Owner or delegate only
// ***
// Reject a swap with reason. Allows the initialiser to immediately withdraw the funds again
function reject(address sender, uint256 id, uint256 expirationBlock, string calldata reason) external;
// Reject multiple swaps with the same reason
function batchReject(
address[] calldata senders,
uint256[] calldata _ids,
uint256[] calldata expirationBlocks,
string calldata reason) external;
// Pause or unpause the transferToNativeTargetAddress() method
function pauseTransferToNativeTargetAddress(bool isPaused) external;
// Pause or unpause the transferToNativeFromKey() method
function pauseTransferToNativeFromKey(bool isPaused) external;
}
contract NativeTokenMigration is Ownable, NativeTokenMigrationInterface {
using SafeMath for uint256;
// minimum time the owner has to wait after the last initialised transfer before allowed to
// delete the contract, in seconds
uint256 constant DELETE_PERIOD = 10 days;
uint256 constant FET_TOTAL_SUPPLY = 1152997575 * 10**18;
uint256 constant DECIMAL_DIFFERENTIATOR = 10**8;
enum Status {Empty, Initialised, Rejected}
struct Swap {
address sender;
uint256 amount;
Status status;
uint256 fee;
}
uint256 public globalSwapID;
// globalSwapID => swap
// usage of a global id instead of address, id pair to simplify processing during the transfer
// over to mainnet
mapping(uint256 => Swap) public swaps;
// global counter increased by every new swap
ERC20 public token;
mapping(address => bool) public delegates;
uint256 public _transferFee;
uint256 public _upperTransferLimit;
uint256 public _lowerTransferLimit;
uint256 public _completedAmount;
bool public _pausedTransferToNativeTargetAddress;
bool public _pausedTransferToNativeFromKey;
uint256 public _earliestDelete;
modifier belowEqualValue(uint256 amount, uint256 threshold) {
require(amount <= threshold, "Value too high");
_;
}
modifier aboveEqualValue(uint256 amount, uint256 threshold) {
require(amount >= threshold, "Value too low");
_;
}
/* Simple length check. Length of FET addresses seem to be either 49 or
50 bytes. Adding a slight margin to this. A proper checksum validation would require a base58
decoder.*/
modifier isFetchAddress(string memory _address) {
require(bytes(_address).length > 47, "Address too short");
require(bytes(_address).length < 52, "Address too long");
_;
}
modifier onlySender(uint256 id) {
require(swaps[id].sender == msg.sender, "Not the sender");
_;
}
/* Only callable by owner or delegate */
modifier onlyDelegate() {
require(isOwner() || delegates[msg.sender], "Caller is neither owner nor delegate");
_;
}
modifier isEqual(uint256 a, uint256 b) {
require(a == b, "Different values");
_;
}
modifier whenNotPaused(bool pauseIndicator) {
require(!pauseIndicator, "Transfers are paused");
_;
}
modifier isRejected(uint256 id) {
require(swaps[id].status == Status.Rejected, "The swap has not been rejected");
_;
}
modifier isInitialised(uint256 id){
require(swaps[id].status == Status.Initialised, "The swap has not been initialised");
_;
}
event SwapInitialised(address indexed sender, uint256 indexed id, string FETAddress, uint256 amount, uint256 fee);
event Rejected(address indexed sender, uint256 indexed id, string reason);
event Refund(address indexed sender, uint256 indexed id);
event RefundRequested(address indexed sender, uint256 indexed id, uint256 amount);
event PauseTransferToNativeTargetAddress(bool isPaused);
event PauseTransferToNativeFromKey(bool isPaused);
event ChangeDelegate(address delegate, bool isDelegate);
event ChangeUpperTransferLimit(uint256 newLimit);
event ChangeLowerTransferLimit(uint256 newLimit);
event ChangeTransferFee(uint256 newFee);
event DeleteContract();
event WithdrawalToFoundation(uint256 amount);
/*******************
Contract start
*******************/
/**
* @param ERC20Address address of the ERC20 contract
*/
constructor(address ERC20Address) public {
token = ERC20(ERC20Address);
_upperTransferLimit = FET_TOTAL_SUPPLY;
_lowerTransferLimit = 0;
_transferFee = 0;
_pausedTransferToNativeTargetAddress = false;
_pausedTransferToNativeFromKey = false;
}
/**
* @notice Return a unit that is divisible by the Fetch mainnet precision
*/
function _toNativeFET(uint256 amount)
internal
pure
returns (uint256)
{
return amount.sub(amount.mod(DECIMAL_DIFFERENTIATOR));
}
/**
* @notice Initialise a swap. Internal only.
*/
function _initSwap(uint256 amount, string memory FETAddress)
internal
belowEqualValue(amount, _upperTransferLimit)
aboveEqualValue(amount, _lowerTransferLimit)
aboveEqualValue(amount, _transferFee)
{
uint256 id = globalSwapID;
globalSwapID = globalSwapID.add(1);
uint256 amountInt = _toNativeFET(amount.sub(_transferFee));
swaps[id].sender = msg.sender;
swaps[id].amount = amountInt;
swaps[id].status = Status.Initialised;
swaps[id].fee = _transferFee;
_completedAmount = _completedAmount.add(amountInt).add(_transferFee);
_earliestDelete = block.timestamp.add(DELETE_PERIOD);
require(token.transferFrom(msg.sender, address(this), amountInt.add(_transferFee)));
emit SwapInitialised(msg.sender, id, FETAddress, amountInt, _transferFee);
}
/**
* @notice Initialise a swap to an address on the Fetch mainnet
* @param amount amount to transfer. Must be below _upperTransferLimit
* @param FETAddress public target address on the Fetch mainnet to transfer the tokens to
* @dev Disregards fractions of FET due to precision differences
* @dev The transfer of ERC20 tokens requires to first approve this transfer with the ERC20
contract by calling ERC20.approve(contractAddress, amount)
*/
function transferToNativeTargetAddress(uint256 amount, string calldata FETAddress)
external
isFetchAddress(FETAddress)
whenNotPaused(_pausedTransferToNativeTargetAddress)
{
_initSwap(amount, FETAddress);
}
/**
* @notice Initialise a swap to an address on the Fetch mainnet that corresponds to the same
private key as used to control the address invoking this address
* @param amount amount to transfer. Must be below _upperTransferLimit
* @dev Disregards fractions of FET due to precision differences
* @dev The transfer of ERC20 tokens requires to first approve this transfer with the ERC20
contract by calling ERC20.approve(contractAddress, amount)
*/
function transferToNativeFromKey(uint256 amount)
external
whenNotPaused(_pausedTransferToNativeFromKey)
{
_initSwap(amount, "");
}
/**
* @notice Reclaim tokens of a swap that has been rejected
* @param id id of the swap to refund
*/
function refund(uint256 id)
external
isRejected(id)
onlySender(id)
{
uint256 amount = swaps[id].amount.add(swaps[id].fee);
emit Refund(msg.sender, id);
delete swaps[id];
require(token.transfer(msg.sender, amount));
}
/**
* @notice Request that a refund be issued. Allows users to "complain" and remind the automated
* server that it might have missed an event somewhere and should try reprocessing it
* @param id id of the swap to refund
*/
function requestRefund(uint256 id)
external
isInitialised(id)
onlySender(id)
{
emit RefundRequested(msg.sender, id, swaps[id].amount);
}
/*******************
Restricted functions
*******************/
/**
* @notice Pause or unpause the transferToNativeTargetAddress() method
* @param isPaused whether to pause or unpause the method
* @dev Delegate only
*/
function pauseTransferToNativeTargetAddress(bool isPaused)
external
onlyDelegate()
{
_pausedTransferToNativeTargetAddress = isPaused;
emit PauseTransferToNativeTargetAddress(isPaused);
}
/**
* @notice Pause or unpause the transferToNativeFromKey() method
* @param isPaused whether to pause or unpause the method
* @dev Delegate only
*/
function pauseTransferToNativeFromKey(bool isPaused)
external
onlyDelegate()
{
_pausedTransferToNativeFromKey = isPaused;
emit PauseTransferToNativeFromKey(isPaused);
}
/**
* @notice Add or remove a delegate address that is allowed to confirm and reject transactions
* @param _address address of the delegate
* @param isDelegate whether to add or remove the address from the delegates set
* @dev Owner only
*/
function setDelegate(address _address, bool isDelegate)
external
onlyOwner()
{
delegates[_address] = isDelegate;
emit ChangeDelegate(_address, isDelegate);
}
/**
* @notice Change the _upperTransferLimit which is the maximum threshold any single swap can be
* @param newLimit new limit in FET * 10**18
* @dev Owner only
*/
function setUpperTransferLimit(uint256 newLimit)
external
onlyOwner()
belowEqualValue(newLimit, FET_TOTAL_SUPPLY)
aboveEqualValue(newLimit, _lowerTransferLimit)
{
_upperTransferLimit = newLimit;
emit ChangeUpperTransferLimit(newLimit);
}
/**
* @notice Change the _lowerTransferLimit which is the minimum threshold any single swap can be
* @param newLimit new limit in FET * 10**18
* @dev Owner only
*/
function setLowerTransferLimit(uint256 newLimit)
external
onlyOwner()
belowEqualValue(newLimit, _upperTransferLimit)
{
_lowerTransferLimit = newLimit;
emit ChangeLowerTransferLimit(newLimit);
}
/**
* @notice Change the _transferFee which is the fee applied to every initialised swap
* @param newFee in FET * 10**18
* @dev This fee will be refunded if the swap is rejected
* @dev Owner only
*/
function setTransferFee(uint256 newFee)
external
onlyOwner()
{
_transferFee = newFee;
emit ChangeTransferFee(newFee);
}
function _reject(address sender, uint256 id, uint256 expirationBlock, string memory reason)
internal
isInitialised(id)
belowEqualValue(block.number, expirationBlock)
{
emit Rejected(sender, id, reason);
swaps[id].status = Status.Rejected;
_completedAmount = _completedAmount.sub(swaps[id].amount).sub(swaps[id].fee);
}
/**
* @notice Reject a swap with reason. Allows the initialiser to immediately withdraw the funds again
* @param sender initialiser of the swap
* @param id id of the swap
* @param reason reason for rejection
* @dev delegate only
*/
function reject(address sender, uint256 id, uint256 expirationBlock, string calldata reason)
external
onlyDelegate()
{
_reject(sender, id, expirationBlock, reason);
}
/**
* @notice Reject multiple swaps with the same reason
* @param senders array of sender addresses
* @param _ids array of swap id's
* @param reason Reason for the rejection. Will be identical across all swaps due to string[]
being only an experimental feature
* @dev delegate only
*/
function batchReject(address[] calldata senders,
uint256[] calldata _ids,
uint256[] calldata expirationBlocks,
string calldata reason)
external
onlyDelegate()
isEqual(senders.length, _ids.length)
isEqual(senders.length, expirationBlocks.length)
{
for (uint256 i = 0; i < senders.length; i++) {
_reject(senders[i], _ids[i], expirationBlocks[i], reason);
}
}
/**
* @notice Withdraw the tokens the confirmed swaps to the owner
* @param _amount amount to withdraw. Set to zero to withdraw all.
* @dev owner only
*/
function withdrawToFoundation(uint256 _amount)
external
onlyOwner()
belowEqualValue(_amount, _completedAmount)
{
uint256 amount;
if (_amount == 0) {
amount = _completedAmount;
} else {
amount = _amount;
}
_completedAmount = _completedAmount.sub(amount);
require(token.transfer(owner(), amount));
emit WithdrawalToFoundation(amount);
}
/**
* @notice Fallback function that allows to increase _completedAmount if the foundation should
* ever withdraw more than required to refund rejected swaps
* @param amount amount to increase _completedAmount by
*/
function topupCompletedAmount(uint256 amount)
external
{
_completedAmount = _completedAmount.add(amount);
require(token.transferFrom(msg.sender, address(this), amount));
}
/**
* @notice Delete the contract after _earliestDelete timestamp is reached, transfers the remaining
token and ether balance to the specified payoutAddress
* @param payoutAddress address to transfer the balances to. Ensure that this is able to handle ERC20 tokens
* @dev owner only
*/
function deleteContract(address payable payoutAddress)
external
onlyOwner()
{
require(block.timestamp >= _earliestDelete, "earliestDelete not reached");
uint256 contractBalance = token.balanceOf(address(this));
require(token.transfer(payoutAddress, contractBalance));
emit DeleteContract();
selfdestruct(payoutAddress);
}
}
|
Change the _lowerTransferLimit which is the minimum threshold any single swap can be newLimit new limit in FET 1018 Owner only/
|
function setLowerTransferLimit(uint256 newLimit)
external
onlyOwner()
belowEqualValue(newLimit, _upperTransferLimit)
{
_lowerTransferLimit = newLimit;
emit ChangeLowerTransferLimit(newLimit);
}
| 12,799,887 |
pragma solidity ^0.4.13;
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;
}
}
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;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract APRInflationToken is StandardToken, Ownable {
// Constants used in calculations
uint256 constant RATE_DECIMALS = 7;
uint256 constant HORIZON = 365 * 10;
uint256 constant ONE_DAY = 86400;
uint256 constant DAY_SCALE = 365 * 10 ** RATE_DECIMALS;
uint256 constant START_RATE = 10 * 10 ** (RATE_DECIMALS - 2);
uint256 constant END_RATE = 1 * 10 ** (RATE_DECIMALS - 2);
uint256 constant ADJ_RATE = (START_RATE - END_RATE) / HORIZON;
// Date control variables
uint256 public startDate;
uint256 public lastAdjust;
// events --------------------------------------------------------------------
event APRMintAdjusted(uint256 _newSupply, uint256 _extraSupply, uint256 _daysPassed, uint256 _rate);
// constructor function ------------------------------------------------------
/**
* @dev Adjusts all the necessary calculations in constructor
*/
function APRInflationToken(uint _startDate) public {
startDate = _startDate;
lastAdjust = 0;
}
// external functions --------------------------------------------------------
/**
* @dev allows anyone to adjust the year mint by calling aprMintAdjustment
* which will calculate days since the latest adjustment and run all calculation
* according N days skipped N days calculated
* @return true
*/
function aprMintAdjustment() public returns (bool) {
uint256 extraSupply;
uint256 day;
for (day = lastAdjust + 1; day <= _currentDay(); day++) {
uint256 rate = _rateFromDay(day);
extraSupply = totalSupply_.mul(rate).div(DAY_SCALE);
totalSupply_ = totalSupply_.add(extraSupply);
balances[owner] = balances[owner].add(extraSupply);
// Adjusts the day of the latest calculation
lastAdjust = day;
APRMintAdjusted(totalSupply_, extraSupply, lastAdjust, rate);
}
return true;
}
function _safeSub(uint256 a, uint256 b) internal pure returns(uint256) {
return b > a ? 0 : a.sub(b);
}
// internal functions --------------------------------------------------------
function _rateFromDay(uint256 day) internal pure returns(uint256) {
if (day < 1) {
return 0;
}
uint256 rate = _safeSub(START_RATE, (day.sub(1)).mul(ADJ_RATE));
return END_RATE > rate ? END_RATE : rate;
}
// Returns the amount of days since the start date
// The calculations are made using the timestamp in seconds
function _currentDay() internal view returns(uint256) {
return now.sub(startDate).div(ONE_DAY);
}
}
contract DelegateCallToken is APRInflationToken {
string public name = 'DelegateCallToken';
string public symbol = 'DCT';
uint8 public decimals = 18;
// one billion
uint256 public constant INITIAL_SUPPLY = 1000000000;
function DelegateCallToken(uint256 _startDate) public
APRInflationToken(_startDate)
{
owner = msg.sender;
totalSupply_ = INITIAL_SUPPLY * (10 ** uint256(decimals));
balances[owner] = totalSupply_;
}
}
|
internal functions --------------------------------------------------------
|
function _rateFromDay(uint256 day) internal pure returns(uint256) {
if (day < 1) {
return 0;
}
uint256 rate = _safeSub(START_RATE, (day.sub(1)).mul(ADJ_RATE));
return END_RATE > rate ? END_RATE : rate;
}
| 11,725,315 |
./full_match/1/0xcccd6EC6F4705292f07eE4a9a8F1F120963358c5/sources/contracts/bridgeToken/adapters/ccip/CCIPBridgeAdapter.sol
|
Executable by Chainlink router, Bridge funds in and mint/give BIFI to the user message Bridge message/
|
function ccipReceive(
IRouterClient.Any2EVMMessage memory message
) external onlyBridge {
if (!whitelistedChains[message.sourceChainSelector]) revert InvalidChain();
if (abi.decode(message.sender, (address)) != address(this)) revert WrongSourceAddress();
(address _user, uint256 _amount) = abi.decode(message.data, (address,uint256));
_bridgeIn(_user, _amount);
emit BridgedIn(ccipIdToChainId[message.sourceChainSelector], _user, _amount);
}
| 4,982,837 |
./full_match/288/0xD05b8fD53614e1569cAC01c6D8d41416d0a7257E/sources/contracts/DAO/governance/GovernorBravoDelegate.sol
|
Initiate the GovernorBravo contract Admin only. Sets initial proposal id which initiates the contract, ensuring a continuous proposal id count/
|
function _initiate() external {
require(msg.sender == admin, "GovernorBravo::_initiate: admin only");
require(initialProposalId == 0, "GovernorBravo::_initiate: can only initiate once");
proposalCount = 0;
initialProposalId = 1;
timelock.acceptAdmin();
}
| 7,103,792 |
//! Casper Interface /* && Casper Interface contract */.
//! By Gabriele Rigo (RigoBlock, Rigo Investment Sagl), 2017.
//! Released under the Apache Licence 2.
pragma solidity ^0.4.15;
//this is the Casper Interface
interface Casper {
//EVENTS
//NON-CONSTANT METHODS
function initiate(uint _epoch_length, uint _withdrawal_delay, address _owner, address _sighasher, address _purity_checker, uint8 _base_interest_factor, uint8 _base_penalty_factor);
function initiate_epoch(uint epoch);
function deposit(address validation_addr, address withdrawal_addr) payable; //would be nice to have: returns (bool success) {}
function logout(bytes logout_msg);
function withdraw(uint validator_index); //would be nice to have: returns (bool success) {}
function proc_reward(uint validator_index, uint16 reward);
function prepare(bytes prepare_msg);
function commit(bytes commit_msg);
function double_prepare_slash(bytes prepare1, bytes prepare2);
function prepare_commit_inconsistency_slash(bytes prepare_msg, bytes commit_msg);
//CONSTANT METHODS
//function balance_of(address validator) constant returns (uint) {} //would be nice to have balances by address in addition of balances by validator_index
function get_deposit_size(uint validator_index) constant returns (uint);
function get_total_curdyn_deposits() constant returns (uint);
function get_total_prevdyn_deposits() constant returns (uint);
function get_recommended_ancestry_hash() constant returns (bytes);
function get_recommended_source_epoch() constant returns (uint);
function get_recommended_source_ancestry_hash() constant returns (bytes);
function get_main_hash_prepared_frac() constant returns (uint8);
function get_main_hash_committed_frac() constant returns (uint8);
}
/*
//the below is the Casper Interface contract
//this is not necessary if one uses the interface
//it helps people who are used to contracts to read
contract CasperFace {
//EVENTS
//NON-CONSTANT METHODS
function initiate(uint _epoch_length, uint _withdrawal_delay, address _owner, address _sighasher, address _purity_checker, uint8 _base_interest_factor, uint8 _base_penalty_factor) {}
function initiate_epoch(uint epoch) {}
function deposit(address validation_addr, address withdrawal_addr) payable {} //would be nice to have: returns (bool success) {}
function logout(bytes logout_msg) {}
function withdraw(uint validator_index) {} //would be nice to have: returns (bool success) {}
function proc_reward(uint validator_index, uint16 reward) {}
function prepare(bytes prepare_msg) {}
function commit(bytes commit_msg) {}
function double_prepare_slash(bytes prepare1, bytes prepare2) {}
function prepare_commit_inconsistency_slash(bytes prepare_msg, bytes commit_msg) {}
//CONSTANT METHODS
//function balance_of(address _who) constant returns (uint) {} //would be nice to have balances by address in addition of balances by validator_index
function get_deposit_size(uint validator_index) constant returns (uint) {}
function get_total_curdyn_deposits() constant returns (uint) {}
function get_total_prevdyn_deposits() constant returns (uint) {}
function get_recommended_ancestry_hash() constant returns (bytes) {}
function get_recommended_source_epoch() constant returns (uint) {}
function get_recommended_source_ancestry_hash() constant returns (bytes) {}
function get_main_hash_prepared_frac() constant returns (uint8) {}
function get_main_hash_committed_frac() constant returns (uint8) {}
}
*/
|
EVENTSNON-CONSTANT METHODSCONSTANT METHODSfunction balance_of(address validator) constant returns (uint) {} would be nice to have balances by address in addition of balances by validator_index
|
interface Casper {
function initiate(uint _epoch_length, uint _withdrawal_delay, address _owner, address _sighasher, address _purity_checker, uint8 _base_interest_factor, uint8 _base_penalty_factor);
function initiate_epoch(uint epoch);
function logout(bytes logout_msg);
function proc_reward(uint validator_index, uint16 reward);
function prepare(bytes prepare_msg);
function commit(bytes commit_msg);
function double_prepare_slash(bytes prepare1, bytes prepare2);
function prepare_commit_inconsistency_slash(bytes prepare_msg, bytes commit_msg);
function get_deposit_size(uint validator_index) constant returns (uint);
function get_total_curdyn_deposits() constant returns (uint);
function get_total_prevdyn_deposits() constant returns (uint);
function get_recommended_ancestry_hash() constant returns (bytes);
function get_recommended_source_epoch() constant returns (uint);
function get_recommended_source_ancestry_hash() constant returns (bytes);
function get_main_hash_prepared_frac() constant returns (uint8);
function get_main_hash_committed_frac() constant returns (uint8);
}
| 896,686 |
pragma solidity ^0.4.0;
contract fsmp {
struct SellOrder{
uint id; //Sell Order Id (auto increment)
address DSO; //Data Storage Owner address of the contract
uint volumeGB; //Volume of disk space, which DSO is ready to sell.
uint pricePerGB; // Min price in wei DSO ready to get for 1 second (will be 1 day in real case) per 1 GB storage
string DSOConnectionInfo; //Specific info to connect to DSO securely
}
struct BuyOrder{
uint id; // Buy Order Id (auto increment)
address DO; //Data Owner address of the contract
uint volumeGB; //Volume of disk space, which DO is ready to buy.
uint pricePerGB; //Max price in wei DO ready to pay for 1 second (will be 1 day in real case) per 1 GB storage
uint weiInitialAmount; // Quantity of wei, that is put into SmartContract at
// the moment of Buy Order creation.
// So it represent real value, that Escrow logic currently manage
// (and real DO intention to pay for future Storage Contract)
string DOConnectionInfo; //Specific info to conect to DO securely
}
struct StorageContract{
uint id; //ContractID (auto increment)
address DO; //Data owner address of the contract
address DSO; //Data storage owner address
string DOConnectionInfo; //Specific info to connect to DO securely
string DSOConnectionInfo; //Specific info to conect to DSO securely
uint volumeGB; //Volume of disk space, which can be provided by DSO.
uint startDate; //Date and time, which, if exists, indicates that the contract has been started
uint stopDate; //Date and time, which, if exists, indicates that the contract has been stopped
uint pricePerGB; //Price in wei to pay for 1 second (will be 1 day in real case) per 1 GB storage
uint weiLeftToWithdraw; //Quantity of wei, that can we withdrawed by DSO
uint withdrawedAtDate; //Last date and time when wei was withdrawed by DSO
}
uint sellOrderId; // auto increment unique id
uint buyOrderId; // auto increment unique id
uint storageContractId; // auto increment unique id
SellOrder[] sellOrderArr; // array of sell orders
BuyOrder[] buyOrderArr; // array of buy orders
StorageContract[] storageContractArr; // array of contracts
//################## Shared function ################################################
function deleteBuyOrderFromArray (uint buyOrderIndex) internal {
//if index not last element in the array
if(buyOrderIndex != buyOrderArr.length-1){
buyOrderArr[buyOrderIndex] = buyOrderArr[buyOrderArr.length-1];
}
buyOrderArr.length--;
}
function deleteSellOrderFromArray (uint sellOrderIndex) internal {
//if index not last element in the array
if(sellOrderIndex != sellOrderArr.length-1){
sellOrderArr[sellOrderIndex] = sellOrderArr[sellOrderArr.length-1];
}
sellOrderArr.length--;
}
function deleteStorageContractFromArray (uint storageContractIndex) internal {
//if index not last element in the array
if(storageContractIndex != storageContractArr.length-1){
storageContractArr[storageContractIndex] = storageContractArr[storageContractArr.length-1];
}
storageContractArr.length--;
}
function weiAllowedToWithdraw(uint storageContractIndex) internal constant returns (uint weiAllowedToWithdraw) {
var c = storageContractArr[storageContractIndex];
if (c.startDate == 0) return 0;
uint calcToDate = now;
if (c.stopDate != 0) calcToDate = c.stopDate;
weiAllowedToWithdraw = (calcToDate - c.withdrawedAtDate) * c.pricePerGB * c.volumeGB;
if (weiAllowedToWithdraw >= c.weiLeftToWithdraw) weiAllowedToWithdraw = c.weiLeftToWithdraw;
return weiAllowedToWithdraw;
}
// ################## Trading ###################################################
// Buy Order
function createBuyOrder(uint volumeGB, uint pricePerGB, string DOConnectionInfo) payable {
buyOrderArr.push(BuyOrder(++buyOrderId, msg.sender, volumeGB, pricePerGB, msg.value, DOConnectionInfo));
}
function cancelBuyOrder(uint buyOrderIndex, uint buyOrderID){
//check if user can cancel an order
if(buyOrderArr[buyOrderIndex].DO == msg.sender && buyOrderArr[buyOrderIndex].id == buyOrderID){
uint amount = buyOrderArr[buyOrderIndex].weiInitialAmount;
deleteBuyOrderFromArray(buyOrderIndex);
if (!msg.sender.send(amount)) throw;
}else{
throw;
}
}
function getBuyOrder(uint buyOrderIndex)constant returns(uint id, address DO, uint volume, uint pricePerGB, uint weiInitialAmount, string DOConnectionInfo){
return (buyOrderArr[buyOrderIndex].id,
buyOrderArr[buyOrderIndex].DO,
buyOrderArr[buyOrderIndex].volumeGB,
buyOrderArr[buyOrderIndex].pricePerGB,
buyOrderArr[buyOrderIndex].weiInitialAmount,
buyOrderArr[buyOrderIndex].DOConnectionInfo);
}
function buyOrdersLength() constant returns(uint) {
return buyOrderArr.length;
}
// Sell Order
function createSellOrder(uint volumeGB, uint pricePerGB, string DSOConnectionInfo) {
sellOrderArr.push(SellOrder(++sellOrderId, msg.sender, volumeGB, pricePerGB, DSOConnectionInfo));
}
function getSellOrder(uint sellOrderIndex)constant returns(uint id, address DSO, uint volume, uint pricePerGB, string DSOConnectionInfo) {
return (sellOrderArr[sellOrderIndex].id,
sellOrderArr[sellOrderIndex].DSO,
sellOrderArr[sellOrderIndex].volumeGB,
sellOrderArr[sellOrderIndex].pricePerGB,
sellOrderArr[sellOrderIndex].DSOConnectionInfo);
}
function sellOrdersLength() constant returns(uint){
return sellOrderArr.length;
}
function cancelSellOrder(uint sellOrderIndex, uint sellOrderID){
//check if user can cancel an order
if(sellOrderArr[sellOrderIndex].DSO == msg.sender && sellOrderArr[sellOrderIndex].id == sellOrderID){
deleteSellOrderFromArray(sellOrderIndex);
return;
}else{
throw;
}
}
}
|
check if user can cancel an order
|
function cancelSellOrder(uint sellOrderIndex, uint sellOrderID){
if(sellOrderArr[sellOrderIndex].DSO == msg.sender && sellOrderArr[sellOrderIndex].id == sellOrderID){
deleteSellOrderFromArray(sellOrderIndex);
return;
throw;
}
}
| 6,380,631 |
./full_match/4/0xCbd380E055A76940fa46bD3Ec85524EF09dE647D/sources/lexlocker.sol
|
Registers an account to serve as a potential `resolver`. active Tracks willingness to serve - if 'true', can be joined to a locker. fee The divisor to determine resolution fee - e.g., if '20', fee is 5% of locker.
|
function registerResolver(bool active, uint8 fee) external cooldown nonReentrant {
require(fee != 0, "FEE_MUST_BE_GREATER_THAN_ZERO");
resolvers[msg.sender] = Resolver(active, fee);
lastActionTimestamp[msg.sender] = block.timestamp;
emit RegisterResolver(msg.sender, active, fee);
}
| 721,004 |
pragma solidity ^0.5.0;
import "./AbstractWrapper.sol";
contract DigitalArtCollectibleERC1155Wrapper is AbstractWrapper {
function initialize() internal {
create(1, 1, "ipfs://QmWAP5TQokmAXWw7mYFapCdDa9piYZE2kVJiqP53NqoQD2");
create(4, 50, "ipfs://Qmf3UT9mmzPZwgf3cSQDEa7ZBji8ntZskrLDBEN1gVscpp");
create(6, 10, "ipfs://QmToz4QuznqSFkb9h4K9soKJ7aMsr9nREnFmYqLCSe3RdH");
create(7, 100, "ipfs://QmRFtHmyQnmXJ75Zxcq9Jb6XPgFyVK9iNdJWwepYx9Eire");
create(8, 10, "ipfs://QmcbfX6GYWTXYw9y6GEWwiuco4cXDZJTnfK88SFuXzfurk");
create(9, 100, "ipfs://QmRWB53RU2YkRDpytq4wrDf7AVvwD65vLKQxjUeAswHU66");
create(10, 100, "ipfs://QmTKR3GjmRqxWaw6QJph7pRnrnfYf23WSMjfAGbeDvt9bA");
create(11, 100, "ipfs://QmVddaQPEX7kREHNq7q7yEBxWcf5WoDHKqiCb7cLvtNZrg");
create(12, 50, "ipfs://QmbaR52MFHjN2hQi9uJGoYX8GNhtLQPPuokBPwJ4ok32W5");
create(13, 50, "ipfs://QmTsy7cSX7UijWndeEsqZb1VKzecyKbosqYrHuEu3Apevh");
create(14, 100, "ipfs://QmZg5DNNBV1wZ8jX5ZMXPLguBxDMQt5DUpyvwVwNiEcR7G");
create(15, 200, "ipfs://QmUMXZTDLQcsB222MYsSSt8TncANDkamnNwhUF7pD6QLCk");
create(16, 50, "ipfs://QmehKVW9PueWFaaaxZ2rHmVJPEKfyjGVCZMgiFYxwVJZAv");
create(17, 100, "ipfs://QmUH2Mf5UdRfL1UeRnJmBNUX1T5L3qGSP7vD5apsu4cp9i");
create(18, 200, "ipfs://QmULb4tuKQHXTro5N9U3jVxxNiLdoGYyippzwacExbTDkW");
create(19, 50, "ipfs://QmYU8WttFNtNmncbxwfcrgay6y25NPNU86PDTWHth4Y7Bs");
create(20, 50, "ipfs://QmW6vr9cmAakVQWxaojo6inFub7QgSGBfBS18fZRNNFmpX");
create(21, 100, "ipfs://QmQ537xkrPNr9wVVF1Lh9Wbf4rZmBQQzxTpCa3tjjBwj9N");
create(22, 200, "ipfs://QmcXtodSRshYVih4VPiHRogg4ysGEwTQEuegx4S9eqStgM");
create(23, 200, "ipfs://QmPLVtPKBC8wAFfe1uLu11ym6wFGKERQc4bb3odjj4YhAC");
create(24, 200, "ipfs://QmPsZyWu1GsCem4ARUGa5QhQYfT3CXNdkHhmVZCET1kFDX");
create(25, 200, "ipfs://QmfXJtR7bCcq28vcYCqFZX8PXtbhK6nxLRqgg21E9qaMSM");
create(26, 100, "ipfs://QmQYH2yyqRGCCtk3oK3r5WVCdJF2Ff7D9dWE7ZFZyo2kXY");
create(27, 200, "ipfs://QmVvaffp7Do9LhEvPGkmSM5B1tEnM34YrCiQTwfDtEABck");
create(28, 100, "ipfs://QmPB8pfwgpnbHRiUz3JwFNpvmKsnBqKhtaEqWggN2FSFdm");
create(29, 200, "ipfs://Qmex4cmDTQecLcXnkVAGc7RHDjgQbaDcydtwmwTyGYNt1e");
create(30, 10, "ipfs://QmcCMakqG9kBAHvFkCUUNVriiXFnEh4ibbTjd3kdZ8hqZk");
create(31, 200, "ipfs://QmfXe9nQurA2uCQPjmCmJk4dQjLK2ifCARVnskNejMd76t");
create(32, 10, "ipfs://QmWdbif88zqWXLfMP9riz1cBBUYuUVHS1CrgdKZtnyRiTj");
create(33, 200, "ipfs://QmdsCLuTN9ongEDmjCurs989PwYPPQofPHjUp5UaJMisvX");
create(34, 50, "ipfs://QmdkHQ2arBVsarLxinm4JG4tk3B1zfFTnWPminTg42GZxm");
create(35, 200, "ipfs://QmX2vGQQLUqRMuHJMHtfPdzSAmc2RXTWen5eLHUCQxdxA6");
create(36, 50, "ipfs://Qmdvjn9WCUKMgYcy2NHi3LSQJofLvW3mZFjdvr1N5AYcYS");
create(37, 200, "ipfs://QmSVKpf6fyVZZ2PVJkCRnLad7BffF1Xh6zEbP5kqkYA2SK");
create(38, 200, "ipfs://QmdQNgpNfJX59wzCHS1UfxSVMJY4YEWLkfqxbnTgA8SCuG");
create(39, 200, "ipfs://QmRsxTm2BCofrVQ5xnWvcmdoDFkvcHpbSJ93Xvr9aDAexq");
create(40, 100, "ipfs://QmY39vaPzVUnd2UTJx89QPJXjBMWXBh75oTvnrdfYVWkHR");
create(41, 100, "ipfs://QmYv4o4L4k1GTS2T2iqjF9JKRXf6oD8kxN4YDGiAZFgNPF");
create(42, 200, "ipfs://QmPhb71kNgm8Rnr9cYESPa68mRn8dWPNRm3UZgjgg94YmS");
create(43, 200, "ipfs://QmSoEVqdf8R4LLAaDGVmu79Y5N1WzauV8tiv4D8PQARz9a");
create(44, 100, "ipfs://Qmbj7MKjZx9vfuLThsBWZsBJffkChcFKhGXhLp2iCtU2u8");
create(45, 100, "ipfs://QmeNUDM6avcRMZYiFqEBTDU3Fz9biypqtTiDnZV6jT7CDi");
create(46, 100, "ipfs://QmXmo2oaQKiVx3rSB5xpHjKq9XYBo6iY2SqUfXr7aERvRy");
create(47, 200, "ipfs://QmSm2C2sZeoNdvQcPKaaVHgrF18sA9rLZJWdzEVw43pCSK");
create(48, 200, "ipfs://QmXh2o3o1qeXYUzzYQXUKUjuvQJuUgGKw8wRM9TKCvCqiR");
create(49, 200, "ipfs://QmPP2hKCVRoo5X9tjZnuAoyvPrKzkjhxBrr3T5awmbBMJT");
create(50, 200, "ipfs://QmZJa3nosLH4csDHs577BR4fPNTQ8beubsksznsyrGeLvJ");
create(51, 200, "ipfs://QmQBhWbbZjbZ7wawBnViZgK4j6xpa7irMXsY9mDnrDLwYp");
create(52, 200, "ipfs://QmQdXA2Mwuho4mqjn7RfvTda7BKXo9A9UiZivrZmZNMtvg");
create(53, 200, "ipfs://QmTCeqs7og4RfJefk7UMwmB1Wm9vWoqXVBJ1LwZy44ECVm");
create(54, 200, "ipfs://QmQQarCamg6DTbegfuTi6GmcaJxj3otS1xp5kk7meymWwX");
create(55, 200, "ipfs://QmeZ9ZjiLRA46ygNCyzMniM4LVF5KGNNMj1zL3E8Wit6j5");
create(56, 100, "ipfs://QmYSfQJBJzAfEUCjfijus67RAdxazY5KiLtSXYVY7BqyXR");
create(57, 200, "ipfs://QmPAzd37Agu4xspCXUKeuerTsTHVrNHK7QN2HxT1r5uPNG");
create(58, 200, "ipfs://QmXkrMH9B5ehk9ftfKqSWZaQ13RzeVrQ2qk5VzeUyPsN5S");
create(61, 100, "ipfs://QmSr3hcyg6DBcncy85pN6bZfTStEQCqrc4pswAtcMJUK7B");
create(62, 200, "ipfs://QmcBPVKpESwSNLhbQnxQv1oEBqR46jZrUNnW5cbL4Dr7LC");
create(63, 200, "ipfs://QmZyTS3NmG97L6gP2DorGTp67Bw3GXUGMDMrQfPYd6uD2B");
create(64, 200, "ipfs://Qmc3sGP18Gy8J7oh7MjD4Ym8eJDapv4mk1nM1nv3z2yhuv");
create(65, 200, "ipfs://QmedZmtCg5c5h4pDZzM26kE5vQmUp5xUKEBAbGhhUhvcxH");
create(66, 50, "ipfs://QmVpqZC1aKYNhPeJap5Dz3UdJVqf8kRXk1FpGVTE3za1ec");
create(67, 200, "ipfs://QmZ5xPstBG7PMLqFed1xLVJJWDuwAP3Y512mSjpM4vNW9j");
create(68, 100, "ipfs://QmXsUV7QEYxXXbgYjXdqmM8duYg1aJsf2Nr7fbbjxpQAKP");
create(69, 10, "ipfs://QmUbrnb3zXSdc55mBLRSYBMiBpvG1MNo9YbCno2RcB3oif");
create(70, 50, "ipfs://QmcQuf4f7QyxdArtpBNenakyy1JQFGPfMGBwbk9FBtAAcw");
create(71, 100, "ipfs://QmSCqCzwv36cpsnkTDYqL7zSxkDfBQLyvM1ttaFcCUWszR");
}
constructor(address _proxyRegistryAddress, address digitalArtCollectibleAddress) AbstractWrapper(_proxyRegistryAddress, digitalArtCollectibleAddress) public {
}
}
pragma solidity ^0.5.0;
import "./ERC1155.sol";
import "./IDigitalArtCollectible.sol";
import "./IProxyRegistry.sol";
import "./SafeMath.sol";
import "./Address.sol";
contract AbstractWrapper is ERC1155 {
using SafeMath for uint256;
using Address for address;
IDigitalArtCollectible public _DigitalArtCollectibleContract;
// OpenSea's Proxy Registry
IProxyRegistry public proxyRegistry;
// Standard attributes
string public name;
string public symbol;
// starts as allowed
bool isExecutionAllowed = true;
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// nft id => nft metadata IPFS URI
mapping (uint256 => string) public metadatas;
// nft id => nft total supply
mapping(uint => uint) public tokenSupply;
// print index => whether is wrapped
mapping(uint => bool) public wrappedPrints;
function initialize() internal;
/**
@notice Initialize an nft id's data.
*/
function create(uint256 _id, uint256 _totalSupply, string memory _uri) internal {
require(tokenSupply[_id] == 0, "id already exists");
tokenSupply[_id] = _totalSupply;
// mint 0 just to let explorers know it exists
// emit TransferSingle(msg.sender, address(0), msg.sender, _id, 0);
metadatas[_id] = _uri;
emit URI(_uri, _id);
}
constructor(address _proxyRegistryAddress, address digitalArtCollectibleAddress) public {
proxyRegistry = IProxyRegistry(_proxyRegistryAddress);
_DigitalArtCollectibleContract = IDigitalArtCollectible(digitalArtCollectibleAddress);
_owner = msg.sender;
// Set the name for display purposes
name = "Cryptocards";
// Set the symbol for display purposes
symbol = "WƉ";
initialize();
}
/**
@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(), "Not owner");
_;
}
/**
* @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 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;
}
/**
@dev override ERC1155 uri function to return IPFS ref.
@param _id NFT ID
@return IPFS URI pointing to NFT ID's metadata.
*/
function uri(uint256 _id) public view returns (string memory) {
return metadatas[_id];
}
/**
* @dev Will update the metadata for a token
* @param _tokenId The token to update. _msgSender() must be its creator.
* @param _newURI New URI for the token.
*/
function setCustomURI(uint256 _tokenId, string memory _newURI) public onlyOwner {
metadatas[_tokenId] = _newURI;
emit URI(_newURI, _tokenId);
}
/**
@notice Queries the approval status of an operator for a given owner.
@param _user The owner of the Tokens
@param _operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address _user, address _operator) public view returns (bool) {
// Whitelist OpenSea proxy contract for easy trading.
if (proxyRegistry.proxies(_user) == _operator) {
return true;
}
return super.isApprovedForAll(_user, _operator);
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
@dev helper function to see if NFT ID exists, makes OpenSea happy.
@param _id NFT ID
@return if NFT ID exists.
*/
function exists(uint256 _id) external view returns(bool) {
// requires the drawing id to actually exist
return tokenSupply[_id] != 0;
}
/**
@dev for an NFT ID, queries and transfers tokens from the appropriate
collectible contract to itself, and mints and transfers corresponding new
ERC-1155 tokens to caller.
*/
function wrap(uint256 _id, uint256[] calldata _printIndexes) external {
require(isExecutionAllowed);
address _to = msg.sender;
uint256 _quantity = _printIndexes.length;
for (uint256 i=0; i < _quantity; ++i) {
uint256 _printIndex = _printIndexes[i];
address owner_address = _DigitalArtCollectibleContract.DrawingPrintToAddress(_printIndex);
// Check if caller owns the ERC20
require(owner_address == msg.sender, "Does not own ERC20");
_DigitalArtCollectibleContract.buyCollectible(_id, _printIndex);
// Check if buy succeeded
require(_DigitalArtCollectibleContract.DrawingPrintToAddress(_printIndex) == address(this), "An error occured");
wrappedPrints[_printIndex] = true;
balances[_id][msg.sender] = balances[_id][msg.sender].add(1);
}
// mint
emit TransferSingle(msg.sender, address(0), msg.sender, _id, _quantity);
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, msg.sender, msg.sender, _id, _quantity, '');
}
}
/**
@dev for an NFT ID, burns ERC-1155 quantity and transfers cryptoart ERC-20
tokens to caller.
*/
function unwrap(uint256 _id, uint256[] calldata _printIndexes) external {
require(isExecutionAllowed);
uint256 _quantity = _printIndexes.length;
require(balances[_id][msg.sender] >= _quantity, "insufficient balance");
for (uint256 i=0; i < _quantity; ++i) {
uint256 _printIndex = _printIndexes[i];
bool success = _DigitalArtCollectibleContract.transfer(msg.sender, _id, _printIndex);
// Check if transfer succeeded
require(success, "An error occured while transferring");
wrappedPrints[_printIndex] = false;
balances[_id][msg.sender] = balances[_id][msg.sender].sub(1);
}
// burn
emit TransferSingle(msg.sender, address(this), address(0), _id, _quantity);
}
/**
@dev bulk buy presale items
*/
function bulkPreBuyCollectible(uint256 _id, uint256[] calldata _printIndexes, uint256 initialPrintPrice) external payable {
require(isExecutionAllowed);
address _to = msg.sender;
uint256 _quantity = _printIndexes.length;
for (uint256 i=0; i < _quantity; ++i) {
uint256 _printIndex = _printIndexes[i];
_DigitalArtCollectibleContract.alt_buyCollectible.value(initialPrintPrice)(_id, _printIndex);
require(_DigitalArtCollectibleContract.DrawingPrintToAddress(_printIndex) == address(this), "An error occured");
wrappedPrints[_printIndex] = true;
balances[_id][msg.sender] = balances[_id][msg.sender].add(1);
}
// mint
emit TransferSingle(msg.sender, address(0), msg.sender, _id, _quantity);
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, msg.sender, msg.sender, _id, _quantity, '');
}
}
function flipSwitchTo(bool state) public onlyOwner {
isExecutionAllowed = state;
}
}
pragma solidity ^0.5.0;
import "./SafeMath.sol";
import "./Address.sol";
import "./Common.sol";
import "./IERC1155TokenReceiver.sol";
import "./IERC1155.sol";
// A sample implementation of core ERC1155 function.
contract ERC1155 is IERC1155, ERC165, CommonConstants
{
using SafeMath for uint256;
using Address for address;
// id => (owner => balance)
mapping (uint256 => mapping(address => uint256)) internal balances;
// owner => (operator => approved)
mapping (address => mapping(address => bool)) internal operatorApproval;
/////////////////////////////////////////// ERC165 //////////////////////////////////////////////
/*
bytes4(keccak256('supportsInterface(bytes4)'));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/*
bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
bytes4(keccak256("balanceOf(address,uint256)")) ^
bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
bytes4(keccak256("setApprovalForAll(address,bool)")) ^
bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
function supportsInterface(bytes4 _interfaceId)
public
view
returns (bool) {
if (_interfaceId == INTERFACE_SIGNATURE_ERC165 ||
_interfaceId == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
/////////////////////////////////////////// ERC1155 //////////////////////////////////////////////
/**
@notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _id ID of the token type
@param _value Transfer amount
@param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external {
require(_to != address(0x0), "_to must be non-zero.");
require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers.");
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[_id][_from] = balances[_id][_from].sub(_value);
balances[_id][_to] = _value.add(balances[_id][_to]);
// MUST emit event
emit TransferSingle(msg.sender, _from, _to, _id, _value);
// Now that the balance is updated and the event was emitted,
// call onERC1155Received if the destination is a contract.
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, _from, _to, _id, _value, _data);
}
}
/**
@notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if length of `_ids` is not the same as length of `_values`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _ids IDs of each token type (order and length must match _values array)
@param _values Transfer amounts per token type (order and length must match _ids array)
@param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external {
// MUST Throw on errors
require(_to != address(0x0), "destination address must be non-zero.");
require(_ids.length == _values.length, "_ids and _values array length must match.");
require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers.");
for (uint256 i = 0; i < _ids.length; ++i) {
uint256 id = _ids[i];
uint256 value = _values[i];
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[id][_from] = balances[id][_from].sub(value);
balances[id][_to] = value.add(balances[id][_to]);
}
// Note: instead of the below batch versions of event and acceptance check you MAY have emitted a TransferSingle
// event and a subsequent call to _doSafeTransferAcceptanceCheck in above loop for each balance change instead.
// Or emitted a TransferSingle event for each in the loop and then the single _doSafeBatchTransferAcceptanceCheck below.
// However it is implemented the balance changes and events MUST match when a check (i.e. calling an external contract) is done.
// MUST emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _values);
// Now that the balances are updated and the events are emitted,
// call onERC1155BatchReceived if the destination is a contract.
if (_to.isContract()) {
_doSafeBatchTransferAcceptanceCheck(msg.sender, _from, _to, _ids, _values, _data);
}
}
/**
@notice Get the balance of an account's Tokens.
@param _owner The address of the token holder
@param _id ID of the Token
@return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id) external view returns (uint256) {
// The balance of any account can be calculated from the Transfer events history.
// However, since we need to keep the balances to validate transfer request,
// there is no extra cost to also privide a querry function.
return balances[_id][_owner];
}
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the Tokens
@return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory) {
require(_owners.length == _ids.length);
uint256[] memory balances_ = new uint256[](_owners.length);
for (uint256 i = 0; i < _owners.length; ++i) {
balances_[i] = balances[_ids[i]][_owners[i]];
}
return balances_;
}
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@param _operator Address to add to the set of authorized operators
@param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external {
operatorApproval[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
@notice Queries the approval status of an operator for a given owner.
@param _owner The owner of the Tokens
@param _operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApproval[_owner][_operator];
}
/////////////////////////////////////////// Internal //////////////////////////////////////////////
function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 _id, uint256 _value, bytes memory _data) internal {
// If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
// the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.
// Note: if the below reverts in the onERC1155Received function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
// If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_ACCEPTED test.
require(ERC1155TokenReceiver(_to).onERC1155Received(_operator, _from, _id, _value, _data) == ERC1155_ACCEPTED, "contract returned an unknown value from onERC1155Received");
}
function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) internal {
// If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
// the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.
// Note: if the below reverts in the onERC1155BatchReceived function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
// If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_BATCH_ACCEPTED test.
require(ERC1155TokenReceiver(_to).onERC1155BatchReceived(_operator, _from, _ids, _values, _data) == ERC1155_BATCH_ACCEPTED, "contract returned an unknown value from onERC1155BatchReceived");
}
}
pragma solidity ^0.5.0;
// DigitalArtCollectible is not quite ERC-20 compliant
interface IDigitalArtCollectible {
function transfer(address to, uint drawingId, uint printIndex) external returns (bool success);
function DrawingPrintToAddress(uint print) external returns (address _address);
function buyCollectible(uint drawingId, uint printIndex) external payable;
function alt_buyCollectible(uint drawingId, uint printIndex) external payable;
}
pragma solidity ^0.5.0;
interface IProxyRegistry {
function proxies(address) external view returns (address);
}
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// 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;
}
}
pragma solidity ^0.5.0;
/**
* 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.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity ^0.5.0;
/**
Note: Simple contract to use as base for const vals
*/
contract CommonConstants {
bytes4 constant internal ERC1155_ACCEPTED = 0xf23a6e61; // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
bytes4 constant internal ERC1155_BATCH_ACCEPTED = 0xbc197c81; // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
}
pragma solidity ^0.5.0;
/**
Note: The ERC-165 identifier for this interface is 0x4e2312e0.
*/
interface ERC1155TokenReceiver {
/**
@notice Handle the receipt of a single ERC1155 token type.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated.
This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer.
This function MUST revert if it rejects the transfer.
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@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)"))`
*/
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4);
/**
@notice Handle the receipt of multiple ERC1155 token types.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated.
This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s).
This function MUST revert if it rejects the transfer(s).
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@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)"))`
*/
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4);
}
pragma solidity ^0.5.0;
import "./ERC165.sol";
/**
@title ERC-1155 Multi Token Standard
@dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md
Note: The ERC-165 identifier for this interface is 0xd9b67a26.
*/
interface IERC1155 /* is ERC165 */ {
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be msg.sender.
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_id` argument MUST be the token type being transferred.
The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value);
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be msg.sender.
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_ids` argument MUST be the list of tokens being transferred.
The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values);
/**
@dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absense of an event assumes disabled).
*/
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
@dev MUST emit when the URI is updated for a token ID.
URIs are defined in RFC 3986.
The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".
*/
event URI(string _value, uint256 indexed _id);
/**
@notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _id ID of the token type
@param _value Transfer amount
@param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;
/**
@notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if length of `_ids` is not the same as length of `_values`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _ids IDs of each token type (order and length must match _values array)
@param _values Transfer amounts per token type (order and length must match _ids array)
@param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external;
/**
@notice Get the balance of an account's Tokens.
@param _owner The address of the token holder
@param _id ID of the Token
@return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the Tokens
@return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@param _operator Address to add to the set of authorized operators
@param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
@notice Queries the approval status of an operator for a given owner.
@param _owner The owner of the Tokens
@param _operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
pragma solidity ^0.5.0;
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @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);
}
|
/ mint 0 just to let explorers know it exists emit TransferSingle(msg.sender, address(0), msg.sender, _id, 0);
|
function create(uint256 _id, uint256 _totalSupply, string memory _uri) internal {
require(tokenSupply[_id] == 0, "id already exists");
tokenSupply[_id] = _totalSupply;
metadatas[_id] = _uri;
emit URI(_uri, _id);
}
| 7,031,661 |
pragma solidity ^0.5.12;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
contract minterests is Ownable, ReentrancyGuard {
using SafeMath for uint256;
/**
* @dev Represents the balance of a given user. The 'previous' field is used to store the
* balance of the previous month in order to ponderate the bond's held time when updating
* interests.
*/
struct Balance {
// Total number of tokens held last month.
uint256 previousBalance;
// Total number of tokens held atm.
uint256 currentBalance;
// Total number of months these tokens have been held as of last month.
uint256 previousHolding;
// Total number of months these tokens have been held atm.
uint256 currentHolding;
// How much tokens has been bought through referral.
uint256 refereeBalance;
}
/**
* @dev Represents the claiming informations of an investor :
* Whether he is claiming and in which currency he whishes to get paid.
*/
struct Claiming {
// Tells wether investor is claiming its interests or not.
bool claiming;
// The currency type to be delivered, Euro or Ether.
bytes32 currency;
// The name of the bond partition to be redeemed.
bytes32 partitionNameInHex;
}
/**
* @dev Represents all about an investor.
*/
struct Info {
// Calculated according to the balance, the held time, and the token type.
// It needs to be multiplied by 10 to get the € value.
uint256 balanceInterests;
// User status about his willing to claim its interests.
Claiming claimingInterests;
// User status about his willing to redeem its midterm or longterm bonds.
Claiming claimingBonds;
// Total of midterm bond tokens.
Balance mid;
// Total of longterm bond tokens.
Balance lng;
// Total of perpetual bond tokens.
Balance per;
}
// The state of each investor.
mapping (address => Info) investors;
// A list of "superuser" that have control over a few methods of this contract,
// not a controller as in ERC1400. Used to allow third-parties to update an investor's
// infos.
mapping (address => bool) _isInterestsController;
// To what extent an interest unit can be divided (10^18).
uint256 DECIMALS = 1000000000000000000;
/**************************** MWT_interests events ********************************/
// Emitted when an investor invested through a referal link.
event Refered (
address indexed referer,
address indexed referee,
uint256 midAmount,
uint256 lngAmount,
uint256 perAmount
);
// Emitted when the balance of an investor which invested through
// a referal link is updated.
event ModifiedReferee (
address indexed investor,
uint256 midAmount,
uint256 lngAmount,
uint256 perAmount
);
// Emitted when an investor's interests balance is modified.
event UpdatedInterests (
address indexed investor,
uint256 interests
);
// Special case when a controller directly modified an investor's
// interests balance.
event ModifiedInterests (
address indexed investor,
uint256 value
);
// Emitted when an "interest controller" is addded or removed.
event ModifiedInterestsController (
address indexed controller,
bool value
);
// Emitted when the claiming state of the investor is modified.
event ModifiedClaimingInterests (
address indexed investor,
bool claiming,
bytes32 currency
);
// Emitted when an user's interests are to be paid in euros by
// the third party.
event WillBePaidInterests (
address indexed investor,
uint256 balanceInterests
);
// Emitted when the bonds claiming status of an investor changed.
event ModifiedClaimingBonds (
address indexed investor,
bool claiming,
bytes32 currency,
bytes32 partitionNameInHex
);
// Emitted when an user's bonds are to be paid in euros by
// the third party.
event WillBePaidBonds (
address indexed investor,
bytes32 partitionNameInHex,
uint256 claimedAmount
);
// Emitted when the number of months an investor has been holding
// each bond is modified. It's modified when a month has passed,
// when the bonds are redeemed, or when set ad hoc by the contract
// owner.
event ModifiedHoldings (
address indexed investor,
uint256 midHolding,
uint256 lngHolding,
uint256 perHolding
);
// Emitted when an user redeems more bonds that we know he got. This
// seems sneaky, and actually it is : the bonds balance is on another
// contract (ERC1400) and we know about the actual balance of the
// investor when we call `updateInterests`, once each month...
event ModifiedHoldingsAndBalanceError (
address indexed investor,
bytes32 partitionNameInHex,
uint256 holding,
uint256 balance
);
// Emitted when an investor's interests balance is modified. It's
// modified when one month has passed, when bonds are redeemed, or
// when the balance is set ad hoc by the contract owner.
event ModifiedBalances (
address indexed investor,
uint256 midBalance,
uint256 lngBalance,
uint256 perBalance
);
/**************************** MWT_interests getters ********************************/
/**
* @dev Get the interests balance of an investor.
*/
function interestsOf (address investor) external view returns (uint256) {
return (investors[investor].balanceInterests);
}
/**
* @dev Check whether an address is an "interest controller" (a third-party superuser).
*/
function isInterestsController (address _address) external view returns (bool) {
return (_isInterestsController[_address]);
}
/**
* @dev Check whether an investor is currently claiming its interests, and in which currency.
*/
function isClaimingInterests (address investor) external view returns (bool, bytes32) {
return (investors[investor].claimingInterests.claiming, investors[investor].claimingInterests.currency);
}
/**
* @dev Check whether an investor is currently claiming its bonds, which one(s), and in which currency.
*/
function isClaimingBonds (address investor) external view returns (bool, bytes32, bytes32) {
return (
investors[investor].claimingBonds.claiming,
investors[investor].claimingBonds.currency,
investors[investor].claimingBonds.partitionNameInHex
);
}
/**
* @dev Get the midterm bond infos of an investor.
*/
function midtermBondInfosOf (address investor) external view returns (
uint256,
uint256,
uint256
) {
return (
investors[investor].mid.currentBalance,
investors[investor].mid.currentHolding,
investors[investor].mid.refereeBalance
);
}
/**
* @dev Get the longterm bond infos of an investor.
*/
function longtermBondInfosOf (address investor) external view returns (
uint256,
uint256,
uint256
) {
return (
investors[investor].lng.currentBalance,
investors[investor].lng.currentHolding,
investors[investor].lng.refereeBalance
);
}
/**
* @dev Get the perpetual bond infos of an investor.
*/
function perpetualBondInfosOf (address investor) external view returns (
uint256,
uint256,
uint256
) {
return (
investors[investor].per.currentBalance,
investors[investor].per.currentHolding,
investors[investor].per.refereeBalance
);
}
/**************************** MWT_interests external functions ********************************/
/**
* @dev Allows an investor to express his desire to redeem his interests.
*/
function claimInterests (bool claiming, bytes32 _currency) external {
bytes32 currency = _currency;
require (currency == "eur" || currency == "eth", "A8"); // Transfer Blocked - Token restriction
uint256 minimum = currency == "eth" ? 10 : 100; // ie: 100 euros
require (investors[msg.sender].balanceInterests >= minimum.mul(DECIMALS), "A6"); // Transfer Blocked - Receiver not eligible
if (!claiming) {
currency = "";
}
investors[msg.sender].claimingInterests.claiming = claiming;
investors[msg.sender].claimingInterests.currency = currency;
emit ModifiedClaimingInterests (msg.sender, claiming, currency);
}
/**
* @dev This function updates interests balance for several investors, so that they can be paid by the third party.
*/
function payInterests (address[] calldata investorsAddresses) external nonReentrant {
require (_isInterestsController[msg.sender], "A5"); // Your are not allowed to perform this action
for (uint i = 0; i < investorsAddresses.length; i++) {
require (investors[investorsAddresses[i]].claimingInterests.claiming, "A6"); // This investor is not currently claiming
investors[investorsAddresses[i]].claimingInterests.claiming = false;
investors[investorsAddresses[i]].claimingInterests.currency = "";
emit ModifiedClaimingInterests(investorsAddresses[i], false, "");
emit WillBePaidInterests(investorsAddresses[i], investors[investorsAddresses[i]].balanceInterests);
investors[investorsAddresses[i]].balanceInterests = 0;
emit UpdatedInterests(investorsAddresses[i], investors[investorsAddresses[i]].balanceInterests);
}
}
/**
* @dev Allows an investor to claim one of its bonds.
*/
function claimBond (bool claiming, bytes32 _currency, bytes32 partition) external {
uint256 bondYear = 0;
uint256 bondMonth = 0;
bytes32 currency = _currency;
require (currency == "eur" || currency == "eth", "A8"); // Transfer Blocked - Token restriction
// This function is only for midterm and longterm bonds, which have a restricted period
// before they can be withdrawn.
// We use 3 utf8 characters in each partition to identify it ("mid" for the midterm ones and "lng" for the longterm
// ones).
require ((partition[0] == "m" && partition[1] == "i" && partition[2] == "d")
|| (partition[0] == "l" && partition[1] == "n" && partition[2] == "g"), "A6");
// Retrieving the bond issuance date (YYYYMM) from an UTF8 encoded string.
for (uint i = 4; i < 10; i++) {
// Is it a valid UTF8 digit ? https://www.utf8-chartable.de/unicode-utf8-table.pl
require ((uint8(partition[i]) >= 48) && (uint8(partition[i]) <= 57), "A6"); // Transfer Blocked - Receiver not eligible
}
// The first digit is the millenium.
bondYear = bondYear.add(uint256(uint8(partition[4])).sub(48).mul(1000));
// The second one is the century.
bondYear = bondYear.add(uint256(uint8(partition[5])).sub(48).mul(100));
// The third one is the <is there a name for a ten year period ?>.
bondYear = bondYear.add(uint256(uint8(partition[6])).sub(48).mul(10));
// The fourth one is the year unit.
bondYear = bondYear.add(uint256(uint8(partition[7])).sub(48));
// Same for month, but it has only two digits.
bondMonth = bondMonth.add(uint256(uint8(partition[8])).sub(48).mul(10));
bondMonth = bondMonth.add(uint256(uint8(partition[9])).sub(48));
// Did the boutique decoding fucked up ? :-)
require (bondYear >= 2000);
require (bondMonth >= 0 && bondMonth <= 12);
// Calculating the elapsed time since bond issuance
uint256 elapsedMonths = (bondYear * 12 + bondMonth) - 23640;
uint256 currentTime;
assembly {
currentTime := timestamp()
}
// conversion of the current time (in sec) since epoch to months
uint256 currentMonth = currentTime / 2630016;
uint256 deltaMonths = currentMonth - elapsedMonths;
if (partition[0] == "m" && partition[1] == "i" && partition[2] == "d") {
// This is a midterm bond, 5 years (60 months) should have passed.
require (deltaMonths >= 60, "A6"); // Transfer Blocked - Receiver not eligible
} else if (partition[0] == "l" && partition[1] == "n" && partition[2] == "g") {
// This is a longterm bond, 10 years (120 months) should have passed.
require (deltaMonths >= 120, "A6"); // Transfer Blocked - Receiver not eligible
} else {
// This is __not__ possible !
assert (false);
}
investors[msg.sender].claimingBonds.claiming = claiming;
investors[msg.sender].claimingBonds.currency = claiming ? currency : bytes32("");
investors[msg.sender].claimingBonds.partitionNameInHex = claiming ? partition : bytes32("");
emit ModifiedClaimingBonds(
msg.sender,
claiming,
investors[msg.sender].claimingBonds.currency,
investors[msg.sender].claimingBonds.partitionNameInHex
);
}
/**
* @dev This functions is called after the investor expressed its desire to redeem its bonds using the above
* function (claimBonds). It needs to be called __before__ the third party pays the investor its bonds
* in fiat.
*
* @param claimedAmount The balance of the investor on the redeemed partition.
*/
function payBonds (address investor, uint256 claimedAmount) external nonReentrant {
require (_isInterestsController[msg.sender], "A5"); // You are not allowed to perform this action
require (investors[investor].claimingBonds.claiming, "A6"); // This investor is not currently claiming
investors[investor].claimingBonds.claiming = false;
// This function is only for midterm and longterm bonds, which have a restricted period
// before they can be withdrawn.
// We use 3 utf8 characters in each partition to identify it ("mid" for the midterm ones and "lng" for the longterm
// ones).
bytes32 partition = investors[investor].claimingBonds.partitionNameInHex;
require ((partition[0] == "m" && partition[1] == "i" && partition[2] == "d")
|| (partition[0] == "l" && partition[1] == "n" && partition[2] == "g"), "A6");
// If all balances of a partition type are empty, we need to reset the "holding" variable.
uint256 midLeft = 0;
uint256 lngLeft = 0;
bool emitHoldingEvent = false;
if (partition[0] == "m" && partition[1] == "i" && partition[2] == "d") {
// For the midterm bonds.
if (claimedAmount < investors[investor].mid.currentBalance) {
// All partitions of this type are not empty, no need to update holding.
midLeft = investors[investor].mid.currentBalance.sub(claimedAmount);
} else if (claimedAmount == investors[investor].mid.currentBalance) {
// The investor just withdrew all bonds from all partitions of this type.
// There is a possibility that an investor could refill the __exact same__ amount of the
// __same partition type__ before we update the interests, i.e. before the end of the month.
// Example: let's be an investor with the foolowing balances.
// mid_201001 = 200, mid_201801 = 200, currentBalance = mid_201001 + mid_201801 = 400
// If this investor refills mid_201801 with 200, then mid_201801 = 400 = currentBalance.
// In that case, holding would be reseted whereas the investor still has 200 mid_201001
// Since this case should be extremly rare, we do not emit an error event.
investors[investor].mid.previousHolding = 0;
investors[investor].mid.currentHolding = 0;
emitHoldingEvent = true;
} else {
// This case should normally not occur.
// If the current holding is not up to date regarding token balances, it means that the
// investor refilled its balance after claiming bonds but before we update the interests.
// This period lasts at most one month.
// We reset holding and balance too (which could mess up adjustmentRate), but we emit an event.
emit ModifiedHoldingsAndBalanceError(
investor,
investors[investor].claimingBonds.partitionNameInHex,
investors[investor].mid.currentHolding,
investors[investor].mid.currentBalance
);
investors[investor].mid.previousHolding = 0;
investors[investor].mid.currentHolding = 0;
emitHoldingEvent = true;
}
// There are some units left only if the investor had other partitions of the same type.
investors[investor].mid.previousBalance = midLeft;
investors[investor].mid.currentBalance = midLeft;
} else if (partition[0] == "l" && partition[1] == "n" && partition[2] == "g") {
if (claimedAmount < investors[investor].lng.currentBalance) {
// All partitions of this type are not empty, no need to update holding.
lngLeft = investors[investor].lng.currentBalance.sub(claimedAmount);
} else if (claimedAmount == investors[investor].lng.currentBalance) {
// Same as in the precedent branch, but with longterm bonds.
investors[investor].lng.previousHolding = 0;
investors[investor].lng.currentHolding = 0;
emitHoldingEvent = true;
} else {
// See above for the details of this sneaky case..
emit ModifiedHoldingsAndBalanceError(
investor,
investors[investor].claimingBonds.partitionNameInHex,
investors[investor].lng.currentHolding,
investors[investor].lng.currentBalance
);
investors[investor].lng.previousHolding = 0;
investors[investor].lng.currentHolding = 0;
emitHoldingEvent = true;
}
// There are some units left only if the investor had other partitions of the same type.
investors[investor].lng.previousBalance = lngLeft;
investors[investor].lng.currentBalance = lngLeft;
} else {
// We should __not__ get here !
assert (false);
}
emit WillBePaidBonds(
investor,
partition,
claimedAmount
);
investors[investor].claimingBonds.currency = "";
investors[investor].claimingBonds.partitionNameInHex = "";
emit ModifiedClaimingBonds(
investor,
false,
investors[investor].claimingBonds.currency,
investors[investor].claimingBonds.partitionNameInHex
);
if (emitHoldingEvent) {
emit ModifiedHoldings(
investor,
investors[investor].mid.currentHolding,
investors[investor].lng.currentHolding,
investors[investor].per.currentHolding
);
}
emit ModifiedBalances(
investor,
investors[investor].mid.currentBalance,
investors[investor].lng.currentBalance,
investors[investor].per.currentBalance
);
}
/**
* @dev Set how much time an investor has been holding each bond.
*/
function setHoldings (address investor, uint256 midHolding, uint256 lngHolding, uint256 perHolding) external onlyOwner {
investors[investor].mid.previousHolding = midHolding;
investors[investor].mid.currentHolding = midHolding;
investors[investor].lng.previousHolding = lngHolding;
investors[investor].lng.currentHolding = lngHolding;
investors[investor].per.previousHolding = perHolding;
investors[investor].per.currentHolding = perHolding;
emit ModifiedHoldings(investor, midHolding, lngHolding, perHolding);
}
/**
* @dev Set custom balances for an investor.
*/
function setBalances (address investor, uint256 midBalance, uint256 lngBalance, uint256 perBalance) external onlyOwner {
investors[investor].mid.previousBalance = midBalance;
investors[investor].mid.currentBalance = midBalance;
investors[investor].lng.previousBalance = lngBalance;
investors[investor].lng.currentBalance = lngBalance;
investors[investor].per.previousBalance = perBalance;
investors[investor].per.currentBalance = perBalance;
emit ModifiedBalances(investor, midBalance, lngBalance, perBalance);
}
/**
* @dev Set the interests balance of an investor.
*/
function setInterests (address investor, uint256 value) external onlyOwner {
investors[investor].balanceInterests = value;
emit ModifiedInterests(investor, value);
emit UpdatedInterests(investor, investors[investor].balanceInterests);
}
/**
* @dev Add or remove an address from the InterestsController mapping.
*/
function setInterestsController (address controller, bool value) external onlyOwner {
_isInterestsController[controller] = value;
emit ModifiedInterestsController(controller, value);
}
/**
* @dev Increases the referer interests balance of a given amount.
*
* @param referer The address of the referal initiator
* @param referee The address of the referal consumer
* @param percent The percentage of interests earned by the referer
* @param midAmount How many mid term bonds the referee bought through this referal
* @param lngAmount How many long term bonds the referee bought through this referal
* @param perAmount How many perpetual tokens the referee bought through this referal
*/
function updateReferralInfos (
address referer,
address referee,
uint256 percent,
uint256 midAmount,
uint256 lngAmount,
uint256 perAmount
) external onlyOwner {
// Referee and/or referer address(es) is(/are) not valid.
require (referer != referee && referer != address(0) && referee != address(0), "A7");
// The given percent parameter is not a valid percentage.
require (percent >= 1 && percent <= 100, "A8");
// Updates referer interests balance accounting for the referee investment
investors[referer].balanceInterests = investors[referer].balanceInterests.add(midAmount.mul(percent).div(100));
investors[referer].balanceInterests = investors[referer].balanceInterests.add(lngAmount.mul(percent).div(100));
investors[referer].balanceInterests = investors[referer].balanceInterests.add(perAmount.mul(percent).div(100));
emit UpdatedInterests(referer, investors[referer].balanceInterests);
investors[referee].mid.refereeBalance = investors[referee].mid.refereeBalance.add(midAmount);
investors[referee].lng.refereeBalance = investors[referee].lng.refereeBalance.add(lngAmount);
investors[referee].per.refereeBalance = investors[referee].per.refereeBalance.add(perAmount);
emit ModifiedReferee(
referee,
investors[referee].mid.refereeBalance,
investors[referee].lng.refereeBalance,
investors[referee].per.refereeBalance
);
emit Refered(referer, referee, midAmount, lngAmount, perAmount);
}
/**
* @dev Set the referee balance of an investor.
*
* @param investor The address of the investor whose balance has to be modified
* @param midAmount How many mid term bonds the referee bought through referal
* @param lngAmount How many long term bonds the referee bought through referal
* @param perAmount How many perpetual tokens the referee bought through referal
*/
function setRefereeAmount (
address investor,
uint256 midAmount,
uint256 lngAmount,
uint256 perAmount
) external onlyOwner {
investors[investor].mid.refereeBalance = midAmount;
investors[investor].lng.refereeBalance = lngAmount;
investors[investor].per.refereeBalance = perAmount;
emit ModifiedReferee(investor, midAmount, lngAmount, perAmount);
}
/**
* @dev Updates an investor's investment state. Will be called each month.
*
* @param investor The address of the investor for which to update interests
* @param midBalance Balance of mid term bond
* @param lngBalance Balance of long term bond
* @param perBalance Balance of perpetual token
*/
function updateInterests (address investor, uint256 midBalance, uint256 lngBalance, uint256 perBalance) external onlyOwner {
// Investor's balance in each bond may have changed since last month
investors[investor].mid.currentBalance = midBalance;
investors[investor].lng.currentBalance = lngBalance;
investors[investor].per.currentBalance = perBalance;
// Adjusts investor's referee balance
bool adjustedReferee = false;
if (investors[investor].mid.refereeBalance > investors[investor].mid.currentBalance) {
investors[investor].mid.refereeBalance = investors[investor].mid.currentBalance;
adjustedReferee = true;
}
if (investors[investor].lng.refereeBalance > investors[investor].lng.currentBalance) {
investors[investor].lng.refereeBalance = investors[investor].lng.currentBalance;
adjustedReferee = true;
}
if (investors[investor].per.refereeBalance > investors[investor].per.currentBalance) {
investors[investor].per.refereeBalance = investors[investor].per.currentBalance;
adjustedReferee = true;
}
if (adjustedReferee) {
emit ModifiedReferee(
investor,
investors[investor].mid.refereeBalance,
investors[investor].lng.refereeBalance,
investors[investor].per.refereeBalance
);
}
// Increment the hodling counter : we pass to the next month. The hodling (in months) has to be adjusted
// if the longterm or perpetual bonds balance has increased, for the midterm the interests are fixed so we
// can, for one, keep it simple :-).
if (investors[investor].mid.currentBalance > 0) {
investors[investor].mid.currentHolding = investors[investor].mid.currentHolding.add(DECIMALS);
}
if (investors[investor].lng.currentBalance > 0) {
if (investors[investor].lng.currentBalance > investors[investor].lng.previousBalance
&& investors[investor].lng.previousBalance > 0) {
uint256 adjustmentRate = (((investors[investor].lng.currentBalance
.sub(investors[investor].lng.previousBalance))
.mul(DECIMALS))
.div(investors[investor].lng.currentBalance));
investors[investor].lng.currentHolding = (((DECIMALS
.sub(adjustmentRate))
.mul(investors[investor].lng.previousHolding
.add(DECIMALS)))
.div(DECIMALS));
}
else {
investors[investor].lng.currentHolding = investors[investor].lng.currentHolding.add(DECIMALS);
}
}
if (investors[investor].per.currentBalance > 0) {
if (investors[investor].per.currentBalance > investors[investor].per.previousBalance
&& investors[investor].per.previousBalance > 0) {
uint256 adjustmentRate = (((investors[investor].per.currentBalance
.sub(investors[investor].per.previousBalance))
.mul(DECIMALS))
.div(investors[investor].per.currentBalance));
investors[investor].per.currentHolding = (((DECIMALS.sub(adjustmentRate))
.mul(investors[investor].per.previousHolding
.add(DECIMALS)))
.div(DECIMALS));
}
else {
investors[investor].per.currentHolding = investors[investor].per.currentHolding.add(DECIMALS);
}
}
// We emit ModifiedHoldings later
_minterest(investor);
// We pass to the next month, hence the previous month is now the current one :D
investors[investor].mid.previousHolding = investors[investor].mid.currentHolding;
investors[investor].lng.previousHolding = investors[investor].lng.currentHolding;
investors[investor].per.previousHolding = investors[investor].per.currentHolding;
// Same thing for balances
investors[investor].mid.previousBalance = investors[investor].mid.currentBalance;
investors[investor].lng.previousBalance = investors[investor].lng.currentBalance;
investors[investor].per.previousBalance = investors[investor].per.currentBalance;
emit ModifiedBalances(
investor,
investors[investor].mid.currentBalance,
investors[investor].lng.currentBalance,
investors[investor].per.currentBalance
);
// If the balance of a partition is empty, we need to reset the corresponding "holding" variable
if (investors[investor].per.currentBalance == 0) {
investors[investor].per.previousHolding = 0;
investors[investor].per.currentHolding = 0;
}
if (investors[investor].mid.currentBalance == 0) {
investors[investor].mid.previousHolding = 0;
investors[investor].mid.currentHolding = 0;
}
if (investors[investor].lng.currentBalance == 0) {
investors[investor].lng.previousHolding = 0;
investors[investor].lng.currentHolding = 0;
}
emit ModifiedHoldings(
investor,
investors[investor].mid.currentHolding,
investors[investor].lng.currentHolding,
investors[investor].per.currentHolding
);
emit UpdatedInterests(investor, investors[investor].balanceInterests);
}
/******************** MWT_interests internal functions ************************/
/**
* @dev Calculates the investor's total interests given how many tokens he holds, their type, and
* for how long he's been holding them.
* For midterm bonds tokens, the interest rate is constant. For longterm and perpetual bonds tokens
* rates are given by a table designed by the token issuer (Montessori Worldwide) which is
* translated in Solidity as a set of conditions.
*/
function _minterest (address investor) internal {
// The interests rates are multiplied by 10^4 to both use integers and have a 10^-4 percent precision
uint256 rateFactor = 10000; // 10^4
// Bonus to referee interest rates are multiplied by 100 to keep 10^-2 precision
uint256 bonusFactor = 100;
// midRate represents the interest rate of the user's midterm bonds
uint256 midRate = 575;
// lngRate represents the interest rate of the user's midterm bonds
uint256 lngRate = 0;
if (investors[investor].lng.currentBalance > 0) {
if (investors[investor].lng.currentHolding < DECIMALS.mul(12)) {
if (investors[investor].lng.currentBalance < DECIMALS.mul(800)) {
lngRate = 700;
}
else if (investors[investor].lng.currentBalance < DECIMALS.mul(2400)) {
lngRate = 730;
}
else if (investors[investor].lng.currentBalance < DECIMALS.mul(7200)) {
lngRate = 749;
}
else {
lngRate = 760;
}
}
else if (investors[investor].lng.currentHolding < DECIMALS.mul(36)) {
if (investors[investor].lng.currentBalance < DECIMALS.mul(800)) {
lngRate = 730;
}
else if (investors[investor].lng.currentBalance < DECIMALS.mul(2400)) {
lngRate = 745;
}
else if (investors[investor].lng.currentBalance < DECIMALS.mul(7200)) {
lngRate = 756;
}
else {
lngRate = 764;
}
}
else if (investors[investor].lng.currentHolding < DECIMALS.mul(72)) {
if (investors[investor].lng.currentBalance < DECIMALS.mul(800)) {
lngRate = 749;
}
else if (investors[investor].lng.currentBalance < DECIMALS.mul(2400)) {
lngRate = 757;
}
else if (investors[investor].lng.currentBalance < DECIMALS.mul(7200)) {
lngRate = 763;
}
else {
lngRate = 767;
}
}
else if (investors[investor].lng.currentHolding >= DECIMALS.mul(72)) {
if (investors[investor].lng.currentBalance < DECIMALS.mul(800)) {
lngRate = 760;
}
else if (investors[investor].lng.currentBalance < DECIMALS.mul(2400)) {
lngRate = 764;
}
else if (investors[investor].lng.currentBalance < DECIMALS.mul(7200)) {
lngRate = 767;
}
else if (investors[investor].lng.currentBalance >= DECIMALS.mul(7200)) {
lngRate = 770;
}
}
assert (lngRate != 0);
}
// perRate represents the interest rate of the user's midterm bonds
uint256 perRate = 0;
if (investors[investor].per.currentBalance > 0) {
if (investors[investor].per.currentHolding < DECIMALS.mul(12)) {
if (investors[investor].per.currentBalance < DECIMALS.mul(800)) {
perRate = 850;
}
else if (investors[investor].per.currentBalance < DECIMALS.mul(2400)) {
perRate = 888;
}
else if (investors[investor].per.currentBalance < DECIMALS.mul(7200)) {
perRate = 911;
}
else if (investors[investor].per.currentBalance >= DECIMALS.mul(7200)) {
perRate = 925;
}
}
else if (investors[investor].per.currentHolding < DECIMALS.mul(36)) {
if (investors[investor].per.currentBalance < DECIMALS.mul(800)) {
perRate = 888;
}
else if (investors[investor].per.currentBalance < DECIMALS.mul(2400)) {
perRate = 906;
}
else if (investors[investor].per.currentBalance < DECIMALS.mul(7200)) {
perRate = 919;
}
else if (investors[investor].per.currentBalance >= DECIMALS.mul(7200)) {
perRate = 930;
}
}
else if (investors[investor].per.currentHolding < DECIMALS.mul(72)) {
if (investors[investor].per.currentBalance < DECIMALS.mul(800)) {
perRate = 911;
}
else if (investors[investor].per.currentBalance < DECIMALS.mul(2400)) {
perRate = 919;
}
else if (investors[investor].per.currentBalance < DECIMALS.mul(7200)) {
perRate = 927;
}
else if (investors[investor].per.currentBalance >= DECIMALS.mul(7200)) {
perRate = 934;
}
}
else if (investors[investor].per.currentHolding >= DECIMALS.mul(72)) {
if (investors[investor].per.currentBalance < DECIMALS.mul(800)) {
perRate = 925;
}
else if (investors[investor].per.currentBalance < DECIMALS.mul(2400)) {
perRate = 930;
}
else if (investors[investor].per.currentBalance < DECIMALS.mul(7200)) {
perRate = 934;
}
else if (investors[investor].per.currentBalance >= DECIMALS.mul(7200)) {
perRate = 937;
}
}
assert (perRate != 0);
}
// The total user interests are incremented by this month's interests in each bond.
// We divide by 12 because the interest rate is calculated on a yearly basis.
// If an investor has a "referee balance" we need to apply a 5% bonus to its interests rate. In this case,
// we multiply the interests rate by 105 then divide it by 100 so it is increased by 5% without precision loss.
// In any case, we add the rate of each bond (time the investor's balance in this bond) on the interests balance.
// Midterm bond interests
if (investors[investor].mid.refereeBalance > 0) {
investors[investor].balanceInterests = investors[investor].balanceInterests.add(
((midRate.mul(105) // Rate with 5% bonus
.mul(investors[investor].mid.refereeBalance))
.div(12))
.div(rateFactor)
.div(bonusFactor)
);
investors[investor].balanceInterests = investors[investor].balanceInterests.add(
((midRate
.mul(investors[investor].mid.currentBalance.sub(investors[investor].mid.refereeBalance)))
.div(12))
.div(rateFactor)
);
} else {
investors[investor].balanceInterests = investors[investor].balanceInterests.add(
((midRate
.mul(investors[investor].mid.currentBalance))
.div(12))
.div(rateFactor)
);
}
// Longterm bond interests
if (investors[investor].lng.refereeBalance > 0) {
investors[investor].balanceInterests = investors[investor].balanceInterests.add(
((lngRate.mul(105) // Rate with 5% bonus
.mul(investors[investor].lng.refereeBalance))
.div(12))
.div(rateFactor)
.div(bonusFactor)
);
investors[investor].balanceInterests = investors[investor].balanceInterests.add(
((lngRate.mul(investors[investor].lng.currentBalance.sub(investors[investor].lng.refereeBalance)))
.div(12))
.div(rateFactor)
);
} else {
investors[investor].balanceInterests = investors[investor].balanceInterests.add(
((lngRate.mul(investors[investor].lng.currentBalance))
.div(12))
.div(rateFactor)
);
}
// Perpetual bond interests
if (investors[investor].per.refereeBalance > 0) {
investors[investor].balanceInterests = investors[investor].balanceInterests.add(
((perRate.mul(105) // Rate with 5% bonus
.mul(investors[investor].per.refereeBalance))
.div(12))
.div(rateFactor)
.div(bonusFactor)
);
investors[investor].balanceInterests = investors[investor].balanceInterests.add(
((perRate.mul(investors[investor].per.currentBalance.sub(investors[investor].per.refereeBalance)))
.div(12))
.div(rateFactor)
);
} else {
investors[investor].balanceInterests = investors[investor].balanceInterests.add(
((perRate.mul(investors[investor].per.currentBalance))
.div(12))
.div(rateFactor)
);
}
}
}
|
This functions is called after the investor expressed its desire to redeem its bonds using the above function (claimBonds). It needs to be called __before__ the third party pays the investor its bonds in fiat. claimedAmount The balance of the investor on the redeemed partition./ This function is only for midterm and longterm bonds, which have a restricted period before they can be withdrawn. We use 3 utf8 characters in each partition to identify it ("mid" for the midterm ones and "lng" for the longterm ones). If all balances of a partition type are empty, we need to reset the "holding" variable. For the midterm bonds. All partitions of this type are not empty, no need to update holding. The investor just withdrew all bonds from all partitions of this type. There is a possibility that an investor could refill the __exact same__ amount of the __same partition type__ before we update the interests, i.e. before the end of the month. Example: let's be an investor with the foolowing balances. mid_201001 = 200, mid_201801 = 200, currentBalance = mid_201001 + mid_201801 = 400 If this investor refills mid_201801 with 200, then mid_201801 = 400 = currentBalance. In that case, holding would be reseted whereas the investor still has 200 mid_201001 Since this case should be extremly rare, we do not emit an error event. This case should normally not occur. If the current holding is not up to date regarding token balances, it means that the investor refilled its balance after claiming bonds but before we update the interests. This period lasts at most one month. We reset holding and balance too (which could mess up adjustmentRate), but we emit an event. All partitions of this type are not empty, no need to update holding. Same as in the precedent branch, but with longterm bonds. See above for the details of this sneaky case..
|
function payBonds (address investor, uint256 claimedAmount) external nonReentrant {
investors[investor].claimingBonds.claiming = false;
bytes32 partition = investors[investor].claimingBonds.partitionNameInHex;
require ((partition[0] == "m" && partition[1] == "i" && partition[2] == "d")
|| (partition[0] == "l" && partition[1] == "n" && partition[2] == "g"), "A6");
uint256 midLeft = 0;
uint256 lngLeft = 0;
bool emitHoldingEvent = false;
if (partition[0] == "m" && partition[1] == "i" && partition[2] == "d") {
if (claimedAmount < investors[investor].mid.currentBalance) {
midLeft = investors[investor].mid.currentBalance.sub(claimedAmount);
investors[investor].mid.previousHolding = 0;
investors[investor].mid.currentHolding = 0;
emitHoldingEvent = true;
emit ModifiedHoldingsAndBalanceError(
investor,
investors[investor].claimingBonds.partitionNameInHex,
investors[investor].mid.currentHolding,
investors[investor].mid.currentBalance
);
investors[investor].mid.previousHolding = 0;
investors[investor].mid.currentHolding = 0;
emitHoldingEvent = true;
}
investors[investor].mid.currentBalance = midLeft;
if (claimedAmount < investors[investor].lng.currentBalance) {
lngLeft = investors[investor].lng.currentBalance.sub(claimedAmount);
investors[investor].lng.previousHolding = 0;
investors[investor].lng.currentHolding = 0;
emitHoldingEvent = true;
emit ModifiedHoldingsAndBalanceError(
investor,
investors[investor].claimingBonds.partitionNameInHex,
investors[investor].lng.currentHolding,
investors[investor].lng.currentBalance
);
investors[investor].lng.previousHolding = 0;
investors[investor].lng.currentHolding = 0;
emitHoldingEvent = true;
}
investors[investor].lng.currentBalance = lngLeft;
}
emit WillBePaidBonds(
investor,
partition,
claimedAmount
);
investors[investor].claimingBonds.currency = "";
investors[investor].claimingBonds.partitionNameInHex = "";
emit ModifiedClaimingBonds(
investor,
false,
investors[investor].claimingBonds.currency,
investors[investor].claimingBonds.partitionNameInHex
);
if (emitHoldingEvent) {
emit ModifiedHoldings(
investor,
investors[investor].mid.currentHolding,
investors[investor].lng.currentHolding,
investors[investor].per.currentHolding
);
}
emit ModifiedBalances(
investor,
investors[investor].mid.currentBalance,
investors[investor].lng.currentBalance,
investors[investor].per.currentBalance
);
}
| 5,449,914 |
pragma solidity ^0.4.13;
interface IAffiliateList {
/**
* @dev Sets the given address as an affiliate.
* If the address is not currently an affiliate, startTimestamp is required
* and endTimestamp is optional.
* If the address is already registered as an affiliate, both values are optional.
* @param startTimestamp Timestamp when the address became/becomes an affiliate.
* @param endTimestamp Timestamp when the address will no longer be an affiliate.
*/
function set(address addr, uint startTimestamp, uint endTimestamp) external;
/**
* @dev Retrieves the start and end timestamps for the given address.
* It is sufficient to check the start value to determine if the address
* is an affiliate (start will be greater than zero).
*/
function get(address addr) external view returns (uint start, uint end);
/**
* @dev Returns true if the address is, was, or will be an affiliate at the given time.
*/
function inListAsOf(address addr, uint time) external view returns (bool);
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract IInvestorList {
string public constant ROLE_REGD = "regd";
string public constant ROLE_REGCF = "regcf";
string public constant ROLE_REGS = "regs";
string public constant ROLE_UNKNOWN = "unknown";
function inList(address addr) public view returns (bool);
function addAddress(address addr, string role) public;
function getRole(address addr) public view returns (string);
function hasRole(address addr, string role) public view returns (bool);
}
contract Ownable {
address public owner;
address public 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 Starts the 2-step process of changing ownership. The new owner
* must then call `acceptOwnership()`.
*/
function changeOwner(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
/**
* @dev Completes the process of transferring ownership to a new owner.
*/
function acceptOwnership() public {
if (msg.sender == newOwner) {
owner = newOwner;
newOwner = 0;
}
}
}
contract AffiliateList is Ownable, IAffiliateList {
event AffiliateAdded(address addr, uint startTimestamp, uint endTimestamp);
event AffiliateUpdated(address addr, uint startTimestamp, uint endTimestamp);
mapping (address => uint) public affiliateStart;
mapping (address => uint) public affiliateEnd;
function set(address addr, uint startTimestamp, uint endTimestamp) public onlyOwner {
require(addr != address(0));
uint existingStart = affiliateStart[addr];
if(existingStart == 0) {
// this is a new address
require(startTimestamp != 0);
affiliateStart[addr] = startTimestamp;
if(endTimestamp != 0) {
require(endTimestamp > startTimestamp);
affiliateEnd[addr] = endTimestamp;
}
emit AffiliateAdded(addr, startTimestamp, endTimestamp);
}
else {
// this address was previously registered
if(startTimestamp == 0) {
// don't update the start timestamp
if(endTimestamp == 0) {
affiliateStart[addr] = 0;
affiliateEnd[addr] = 0;
}
else {
require(endTimestamp > existingStart);
}
}
else {
// update the start timestamp
affiliateStart[addr] = startTimestamp;
if(endTimestamp != 0) {
require(endTimestamp > startTimestamp);
}
}
affiliateEnd[addr] = endTimestamp;
emit AffiliateUpdated(addr, startTimestamp, endTimestamp);
}
}
function get(address addr) public view returns (uint start, uint end) {
return (affiliateStart[addr], affiliateEnd[addr]);
}
function inListAsOf(address addr, uint time) public view returns (bool) {
uint start;
uint end;
(start, end) = get(addr);
if(start == 0) {
return false;
}
if(time < start) {
return false;
}
if(end != 0 && time >= end) {
return false;
}
return true;
}
}
contract InvestorList is Ownable, IInvestorList {
event AddressAdded(address addr, string role);
event AddressRemoved(address addr, string role);
mapping (address => string) internal investorList;
/**
* @dev Throws if called by any account that's not investorListed.
* @param role string
*/
modifier validRole(string role) {
require(
keccak256(bytes(role)) == keccak256(bytes(ROLE_REGD)) ||
keccak256(bytes(role)) == keccak256(bytes(ROLE_REGCF)) ||
keccak256(bytes(role)) == keccak256(bytes(ROLE_REGS)) ||
keccak256(bytes(role)) == keccak256(bytes(ROLE_UNKNOWN))
);
_;
}
/**
* @dev Getter to determine if address is in investorList.
* @param addr address
* @return true if the address was added to the investorList, false if the address was already in the investorList
*/
function inList(address addr)
public
view
returns (bool)
{
if (bytes(investorList[addr]).length != 0) {
return true;
} else {
return false;
}
}
/**
* @dev Getter for address role if address is in list.
* @param addr address
* @return string for address role
*/
function getRole(address addr)
public
view
returns (string)
{
require(inList(addr));
return investorList[addr];
}
/**
* @dev Returns a boolean indicating if the given address is in the list
* with the given role.
* @param addr address to check
* @param role role to check
* @ return boolean for whether the address is in the list with the role
*/
function hasRole(address addr, string role)
public
view
returns (bool)
{
return keccak256(bytes(role)) == keccak256(bytes(investorList[addr]));
}
/**
* @dev Add single address to the investorList.
* @param addr address
* @param role string
*/
function addAddress(address addr, string role)
onlyOwner
validRole(role)
public
{
investorList[addr] = role;
emit AddressAdded(addr, role);
}
/**
* @dev Add multiple addresses to the investorList.
* @param addrs addresses
* @param role string
*/
function addAddresses(address[] addrs, string role)
onlyOwner
validRole(role)
public
{
for (uint256 i = 0; i < addrs.length; i++) {
addAddress(addrs[i], role);
}
}
/**
* @dev Remove single address from the investorList.
* @param addr address
*/
function removeAddress(address addr)
onlyOwner
public
{
// removeRole(addr, ROLE_WHITELISTED);
require(inList(addr));
string memory role = investorList[addr];
investorList[addr] = "";
emit AddressRemoved(addr, role);
}
/**
* @dev Remove multiple addresses from the investorList.
* @param addrs addresses
*/
function removeAddresses(address[] addrs)
onlyOwner
public
{
for (uint256 i = 0; i < addrs.length; i++) {
if (inList(addrs[i])) {
removeAddress(addrs[i]);
}
}
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ISecurityController {
function balanceOf(address _a) public view returns (uint);
function totalSupply() public view returns (uint);
function isTransferAuthorized(address _from, address _to) public view returns (bool);
function setTransferAuthorized(address from, address to, uint expiry) public;
function transfer(address _from, address _to, uint _value) public returns (bool success);
function transferFrom(address _spender, address _from, address _to, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint);
function approve(address _owner, address _spender, uint _value) public returns (bool success);
function increaseApproval(address _owner, address _spender, uint _addedValue) public returns (bool success);
function decreaseApproval(address _owner, address _spender, uint _subtractedValue) public returns (bool success);
function burn(address _owner, uint _amount) public;
function ledgerTransfer(address from, address to, uint val) public;
function setLedger(address _ledger) public;
function setSale(address _sale) public;
function setToken(address _token) public;
function setAffiliateList(address _affiliateList) public;
}
contract SecurityController is ISecurityController, Ownable {
ISecurityLedger public ledger;
ISecurityToken public token;
ISecuritySale public sale;
IInvestorList public investorList;
ITransferAuthorizations public transferAuthorizations;
IAffiliateList public affiliateList;
uint public lockoutPeriod = 10 * 60 * 60; // length in seconds of the lockout period
// restrict who can grant transfer authorizations
mapping(address => bool) public transferAuthPermission;
constructor() public {
}
function setTransferAuthorized(address from, address to, uint expiry) public {
// Must be called from address in the transferAuthPermission mapping
require(transferAuthPermission[msg.sender]);
// don't allow 'from' to be zero
require(from != 0);
// verify expiry is in future, but not more than 30 days
if(expiry > 0) {
require(expiry > block.timestamp);
require(expiry <= (block.timestamp + 30 days));
}
transferAuthorizations.set(from, to, expiry);
}
// functions below this line are onlyOwner
function setLockoutPeriod(uint _lockoutPeriod) public onlyOwner {
lockoutPeriod = _lockoutPeriod;
}
function setToken(address _token) public onlyOwner {
token = ISecurityToken(_token);
}
function setLedger(address _ledger) public onlyOwner {
ledger = ISecurityLedger(_ledger);
}
function setSale(address _sale) public onlyOwner {
sale = ISecuritySale(_sale);
}
function setInvestorList(address _investorList) public onlyOwner {
investorList = IInvestorList(_investorList);
}
function setTransferAuthorizations(address _transferAuthorizations) public onlyOwner {
transferAuthorizations = ITransferAuthorizations(_transferAuthorizations);
}
function setAffiliateList(address _affiliateList) public onlyOwner {
affiliateList = IAffiliateList(_affiliateList);
}
function setTransferAuthPermission(address agent, bool hasPermission) public onlyOwner {
require(agent != address(0));
transferAuthPermission[agent] = hasPermission;
}
modifier onlyToken() {
require(msg.sender == address(token));
_;
}
modifier onlyLedger() {
require(msg.sender == address(ledger));
_;
}
// public functions
function totalSupply() public view returns (uint) {
return ledger.totalSupply();
}
function balanceOf(address _a) public view returns (uint) {
return ledger.balanceOf(_a);
}
function allowance(address _owner, address _spender) public view returns (uint) {
return ledger.allowance(_owner, _spender);
}
function isTransferAuthorized(address _from, address _to) public view returns (bool) {
// A `from` address could have both an allowance for the `to` address
// and a global allowance (to the zero address). We pick the maximum
// of the two.
uint expiry = transferAuthorizations.get(_from, _to);
uint globalExpiry = transferAuthorizations.get(_from, 0);
if(globalExpiry > expiry) {
expiry = globalExpiry;
}
return expiry > block.timestamp;
}
/**
* @dev Determines whether the given transfer is possible. Returns multiple
* boolean flags specifying how the transfer must occur.
* This is kept public to provide for testing and subclasses overriding behavior.
* @param _from Address the tokens are being transferred from
* @param _to Address the tokens are being transferred to
* @param _value Number of tokens that would be transferred
* @param lockoutTime A point in time, specified in epoch time, that specifies
* the lockout period (typically 1 year before now).
* @return canTransfer Whether the transfer can occur at all.
* @return useLockoutTime Whether the lockoutTime should be used to determine which tokens to transfer.
* @return newTokensAreRestricted Whether the transferred tokens should be marked as restricted.
* @return preservePurchaseDate Whether the purchase date on the tokens should be preserved, or reset to 'now'.
*/
function checkTransfer(address _from, address _to, uint _value, uint lockoutTime)
public
returns (bool canTransfer, bool useLockoutTime, bool newTokensAreRestricted, bool preservePurchaseDate) {
// DEFAULT BEHAVIOR:
//
// If there exists a Transfer Agent authorization, allow transfer regardless
//
// All transfers from an affiliate must be authorized by Transfer Agent
// - tokens become restricted
//
// From Reg S to Reg S: allowable, regardless of holding period
//
// otherwise must meet holding period
// presently this isn't used, so always setting to false to avoid warning
preservePurchaseDate = false;
bool transferIsAuthorized = isTransferAuthorized(_from, _to);
bool fromIsAffiliate = affiliateList.inListAsOf(_from, block.timestamp);
bool toIsAffiliate = affiliateList.inListAsOf(_to, block.timestamp);
if(transferIsAuthorized) {
canTransfer = true;
if(fromIsAffiliate || toIsAffiliate) {
newTokensAreRestricted = true;
}
// useLockoutTime will remain false
// preservePurchaseDate will remain false
}
else if(!fromIsAffiliate) {
// see if both are Reg S
if(investorList.hasRole(_from, investorList.ROLE_REGS())
&& investorList.hasRole(_to, investorList.ROLE_REGS())) {
canTransfer = true;
// newTokensAreRestricted will remain false
// useLockoutTime will remain false
// preservePurchaseDate will remain false
}
else {
if(ledger.transferDryRun(_from, _to, _value, lockoutTime) == _value) {
canTransfer = true;
useLockoutTime = true;
// newTokensAreRestricted will remain false
// preservePurchaseDate will remain false
}
}
}
}
// functions below this line are onlyLedger
// let the ledger send transfer events (the most obvious case
// is when we mint directly to the ledger and need the Transfer()
// events to appear in the token)
function ledgerTransfer(address from, address to, uint val) public onlyLedger {
token.controllerTransfer(from, to, val);
}
// functions below this line are onlyToken
function transfer(address _from, address _to, uint _value) public onlyToken returns (bool success) {
//TODO: this could be configurable
uint lockoutTime = block.timestamp - lockoutPeriod;
bool canTransfer;
bool useLockoutTime;
bool newTokensAreRestricted;
bool preservePurchaseDate;
(canTransfer, useLockoutTime, newTokensAreRestricted, preservePurchaseDate)
= checkTransfer(_from, _to, _value, lockoutTime);
if(!canTransfer) {
return false;
}
uint overrideLockoutTime = lockoutTime;
if(!useLockoutTime) {
overrideLockoutTime = 0;
}
return ledger.transfer(_from, _to, _value, overrideLockoutTime, newTokensAreRestricted, preservePurchaseDate);
}
function transferFrom(address _spender, address _from, address _to, uint _value) public onlyToken returns (bool success) {
//TODO: this could be configurable
uint lockoutTime = block.timestamp - lockoutPeriod;
bool canTransfer;
bool useLockoutTime;
bool newTokensAreRestricted;
bool preservePurchaseDate;
(canTransfer, useLockoutTime, newTokensAreRestricted, preservePurchaseDate)
= checkTransfer(_from, _to, _value, lockoutTime);
if(!canTransfer) {
return false;
}
uint overrideLockoutTime = lockoutTime;
if(!useLockoutTime) {
overrideLockoutTime = 0;
}
return ledger.transferFrom(_spender, _from, _to, _value, overrideLockoutTime, newTokensAreRestricted, preservePurchaseDate);
}
function approve(address _owner, address _spender, uint _value) public onlyToken returns (bool success) {
return ledger.approve(_owner, _spender, _value);
}
function increaseApproval (address _owner, address _spender, uint _addedValue) public onlyToken returns (bool success) {
return ledger.increaseApproval(_owner, _spender, _addedValue);
}
function decreaseApproval (address _owner, address _spender, uint _subtractedValue) public onlyToken returns (bool success) {
return ledger.decreaseApproval(_owner, _spender, _subtractedValue);
}
function burn(address _owner, uint _amount) public onlyToken {
ledger.burn(_owner, _amount);
}
}
interface ISecurityLedger {
function balanceOf(address _a) external view returns (uint);
function totalSupply() external view returns (uint);
function transferDryRun(address _from, address _to, uint amount, uint lockoutTime) external returns (uint transferrableCount);
function transfer(address _from, address _to, uint _value, uint lockoutTime, bool newTokensAreRestricted, bool preservePurchaseDate) external returns (bool success);
function transferFrom(address _spender, address _from, address _to, uint _value, uint lockoutTime, bool newTokensAreRestricted, bool preservePurchaseDate) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint);
function approve(address _owner, address _spender, uint _value) external returns (bool success);
function increaseApproval(address _owner, address _spender, uint _addedValue) external returns (bool success);
function decreaseApproval(address _owner, address _spender, uint _subtractedValue) external returns (bool success);
function burn(address _owner, uint _amount) external;
function setController(address _controller) external;
}
contract SecurityLedger is Ownable {
using SafeMath for uint256;
struct TokenLot {
uint amount;
uint purchaseDate;
bool restricted;
}
mapping(address => TokenLot[]) public tokenLotsOf;
SecurityController public controller;
mapping(address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint public totalSupply;
uint public mintingNonce;
bool public mintingStopped;
constructor() public {
}
// functions below this line are onlyOwner
function setController(address _controller) public onlyOwner {
controller = SecurityController(_controller);
}
function stopMinting() public onlyOwner {
mintingStopped = true;
}
//TODO: not sure if this function should stay long term
function mint(address addr, uint value, uint timestamp) public onlyOwner {
require(!mintingStopped);
uint time = timestamp;
if(time == 0) {
time = block.timestamp;
}
balanceOf[addr] = balanceOf[addr].add(value);
tokenLotsOf[addr].push(TokenLot(value, time, true));
controller.ledgerTransfer(0, addr, value);
totalSupply = totalSupply.add(value);
}
function multiMint(uint nonce, uint256[] bits, uint timestamp) external onlyOwner {
require(!mintingStopped);
if (nonce != mintingNonce) return;
mintingNonce = mintingNonce.add(1);
uint256 lomask = (1 << 96) - 1;
uint created = 0;
uint time = timestamp;
if(time == 0) {
time = block.timestamp;
}
for (uint i = 0; i < bits.length; i++) {
address addr = address(bits[i]>>96);
uint value = bits[i] & lomask;
balanceOf[addr] = balanceOf[addr].add(value);
tokenLotsOf[addr].push(TokenLot(value, time, true));
controller.ledgerTransfer(0, addr, value);
created = created.add(value);
}
totalSupply = totalSupply.add(created);
}
// send received tokens to anyone
function sendReceivedTokens(address token, address sender, uint amount) public onlyOwner {
ERC20Basic t = ERC20Basic(token);
require(t.transfer(sender, amount));
}
// functions below this line are onlyController
modifier onlyController() {
require(msg.sender == address(controller));
_;
}
/**
* @dev Walks through the list of TokenLots for the given address, attempting to find
* `amount` tokens that can be transferred. It uses the given `lockoutTime` if
* the supplied value is not zero. If `removeTokens` is true the tokens are
* actually removed from the address, otherwise this function acts as a dry run.
* The value returned is the actual number of transferrable tokens found, up to
* the maximum value of `amount`.
*/
function walkTokenLots(address from, address to, uint amount, uint lockoutTime, bool removeTokens,
bool newTokensAreRestricted, bool preservePurchaseDate)
internal returns (uint numTransferrableTokens)
{
TokenLot[] storage fromTokenLots = tokenLotsOf[from];
for(uint i=0; i<fromTokenLots.length; i++) {
TokenLot storage lot = fromTokenLots[i];
uint lotAmount = lot.amount;
// skip if there are no available tokens
if(lotAmount == 0) {
continue;
}
if(lockoutTime > 0) {
// skip if it is more recent than the lockout period AND it's restricted
if(lot.restricted && lot.purchaseDate > lockoutTime) {
continue;
}
}
uint remaining = amount - numTransferrableTokens;
if(lotAmount >= remaining) {
numTransferrableTokens = numTransferrableTokens.add(remaining);
if(removeTokens) {
lot.amount = lotAmount.sub(remaining);
if(to != address(0)) {
if(preservePurchaseDate) {
tokenLotsOf[to].push(TokenLot(remaining, lot.purchaseDate, newTokensAreRestricted));
}
else {
tokenLotsOf[to].push(TokenLot(remaining, block.timestamp, newTokensAreRestricted));
}
}
}
break;
}
// If we're here, then amount in this lot is not yet enough.
// Take all of it.
numTransferrableTokens = numTransferrableTokens.add(lotAmount);
if(removeTokens) {
lot.amount = 0;
if(to != address(0)) {
if(preservePurchaseDate) {
tokenLotsOf[to].push(TokenLot(lotAmount, lot.purchaseDate, newTokensAreRestricted));
}
else {
tokenLotsOf[to].push(TokenLot(lotAmount, block.timestamp, newTokensAreRestricted));
}
}
}
}
}
function transferDryRun(address from, address to, uint amount, uint lockoutTime) public onlyController returns (uint) {
return walkTokenLots(from, to, amount, lockoutTime, false, false, false);
}
function transfer(address _from, address _to, uint _value, uint lockoutTime, bool newTokensAreRestricted, bool preservePurchaseDate) public onlyController returns (bool success) {
if (balanceOf[_from] < _value) return false;
// ensure number of tokens removed from TokenLots is as expected
uint tokensTransferred = walkTokenLots(_from, _to, _value, lockoutTime, true, newTokensAreRestricted, preservePurchaseDate);
require(tokensTransferred == _value);
// adjust balances
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
return true;
}
function transferFrom(address _spender, address _from, address _to, uint _value, uint lockoutTime, bool newTokensAreRestricted, bool preservePurchaseDate) public onlyController returns (bool success) {
if (balanceOf[_from] < _value) return false;
// ensure there is enough allowance
uint allowed = allowance[_from][_spender];
if (allowed < _value) return false;
// ensure number of tokens removed from TokenLots is as expected
uint tokensTransferred = walkTokenLots(_from, _to, _value, lockoutTime, true, newTokensAreRestricted, preservePurchaseDate);
require(tokensTransferred == _value);
// adjust balances
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
allowance[_from][_spender] = allowed.sub(_value);
return true;
}
function approve(address _owner, address _spender, uint _value) public onlyController returns (bool success) {
// require user to set to zero before resetting to nonzero
if ((_value != 0) && (allowance[_owner][_spender] != 0)) {
return false;
}
allowance[_owner][_spender] = _value;
return true;
}
function increaseApproval (address _owner, address _spender, uint _addedValue) public onlyController returns (bool success) {
uint oldValue = allowance[_owner][_spender];
allowance[_owner][_spender] = oldValue.add(_addedValue);
return true;
}
function decreaseApproval (address _owner, address _spender, uint _subtractedValue) public onlyController returns (bool success) {
uint oldValue = allowance[_owner][_spender];
if (_subtractedValue > oldValue) {
allowance[_owner][_spender] = 0;
} else {
allowance[_owner][_spender] = oldValue.sub(_subtractedValue);
}
return true;
}
function burn(address _owner, uint _amount) public onlyController {
require(balanceOf[_owner] >= _amount);
balanceOf[_owner] = balanceOf[_owner].sub(_amount);
// remove tokens from TokenLots
// (i.e. transfer them to 0)
walkTokenLots(_owner, address(0), _amount, 0, true, false, false);
totalSupply = totalSupply.sub(_amount);
}
}
interface ISecuritySale {
function setLive(bool newLiveness) external;
function setInvestorList(address _investorList) external;
}
contract SecuritySale is Ownable {
bool public live; // sale is live right now
IInvestorList public investorList; // approved contributors
event SaleLive(bool liveness);
event EtherIn(address from, uint amount);
event StartSale();
event EndSale();
constructor() public {
live = false;
}
function setInvestorList(address _investorList) public onlyOwner {
investorList = IInvestorList(_investorList);
}
function () public payable {
require(live);
require(investorList.inList(msg.sender));
emit EtherIn(msg.sender, msg.value);
}
// set liveness
function setLive(bool newLiveness) public onlyOwner {
if(live && !newLiveness) {
live = false;
emit EndSale();
}
else if(!live && newLiveness) {
live = true;
emit StartSale();
}
}
// withdraw all of the Ether to owner
function withdraw() public onlyOwner {
msg.sender.transfer(address(this).balance);
}
// withdraw some of the Ether to owner
function withdrawSome(uint value) public onlyOwner {
require(value <= address(this).balance);
msg.sender.transfer(value);
}
// withdraw tokens to owner
function withdrawTokens(address token) public onlyOwner {
ERC20Basic t = ERC20Basic(token);
require(t.transfer(msg.sender, t.balanceOf(this)));
}
// send received tokens to anyone
function sendReceivedTokens(address token, address sender, uint amount) public onlyOwner {
ERC20Basic t = ERC20Basic(token);
require(t.transfer(sender, amount));
}
}
interface ISecurityToken {
function balanceOf(address addr) external view returns(uint);
function transfer(address to, uint amount) external returns(bool);
function controllerTransfer(address _from, address _to, uint _value) external;
}
contract SecurityToken is Ownable{
using SafeMath for uint256;
ISecurityController public controller;
// these public fields are set once in constructor
string public name;
string public symbol;
uint8 public decimals;
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// functions below this line are onlyOwner
function setController(address _c) public onlyOwner {
controller = ISecurityController(_c);
}
// send received tokens to anyone
function sendReceivedTokens(address token, address sender, uint amount) public onlyOwner {
ERC20Basic t = ERC20Basic(token);
require(t.transfer(sender, amount));
}
// functions below this line are public
function balanceOf(address a) public view returns (uint) {
return controller.balanceOf(a);
}
function totalSupply() public view returns (uint) {
return controller.totalSupply();
}
function allowance(address _owner, address _spender) public view returns (uint) {
return controller.allowance(_owner, _spender);
}
function burn(uint _amount) public {
controller.burn(msg.sender, _amount);
emit Transfer(msg.sender, 0x0, _amount);
}
// functions below this line are onlyPayloadSize
// TODO: investigate this security optimization more
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length >= numwords.mul(32).add(4));
_;
}
function isTransferAuthorized(address _from, address _to) public onlyPayloadSize(2) view returns (bool) {
return controller.isTransferAuthorized(_from, _to);
}
function transfer(address _to, uint _value) public onlyPayloadSize(2) returns (bool success) {
if (controller.transfer(msg.sender, _to, _value)) {
emit Transfer(msg.sender, _to, _value);
return true;
}
return false;
}
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3) returns (bool success) {
if (controller.transferFrom(msg.sender, _from, _to, _value)) {
emit Transfer(_from, _to, _value);
return true;
}
return false;
}
function approve(address _spender, uint _value) onlyPayloadSize(2) public returns (bool success) {
if (controller.approve(msg.sender, _spender, _value)) {
emit Approval(msg.sender, _spender, _value);
return true;
}
return false;
}
function increaseApproval (address _spender, uint _addedValue) public onlyPayloadSize(2) returns (bool success) {
if (controller.increaseApproval(msg.sender, _spender, _addedValue)) {
uint newval = controller.allowance(msg.sender, _spender);
emit Approval(msg.sender, _spender, newval);
return true;
}
return false;
}
function decreaseApproval (address _spender, uint _subtractedValue) public onlyPayloadSize(2) returns (bool success) {
if (controller.decreaseApproval(msg.sender, _spender, _subtractedValue)) {
uint newval = controller.allowance(msg.sender, _spender);
emit Approval(msg.sender, _spender, newval);
return true;
}
return false;
}
// functions below this line are onlyController
modifier onlyController() {
assert(msg.sender == address(controller));
_;
}
function controllerTransfer(address _from, address _to, uint _value) public onlyController {
emit Transfer(_from, _to, _value);
}
function controllerApprove(address _owner, address _spender, uint _value) public onlyController {
emit Approval(_owner, _spender, _value);
}
}
interface ITransferAuthorizations {
function setController(address _controller) external;
function get(address from, address to) external view returns (uint);
function set(address from, address to, uint expiry) external;
}
contract TransferAuthorizations is Ownable, ITransferAuthorizations {
/**
* @dev The first key is the `from` address. The second key is the `to` address.
* The uint value of the mapping is the epoch time (seconds since 1/1/1970)
* of the expiration of the approved transfer.
*/
mapping(address => mapping(address => uint)) public authorizations;
/**
* @dev This controller is the only contract allowed to call the `set` function.
*/
address public controller;
event TransferAuthorizationSet(address from, address to, uint expiry);
function setController(address _controller) public onlyOwner {
controller = _controller;
}
modifier onlyController() {
assert(msg.sender == controller);
_;
}
/**
* @dev Sets the authorization for a transfer to occur between the 'from' and
* 'to' addresses, to expire at the 'expiry' time.
* @param from The address from which funds would be transferred.
* @param to The address to which funds would be transferred. This can be
* the zero address to allow transfers to any address.
* @param expiry The epoch time (seconds since 1/1/1970) at which point this
* authorization will no longer be valid.
*/
function set(address from, address to, uint expiry) public onlyController {
require(from != 0);
authorizations[from][to] = expiry;
emit TransferAuthorizationSet(from, to, expiry);
}
/**
* @dev Returns the expiration time for the transfer authorization between the
* given addresses. Returns 0 if not allowed.
* @param from The address from which funds would be transferred.
* @param to The address to which funds would be transferred. This can be
* the zero address to allow transfers to any address.
*/
function get(address from, address to) public view returns (uint) {
return authorizations[from][to];
}
}
|
Walks through the list of TokenLots for the given address, attempting to find `amount` tokens that can be transferred. It uses the given `lockoutTime` if the supplied value is not zero. If `removeTokens` is true the tokens are actually removed from the address, otherwise this function acts as a dry run. The value returned is the actual number of transferrable tokens found, up to the maximum value of `amount`./ skip if there are no available tokens skip if it is more recent than the lockout period AND it's restricted
|
function walkTokenLots(address from, address to, uint amount, uint lockoutTime, bool removeTokens,
bool newTokensAreRestricted, bool preservePurchaseDate)
internal returns (uint numTransferrableTokens)
{
TokenLot[] storage fromTokenLots = tokenLotsOf[from];
for(uint i=0; i<fromTokenLots.length; i++) {
TokenLot storage lot = fromTokenLots[i];
uint lotAmount = lot.amount;
if(lotAmount == 0) {
continue;
}
if(lockoutTime > 0) {
if(lot.restricted && lot.purchaseDate > lockoutTime) {
continue;
}
}
uint remaining = amount - numTransferrableTokens;
if(lotAmount >= remaining) {
numTransferrableTokens = numTransferrableTokens.add(remaining);
if(removeTokens) {
lot.amount = lotAmount.sub(remaining);
if(to != address(0)) {
if(preservePurchaseDate) {
tokenLotsOf[to].push(TokenLot(remaining, lot.purchaseDate, newTokensAreRestricted));
}
else {
tokenLotsOf[to].push(TokenLot(remaining, block.timestamp, newTokensAreRestricted));
}
}
}
break;
}
if(removeTokens) {
lot.amount = 0;
if(to != address(0)) {
if(preservePurchaseDate) {
tokenLotsOf[to].push(TokenLot(lotAmount, lot.purchaseDate, newTokensAreRestricted));
}
else {
tokenLotsOf[to].push(TokenLot(lotAmount, block.timestamp, newTokensAreRestricted));
}
}
}
}
}
| 10,472,433 |
./full_match/42/0xCB75bC96a0005568F256ffa7D337753C32bF2D9d/sources/hw.sol
|
IUniswapV3SwapCallback4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair2).swap(0,uint(amount1Delta),msg.sender,new bytes(0)); IUniswapV2Pair(pair2).swap(uint(amount0Delta),0,msg.sender,new bytes(0)); IUniswapV2Pair(pair2).swap(0,uint(amount1Delta)+amount2,address(this),new bytes(0)); IUniswapV2Pair(pair2).swap(uint(amount0Delta)+amount2,0,address(this),new bytes(0));4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair2).swap(0,amount3,pair3,new bytes(0)); IUniswapV2Pair(pair2).swap(amount3,0,pair3,new bytes(0)); IUniswapV2Pair(pair3).swap(0,v3In,msg.sender,new bytes(0)); IUniswapV2Pair(pair3).swap(v3In,0,msg.sender,new bytes(0)); IUniswapV3Pool(pair2).swap(msg.sender, zeroForOne2, -int256(amount0Delta), zeroForOne2?MIN_SQRT_RATIO__ : MAX_SQRT_RATIO__, data ); IUniswapV3Pool(pair2).swap(msg.sender, zeroForOne2, -int256(amount1Delta), zeroForOne2?MIN_SQRT_RATIO__ : MAX_SQRT_RATIO__, data );4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair3).swap(0,v3In,msg.sender,new bytes(0)); IUniswapV2Pair(pair3).swap(v3In,0,msg.sender,new bytes(0));4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair3).swap(0,v3In,msg.sender,new bytes(0)); IUniswapV2Pair(pair3).swap(v3In,0,msg.sender,new bytes(0));4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair2).swap(0,amount2,address(this),new bytes(0)); IUniswapV2Pair(pair2).swap(amount2,0,address(this),new bytes(0)); IUniswapV3Pool(pair3).swap(msg.sender, zeroForOne3, -amount0Delta, zeroForOne3?MIN_SQRT_RATIO__ : MAX_SQRT_RATIO__, data ); IUniswapV3Pool(pair3).swap(msg.sender, zeroForOne3, -amount1Delta, zeroForOne3?MIN_SQRT_RATIO__ : MAX_SQRT_RATIO__, data );4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair2).swap(0,amount2,address(this),new bytes(0)); IUniswapV2Pair(pair2).swap(amount2,0,address(this),new bytes(0)); IUniswapV2Pair(pair3).swap(0,v3In,msg.sender,new bytes(0)); IUniswapV2Pair(pair3).swap(v3In,0,msg.sender,new bytes(0));4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw IUniswapV2Pair(pair2).swap(0,amount2,pair3,new bytes(0)); IUniswapV2Pair(pair2).swap(amount2,0,pair3,new bytes(0)); IUniswapV2Pair(pair3).swap(0,amount3,address(this),new bytes(0)); IUniswapV2Pair(pair3).swap(amount3,0,address(this),new bytes(0));4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw uint v3Out; if(amount0Delta>0){ v3Out=uint(-amount1Delta); } else{ v3Out=uint(-amount0Delta); }4bytes selector 32bytes amount0 32bytes amount1 32bytes offset 32bytes length data_raw
|
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata _data
) external override {
if( tx.origin != owner)
{
revert("");
}
assembly {
let calldata32bytes := calldataload(132)
pair2 := shr(96,calldata32bytes)
amount2:= and(shr(8,calldata32bytes),0xffffffffffffffffffffff)
type2:=and(calldata32bytes,0x0f)
zeroForOne2:=and(calldata32bytes,0xf0)
}
if(type2==0){
if (zeroForOne2){
wethTransfer(pair2,uint256(-amount0Delta)-amount2);
V2Swap(pair2,0,uint(amount1Delta),msg.sender);
}
else{
wethTransfer(pair2,uint256(-amount1Delta)-amount2);
V2Swap(pair2,uint(amount0Delta),0,msg.sender);
}
}
else if(type2==1) {
if (zeroForOne2){
V2Swap(pair2,0,uint(amount1Delta)+amount2,address(this));
wethTransfer(msg.sender,uint(amount1Delta));
}
else{
V2Swap(pair2,uint(amount0Delta)+amount2,0,address(this));
wethTransfer(msg.sender,uint(amount0Delta));
}
}
else if(type2==2) {
bytes memory data = new bytes(32);
assembly{
let calldata32bytes := calldataload(132)
mstore(add(data, 32), add(shl(4,shr(4,calldata32bytes)),0x03))
}
int v3In;
if(amount0Delta>0){
v3In=-amount0Delta;
}
else{
v3In=-amount1Delta;
}
V3Swap(pair2,msg.sender,zeroForOne2,v3In,data);
}
else if(type2==3) {
wethTransfer(msg.sender,amount2);
}
else if(type2==4) {
assembly {
let calldata32bytes := calldataload(164)
pair3 := shr(96,calldata32bytes)
amount3:= and(shr(8,calldata32bytes),0xffffffffffffffffffffff)
zeroForOne3:=and(calldata32bytes,0xf0)
}
uint v3In;
if(amount0Delta>0){
v3In=uint(amount0Delta);
}
else{
v3In=uint(amount1Delta);
}
wethTransfer(pair2,amount2);
if(zeroForOne2){
V2Swap(pair2,0,amount3,pair3);
}
else{
V2Swap(pair2,amount3,0,pair3);
}
if(zeroForOne3){
V2Swap(pair3,0,v3In,msg.sender);
}
else{
V2Swap(pair3,v3In,0,msg.sender);
}
}
else if(type2==5) {
bytes memory data = new bytes(64);
assembly {
let third32bytes := calldataload(132)
let fourth32bytes := calldataload(164)
mstore(add(data, 32), add(shl(4,shr(4,third32bytes)),0x06))
mstore(add(data, 64), fourth32bytes)
}
if(amount0Delta>0){
V3Swap(pair2,msg.sender,zeroForOne2,-int256(amount0Delta),data);
}
else{
V3Swap(pair2,msg.sender,zeroForOne2,-int256(amount1Delta),data);
}
}
else if(type2==6) {
assembly {
let calldata32bytes := calldataload(164)
pair3 := shr(96,calldata32bytes)
amount3:= and(shr(8,calldata32bytes),0xffffffffffffffffffffff)
zeroForOne3:=and(calldata32bytes,0xf0)
}
wethTransfer(pair3,amount3);
uint v3In;
if(amount0Delta>0){
v3In=uint(amount0Delta);
}
else{
v3In=uint(amount1Delta);
}
if(zeroForOne3){
V2Swap(pair3,0,v3In,msg.sender);
}
else{
V2Swap(pair3,v3In,0,msg.sender);
}
}
else if(type2==7) {
bytes memory data = new bytes(32);
assembly {
let third32bytes := calldataload(132)
mstore(add(data, 32), add(shl(4,shr(4,third32bytes)),0x03))
let fourth32bytes := calldataload(164)
pair3 := shr(96,fourth32bytes)
zeroForOne3:=and(fourth32bytes,0xf0)
}
V3Swap(pair2,pair3,zeroForOne2,int256(amount2),data);
uint v3In;
if(amount0Delta>0){
v3In=uint(amount0Delta);
}
else{
v3In=uint(amount1Delta);
}
if(zeroForOne3){
V2Swap(pair3,0,v3In,msg.sender);
}
else{
V2Swap(pair3,v3In,0,msg.sender);
}
}
else if(type2==8) {
bytes memory data = new bytes(32);
assembly {
let third32bytes := calldataload(132)
let fourth32bytes := calldataload(164)
mstore(add(data, 32), add(shl(4,shr(4,fourth32bytes)),0x03))
pair3 := shr(96,fourth32bytes)
zeroForOne3:=and(fourth32bytes,0xf0)
}
if(zeroForOne2){
V2Swap(pair2,0,amount2,address(this));
}
else{
V2Swap(pair2,amount2,0,address(this));
}
if(amount0Delta>0){
V3Swap(pair3,msg.sender,zeroForOne3,-amount0Delta,data);
}
else{
V3Swap(pair3,msg.sender,zeroForOne3,-amount1Delta,data);
}
}
else if(type2==9) {
assembly {
let third32bytes := calldataload(132)
let fourth32bytes := calldataload(164)
amount3:= and(shr(8,fourth32bytes),0xffffffffffffffffffffff)
pair3 := shr(96,fourth32bytes)
zeroForOne3:=and(fourth32bytes,0xf0)
}
if(zeroForOne2){
V2Swap(pair2,0,amount2,address(this));
}
else{
V2Swap(pair2,amount2,0,address(this));
}
wethTransfer(pair3,amount3);
uint v3In;
if(amount0Delta>0){
v3In=uint(amount0Delta);
}
else{
v3In=uint(amount1Delta);
}
if(zeroForOne3){
V2Swap(pair3,0,v3In,msg.sender);
}
else{
V2Swap(pair3,v3In,0,msg.sender);
}
}
else if(type2==10) {
assembly {
let fourth32bytes := calldataload(164)
amount3:= and(shr(8,fourth32bytes),0xffffffffffffffffffffff)
pair3 := shr(96,fourth32bytes)
zeroForOne3:=and(fourth32bytes,0xf0)
}
if(zeroForOne2){
V2Swap(pair2,0,amount2,pair3);
}
else{
V2Swap(pair2,amount2,0,pair3);
}
if(zeroForOne3){
V2Swap(pair3,0,amount3,address(this));
}
else{
V2Swap(pair3,amount3,0,address(this));
}
uint v3In;
if(amount0Delta>0){
v3In=uint(amount0Delta);
}
else{
v3In=uint(amount1Delta);
}
wethTransfer(msg.sender,v3In);
}
else if(type2==11) {
bytes memory data = new bytes(32);
assembly {
let fourth32bytes := calldataload(164)
mstore(add(data, 32), add(shl(4,shr(4,fourth32bytes)),0x02))
}
int v3In;
if(amount0Delta>0){
v3In=-amount0Delta;
}
else{
v3In=-amount1Delta;
}
V3Swap(pair2,msg.sender,zeroForOne2,v3In,data);
}
else if(type2==12) {
address tokenIn;
address tokenOut;
uint8 type3;
assembly {
let fourth32bytes := calldataload(164)
let fifth32bytes := calldataload(196)
tokenIn:=shr(96,fourth32bytes)
tokenOut:=shr(96,fifth32bytes)
type3:=and(fourth32bytes,0x0f)
}
if(type3==0){
uint balIn;
if(amount0Delta>0){
balIn=uint(-amount1Delta);
}
else{
balIn=uint(-amount0Delta);
}
uint out =BalSwap(pair2,tokenIn,tokenOut,balIn,zeroForOne2);
wethTransfer(msg.sender,out-amount2);
}
else if(type3==1){
uint out=BalSwap(pair2,tokenIn,tokenOut,amount2,zeroForOne2);
erc20Transfer(tokenOut,msg.sender,out);
}
else{
revert("");
}
}
else if(type2==13) {
uint8 type3;
address tokenIn;
address tokenOut;
assembly {
let fourth32bytes := calldataload(164)
amount3:= and(shr(8,fourth32bytes),0xffffffffffffffffffffff)
pair3 := shr(96,fourth32bytes)
zeroForOne3:=and(fourth32bytes,0xf0)
type3:=and(fourth32bytes,0x0f)
let fifth32bytes := calldataload(196)
let sixth32bytes := calldataload(228)
tokenIn:=shr(96,fifth32bytes)
tokenOut:=shr(96,sixth32bytes)
}
if(type3==0){
wethTransfer(pair2,amount2);
require(1==2,'ss');
if(zeroForOne2){
V2Swap(pair2,0,amount3,address(this));
}
else{
V2Swap(pair2,amount3,0,address(this));
}
uint out =BalSwap(pair3,tokenIn,tokenOut,amount3,zeroForOne3);
erc20Transfer(tokenOut,msg.sender,out);
}
}
else{
revert("");
}
}
| 16,254,093 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./Ownable.sol";
/**
* @notice
* A stake struct is used to represent the way we store stakes,
* A Stake will contain the users address, the duration (0 for imediate withdrawal or 1 / 2 / 3 years), the amount staked and a timestamp,
* Since which is when the stake was made
* _stakeCheckPointIndex: The index in the checkpoints array of the current stake
*/
struct Stake {
uint256 _amount;
uint256 _since;
IERC20 _stakingToken;
uint256 _stakaAmount;
uint256 _estimatedReward;
APY _estimatedAPY;
uint256 _rewardStartDate; //This date will change as the amount staked increases
bool _exists;
}
/***@notice Struct to store Staking Contract Parameters */
struct StakingContractParameters {
uint256 _minimumStake;
uint256 _maxSupply;
uint256 _totalReward;
IERC20 _stakingToken;
uint256 _stakingDuration;
uint256 _maximumStake;
//staking starting parameters
uint256 _minimumNumberStakeHoldersBeforeStart;
uint256 _minimumTotalStakeBeforeStart;
uint256 _startDate;
uint256 _endDate;
//vesting parameters
Percentage _immediateRewardPercentage;
uint256 _cliffDuration;
Percentage _cliffRewardPercentage;
uint256 _linearDuration;
}
struct Percentage {
uint256 _percentage;
uint256 _percentageBase;
}
struct StakingContractParametersUpdate {
uint256 _minimumStake;
uint256 _maxSupply;
uint256 _totalReward;
IERC20 _stakingToken;
uint256 _stakingDuration;
uint256 _maximumStake;
uint256 _minimumNumberStakeHoldersBeforeStart;
uint256 _minimumTotalStakeBeforeStart;
Percentage _immediateRewardPercentage;
uint256 _cliffDuration;
Percentage _cliffRewardPercentage;
uint256 _linearDuration;
}
struct APY {
uint256 _apy;
uint256 _base;
}
/**
* @dev Implementation of the {IERC20} interface.
*
*/
contract KatanaInuStakingContract is
ERC20("STAKA Token", "STAKA"),
Ownable,
Pausable
{
using SafeMath for uint256;
///////////// Events ///////////////////
/**
* @dev Emitted when a user stakes tokens
*/
event Staked(
address indexed stakeholder,
uint256 amountStaked,
IERC20 stakingToken,
uint256 xKataAmount
);
/**
* @dev Emitted when a user withdraw stake
*/
event Withdrawn(
address indexed stakeholder,
uint256 amountStaked,
uint256 amountReceived,
IERC20 stakingToken
);
/**
* @dev Emitted when a user withdraw stake
*/
event EmergencyWithdraw(
address indexed stakeholder,
uint256 amountSKataBurned,
uint256 amountReceived
);
///////////////////////////////////////
///// Fields //////////
/*** @notice Stakes by stakeholder address */
mapping(address => Stake) public _stakeholdersMapping;
uint256 _currentNumberOfStakeholders;
/*** @notice Staking contract parameters */
StakingContractParameters private _stakingParameters;
/***@notice Total Kata Staked */
uint256 private _totalKataStaked;
/***@notice Total Kata rewards claimed */
uint256 private _totalKataRewardsClaimed;
bool private _stakingStarted;
////////////////////////////////////////
constructor(address stakingTokenAddress) {
_stakingParameters._stakingToken = IERC20(stakingTokenAddress);
_stakingParameters._minimumNumberStakeHoldersBeforeStart = 1;
}
/***@notice Update Staking Parameters: _startDate can't be updated, it is automatically set when the first stake is created */
function updateStakingParameters(
StakingContractParametersUpdate calldata stakingParameters
) external onlyOwner {
_stakingParameters._minimumStake = stakingParameters._minimumStake;
_stakingParameters._maxSupply = stakingParameters._maxSupply;
_stakingParameters._totalReward = stakingParameters._totalReward;
_stakingParameters._stakingToken = IERC20(
stakingParameters._stakingToken
);
_stakingParameters._stakingDuration = stakingParameters
._stakingDuration;
if (_stakingStarted) {
_stakingParameters._endDate =
_stakingParameters._startDate +
_stakingParameters._stakingDuration;
}
if (!_stakingStarted) {
// No need to update these paraeter if the staking has already started
_stakingParameters
._minimumNumberStakeHoldersBeforeStart = stakingParameters
._minimumNumberStakeHoldersBeforeStart;
_stakingParameters._minimumTotalStakeBeforeStart = stakingParameters
._minimumTotalStakeBeforeStart;
if (
(_stakingParameters._minimumTotalStakeBeforeStart == 0 ||
_totalKataStaked >=
_stakingParameters._minimumTotalStakeBeforeStart) &&
(_stakingParameters._minimumNumberStakeHoldersBeforeStart ==
0 ||
_currentNumberOfStakeholders >=
_stakingParameters._minimumNumberStakeHoldersBeforeStart)
) {
_stakingStarted = true;
_stakingParameters._startDate = block.timestamp;
_stakingParameters._endDate =
_stakingParameters._startDate +
_stakingParameters._stakingDuration;
}
}
_stakingParameters._maximumStake = stakingParameters._maximumStake;
//Update reward schedule array
_stakingParameters._immediateRewardPercentage = stakingParameters
._immediateRewardPercentage;
_stakingParameters._cliffDuration = stakingParameters._cliffDuration;
_stakingParameters._cliffRewardPercentage = stakingParameters
._cliffRewardPercentage;
_stakingParameters._linearDuration = stakingParameters._linearDuration;
}
/***@notice Stake Kata coins in exchange for xKata coins to earn a share of the rewards */
function stake(uint256 amount) external onlyUser whenNotPaused {
//Check the amount is >= _minimumStake
require(
amount >= _stakingParameters._minimumStake,
"Amount below the minimum stake"
);
//Check the amount is <= _maximumStake
require(
_stakingParameters._maximumStake == 0 ||
amount <= _stakingParameters._maximumStake,
"amount exceeds maximum stake"
);
//Check if the new stake will exceed the maximum supply for this pool
require(
(_totalKataStaked + amount) <= _stakingParameters._maxSupply,
"You can not exceeed maximum supply for staking"
);
require(
!_stakingStarted || block.timestamp < _stakingParameters._endDate,
"The staking period has ended"
);
//Check if the totalReward have been already claimed, in theory this should always be true,
//but added the extra check for additional safety
require(
_totalKataRewardsClaimed < _stakingParameters._totalReward,
"All rewards have been distributed"
);
Stake memory newStake = createStake(amount);
_totalKataStaked += amount;
if (!_stakeholdersMapping[msg.sender]._exists) {
_currentNumberOfStakeholders += 1;
}
//Check if the staking period did not end
if (
!_stakingStarted &&
(_stakingParameters._minimumTotalStakeBeforeStart == 0 ||
_totalKataStaked >=
_stakingParameters._minimumTotalStakeBeforeStart) &&
(_stakingParameters._minimumNumberStakeHoldersBeforeStart == 0 ||
_currentNumberOfStakeholders >=
_stakingParameters._minimumNumberStakeHoldersBeforeStart)
) {
_stakingStarted = true;
_stakingParameters._startDate = block.timestamp;
_stakingParameters._endDate =
_stakingParameters._startDate +
_stakingParameters._stakingDuration;
}
//Transfer amount to contract (this)
if (
!_stakingParameters._stakingToken.transferFrom(
msg.sender,
address(this),
amount
)
) {
revert("couldn 't transfer tokens from sender to contract");
}
_mint(msg.sender, newStake._stakaAmount);
//Update stakeholders
if (!_stakeholdersMapping[msg.sender]._exists) {
_stakeholdersMapping[msg.sender] = newStake;
_stakeholdersMapping[msg.sender]._exists = true;
} else {
_stakeholdersMapping[msg.sender]
._rewardStartDate = calculateNewRewardStartDate(
_stakeholdersMapping[msg.sender],
newStake
);
_stakeholdersMapping[msg.sender]._amount += newStake._amount;
_stakeholdersMapping[msg.sender]._stakaAmount += newStake
._stakaAmount;
}
//Emit event
emit Staked(
msg.sender,
amount,
_stakingParameters._stakingToken,
newStake._stakaAmount
);
}
function calculateNewRewardStartDate(
Stake memory existingStake,
Stake memory newStake
) private pure returns (uint256) {
uint256 multiplier = (
existingStake._rewardStartDate.mul(existingStake._stakaAmount)
).add(newStake._rewardStartDate.mul(newStake._stakaAmount));
uint256 divider = existingStake._stakaAmount.add(newStake._stakaAmount);
return multiplier.div(divider);
}
/*** @notice Withdraw stake and get initial amount staked + share of the reward */
function withdrawStake(uint256 amount) external onlyUser whenNotPaused {
require(
_stakeholdersMapping[msg.sender]._exists,
"Can not find stake for sender"
);
require(
_stakeholdersMapping[msg.sender]._amount >= amount,
"Can not withdraw more than actual stake"
);
Stake memory stakeToWithdraw = _stakeholdersMapping[msg.sender];
require(stakeToWithdraw._amount > 0, "Stake alreday withdrawn");
//Reward proportional to amount withdrawn
uint256 reward = (
computeRewardForStake(block.timestamp, stakeToWithdraw, true).mul(
amount
)
).div(stakeToWithdraw._amount);
//Check if there is enough reward tokens, this is to avoid paying rewards with other stakeholders stake
uint256 currentRewardBalance = getRewardBalance();
require(
reward <= currentRewardBalance,
"The contract does not have enough reward tokens"
);
uint256 totalAmoutToWithdraw = reward + amount;
//Calculate nb STAKA to burn:
uint256 nbStakaToBurn = (stakeToWithdraw._stakaAmount.mul(amount)).div(
stakeToWithdraw._amount
);
_stakeholdersMapping[msg.sender]._amount -= amount;
_stakeholdersMapping[msg.sender]._stakaAmount -= nbStakaToBurn;
_totalKataStaked = _totalKataStaked - amount;
_totalKataRewardsClaimed += reward;
//Transfer amount to contract (this)
if (
!stakeToWithdraw._stakingToken.transfer(
msg.sender,
totalAmoutToWithdraw
)
) {
revert("couldn 't transfer tokens from sender to contract");
}
_burn(msg.sender, nbStakaToBurn);
emit Withdrawn(
msg.sender,
stakeToWithdraw._amount,
totalAmoutToWithdraw,
stakeToWithdraw._stakingToken
);
}
/***@notice withdraw all stakes of a given user without including rewards */
function emergencyWithdraw(address stakeHolderAddress) external onlyOwner {
require(
_stakeholdersMapping[stakeHolderAddress]._exists,
"Can not find stake for sender"
);
require(
_stakeholdersMapping[stakeHolderAddress]._amount > 0,
"Can not any stake for supplied address"
);
uint256 totalAmoutTowithdraw;
uint256 totalSKataToBurn;
totalAmoutTowithdraw = _stakeholdersMapping[stakeHolderAddress]._amount;
totalSKataToBurn = _stakeholdersMapping[stakeHolderAddress]
._stakaAmount;
if (
!_stakeholdersMapping[stakeHolderAddress]._stakingToken.transfer(
stakeHolderAddress,
_stakeholdersMapping[stakeHolderAddress]._amount
)
) {
revert("couldn 't transfer tokens from sender to contract");
}
_stakeholdersMapping[stakeHolderAddress]._amount = 0;
_stakeholdersMapping[stakeHolderAddress]._exists = false;
_stakeholdersMapping[stakeHolderAddress]._stakaAmount = 0;
_totalKataStaked = _totalKataStaked - totalAmoutTowithdraw;
_burn(stakeHolderAddress, totalSKataToBurn);
emit EmergencyWithdraw(
stakeHolderAddress,
totalSKataToBurn,
totalAmoutTowithdraw
);
}
/***@notice Get an estimate of the reward */
function getStakeReward(uint256 targetTime)
external
view
onlyUser
returns (uint256)
{
require(
_stakeholdersMapping[msg.sender]._exists,
"Can not find stake for sender"
);
Stake memory targetStake = _stakeholdersMapping[msg.sender];
return computeRewardForStake(targetTime, targetStake, true);
}
/***@notice Get an estimate of the reward */
function getEstimationOfReward(uint256 targetTime, uint256 amountToStake)
external
view
returns (uint256)
{
Stake memory targetStake = createStake(amountToStake);
return computeRewardForStake(targetTime, targetStake, false);
}
function getAPY() external view returns (APY memory) {
if (
!_stakingStarted ||
_stakingParameters._endDate == _stakingParameters._startDate ||
_totalKataStaked == 0
) return APY(0, 1);
uint256 targetTime = 365 days;
if (
_stakingParameters._immediateRewardPercentage._percentage == 0 &&
_stakingParameters._cliffRewardPercentage._percentage == 0 &&
_stakingParameters._cliffDuration == 0 &&
_stakingParameters._linearDuration == 0
) {
uint256 reward = _stakingParameters
._totalReward
.mul(targetTime)
.div(
_stakingParameters._endDate.sub(
_stakingParameters._startDate
)
);
return APY(reward.mul(100000).div(_totalKataStaked), 100000);
}
return getAPYWithVesting();
}
function getAPYWithVesting() private view returns (APY memory) {
uint256 targetTime = 365 days;
Stake memory syntheticStake = Stake(
_totalKataStaked,
block.timestamp,
_stakingParameters._stakingToken,
totalSupply(),
0,
APY(0, 1),
block.timestamp,
true
);
uint256 reward = computeRewardForStakeWithVesting(
block.timestamp + targetTime,
syntheticStake,
true
);
return APY(reward.mul(100000).div(_totalKataStaked), 100000);
}
/***@notice Create a new stake by taking into account accrued rewards when estimating the number of xKata tokens in exchange for Kata tokens */
function createStake(uint256 amount) private view returns (Stake memory) {
uint256 xKataAmountToMint;
uint256 currentTimeStanp = block.timestamp;
if (_totalKataStaked == 0 || totalSupply() == 0) {
xKataAmountToMint = amount;
} else {
//Add multiplication by 1 + time to maturity ratio
uint256 multiplier = amount
.mul(
_stakingParameters._endDate.sub(
_stakingParameters._startDate
)
)
.div(
_stakingParameters._endDate.add(currentTimeStanp).sub(
2 * _stakingParameters._startDate
)
);
xKataAmountToMint = multiplier.mul(totalSupply()).div(
_totalKataStaked
);
}
return
Stake(
amount,
currentTimeStanp,
_stakingParameters._stakingToken,
xKataAmountToMint,
0,
APY(0, 1),
currentTimeStanp,
true
);
}
/*** Stats functions */
/***@notice returns the amount of Kata tokens available for rewards */
function getRewardBalance() public view returns (uint256) {
uint256 stakingTokenBalance = _stakingParameters
._stakingToken
.balanceOf(address(this));
uint256 rewardBalance = stakingTokenBalance.sub(_totalKataStaked);
return rewardBalance;
}
/***@notice returns the amount of Kata tokens withdrawn as rewards */
function getTotalRewardsClaimed() public view returns (uint256) {
return _totalKataRewardsClaimed;
}
function getRequiredRewardAmountForPerdiod(uint256 endPeriod)
external
view
onlyOwner
returns (uint256)
{
return caluclateRequiredRewardAmountForPerdiod(endPeriod);
}
function getRequiredRewardAmount() external view returns (uint256) {
return caluclateRequiredRewardAmountForPerdiod(block.timestamp);
}
///////////////////////////////////////////////////////////////
function caluclateRequiredRewardAmountForPerdiod(uint256 endPeriod)
private
view
returns (uint256)
{
if (
!_stakingStarted ||
_stakingParameters._endDate == _stakingParameters._startDate ||
_totalKataStaked == 0
) return 0;
uint256 requiredReward = _stakingParameters
._totalReward
.mul(endPeriod.sub(_stakingParameters._startDate))
.div(_stakingParameters._endDate.sub(_stakingParameters._startDate))
.sub(_totalKataRewardsClaimed);
return requiredReward;
}
/***@notice Calculate the reward for a give stake if withdrawn at 'targetTime' */
function computeRewardForStake(
uint256 targetTime,
Stake memory targetStake,
bool existingStake
) private view returns (uint256) {
if (
_stakingParameters._immediateRewardPercentage._percentage == 0 &&
_stakingParameters._cliffRewardPercentage._percentage == 0 &&
_stakingParameters._cliffDuration == 0 &&
_stakingParameters._linearDuration == 0
) {
return
computeReward(
_stakingParameters._totalReward,
targetTime,
targetStake._stakaAmount,
targetStake._rewardStartDate,
existingStake
);
}
return
computeRewardForStakeWithVesting(
targetTime,
targetStake,
existingStake
);
}
function computeRewardForStakeWithVesting(
uint256 targetTime,
Stake memory targetStake,
bool existingStake
) private view returns (uint256) {
uint256 accumulatedReward;
uint256 currentStartTime = targetStake._rewardStartDate;
uint256 currentTotalRewardAmount = (
_stakingParameters._totalReward.mul(
_stakingParameters._immediateRewardPercentage._percentage
)
).div(_stakingParameters._immediateRewardPercentage._percentageBase);
if (
(currentStartTime + _stakingParameters._cliffDuration) >= targetTime
) {
return
computeReward(
currentTotalRewardAmount,
targetTime,
targetStake._stakaAmount,
currentStartTime,
existingStake
);
}
accumulatedReward += computeReward(
currentTotalRewardAmount,
currentStartTime + _stakingParameters._cliffDuration,
targetStake._stakaAmount,
currentStartTime,
existingStake
);
currentStartTime = currentStartTime + _stakingParameters._cliffDuration;
currentTotalRewardAmount += (
_stakingParameters._totalReward.mul(
_stakingParameters._cliffRewardPercentage._percentage
)
).div(_stakingParameters._cliffRewardPercentage._percentageBase);
if (
_stakingParameters._linearDuration == 0 ||
(currentStartTime + _stakingParameters._linearDuration) <=
targetTime
) {
// 100% percent of the reward vested
currentTotalRewardAmount = _stakingParameters._totalReward;
return (
accumulatedReward.add(
computeReward(
currentTotalRewardAmount,
targetTime,
targetStake._stakaAmount,
currentStartTime,
existingStake
)
)
);
}
// immediate + cliff + linear proportion of the reward
currentTotalRewardAmount += (
_stakingParameters._totalReward.sub(currentTotalRewardAmount)
).mul(targetTime - currentStartTime).div(
_stakingParameters._linearDuration
);
accumulatedReward += computeReward(
currentTotalRewardAmount,
targetTime,
targetStake._stakaAmount,
currentStartTime,
existingStake
);
return accumulatedReward;
}
/***@notice Calculate the reward for a give stake if withdrawn at 'targetTime' */
function computeReward(
uint256 applicableReward,
uint256 targetTime,
uint256 stakaAmount,
uint256 rewardStartDate,
bool existingStake
) private view returns (uint256) {
uint256 mulltiplier = stakaAmount
.mul(applicableReward)
.mul(targetTime.sub(rewardStartDate))
.div(
_stakingParameters._endDate.sub(_stakingParameters._startDate)
);
uint256 divider = existingStake
? totalSupply()
: totalSupply().add(stakaAmount);
return mulltiplier.div(divider);
}
/**
* @notice
* Update Staking Token
*/
function setStakingToken(address stakingTokenAddress) external onlyOwner {
_stakingParameters._stakingToken = IERC20(stakingTokenAddress);
}
/*** @notice Withdraw reward */
function withdrawFromReward(uint256 amount) external onlyOwner {
//Check if there is enough reward tokens, this is to avoid paying rewards with other stakeholders stake
require(
amount <= getRewardBalance(),
"The contract does not have enough reward tokens"
);
//Transfer amount to contract (this)
if (!_stakingParameters._stakingToken.transfer(msg.sender, amount)) {
revert("couldn 't transfer tokens from sender to contract");
}
}
/**
* @notice
* Return the total amount staked
*/
function getTotalStaked() external view returns (uint256) {
return _totalKataStaked;
}
/**
* @notice
* Return the value of the penalty for early exit
*/
function getContractParameters()
external
view
returns (StakingContractParameters memory)
{
return _stakingParameters;
}
/**
* @notice
* Return stakes for msg.sender
*/
function getStake() external view returns (Stake memory) {
Stake memory currentStake = _stakeholdersMapping[msg.sender];
if (!currentStake._exists) {
// Return empty stake
return
Stake(
0,
0,
_stakingParameters._stakingToken,
0,
0,
APY(0, 1),
0,
false
);
}
if (_stakingStarted) {
currentStake._estimatedReward = computeRewardForStake(
block.timestamp,
currentStake,
true
);
currentStake._estimatedAPY = APY(
computeRewardForStake(
currentStake._rewardStartDate + 365 days,
currentStake,
true
).mul(100000).div(currentStake._amount),
100000
);
}
return currentStake;
}
function shouldStartContract(
uint256 newTotalKataStaked,
uint256 newCurrentNumberOfStakeHolders
) private view returns (bool) {
if (
_stakingParameters._minimumTotalStakeBeforeStart > 0 &&
newTotalKataStaked <
_stakingParameters._minimumTotalStakeBeforeStart
) {
return false;
}
if (
_stakingParameters._minimumNumberStakeHoldersBeforeStart > 0 &&
newCurrentNumberOfStakeHolders <
_stakingParameters._minimumNumberStakeHoldersBeforeStart
) {
return false;
}
return true;
}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal override {
if (from == address(0))
//Nothing to do when _mint is called
return;
if (to == address(0))
//Nothing to do when _burn is called
return;
Stake memory fromStake = _stakeholdersMapping[from];
uint256 amountOfKataToTransfer = (
_stakeholdersMapping[from]._amount.mul(amount)
).div(_stakeholdersMapping[from]._stakaAmount);
fromStake._exists = true;
fromStake._stakaAmount = amount;
fromStake._amount = amountOfKataToTransfer;
if (!_stakeholdersMapping[to]._exists) {
_stakeholdersMapping[to] = fromStake;
_stakeholdersMapping[from]._stakaAmount -= amount;
_stakeholdersMapping[from]._amount -= amountOfKataToTransfer;
} else {
_stakeholdersMapping[to]
._rewardStartDate = calculateNewRewardStartDate(
_stakeholdersMapping[to],
fromStake
);
_stakeholdersMapping[to]._stakaAmount += amount;
_stakeholdersMapping[to]._amount += amountOfKataToTransfer;
_stakeholdersMapping[from]._stakaAmount -= amount;
_stakeholdersMapping[from]._amount -= amountOfKataToTransfer;
}
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
/**
* onlyUser
* @dev guard contracts from calling method
**/
modifier onlyUser() {
require(msg.sender == tx.origin);
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Ownable
* @dev Ownable has an owner address to simplify "user permissions".
*/
contract Ownable {
address payable public owner;
/**
* Ownable
* @dev Ownable constructor sets the `owner` of the contract to sender
*/
constructor() { owner = payable(msg.sender); }
/**
* ownerOnly
* @dev Throws an error if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* transferOwnership
* @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 payable newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// 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 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// 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());
}
}
|
Calculate the reward for a give stake if withdrawn at 'targetTime' /
|
function computeReward(
uint256 applicableReward,
uint256 targetTime,
uint256 stakaAmount,
uint256 rewardStartDate,
bool existingStake
) private view returns (uint256) {
uint256 mulltiplier = stakaAmount
.mul(applicableReward)
.mul(targetTime.sub(rewardStartDate))
.div(
_stakingParameters._endDate.sub(_stakingParameters._startDate)
);
uint256 divider = existingStake
? totalSupply()
: totalSupply().add(stakaAmount);
return mulltiplier.div(divider);
}
| 13,461,776 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.