file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
./full_match/80001/0xaCD2BB9cA3849303dfdAB631eEE4D64dD83F5aC1/sources/contracts/PrimexProxyAdmin.sol
|
Changes the admin of `proxy` to `newAdmin`. Requirements: - This contract must be the current admin of `proxy`./
|
function changeProxyAdmin(
ITransparentUpgradeableProxy proxy,
address newAdmin
) public override onlyRole(BIG_TIMELOCK_ADMIN) {
proxy.changeAdmin(newAdmin);
}
| 5,673,043
|
pragma solidity ^0.4.19;
/**
* @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;
}
}
contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract BitGuildToken {
// Public variables of the token
string public name = "BitGuild PLAT";
string public symbol = "PLAT";
uint8 public decimals = 18;
uint256 public totalSupply = 10000000000 * 10 ** uint256(decimals); // 10 billion tokens;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
* Initializes contract with initial supply tokens to the creator of the contract
*/
function BitGuildToken() public {
balanceOf[msg.sender] = totalSupply;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
}
/**
* @title BitGuildWhitelist
* A small smart contract to provide whitelist functionality and storage
*/
contract BitGuildWhitelist {
address admin;
mapping (address => bool) public whitelist;
uint256 public totalWhitelisted = 0;
event AddressWhitelisted(address indexed user, bool whitelisted);
function BitGuildWhitelist() public {
admin = msg.sender;
}
// Doesn't accept eth
function () external payable {
revert();
}
// Allows an admin to update whitelist
function whitelistAddress(address[] _users, bool _whitelisted) public {
require(msg.sender == admin);
for (uint i = 0; i < _users.length; i++) {
if (whitelist[_users[i]] == _whitelisted) continue;
if (_whitelisted) {
totalWhitelisted++;
} else {
if (totalWhitelisted > 0) {
totalWhitelisted--;
}
}
AddressWhitelisted(_users[i], _whitelisted);
whitelist[_users[i]] = _whitelisted;
}
}
}
/**
* @title BitGuildCrowdsale
* Capped crowdsale with a stard/end date
*/
contract BitGuildCrowdsale {
using SafeMath for uint256;
// Token being sold
BitGuildToken public token;
// Whitelist being used
BitGuildWhitelist public whitelist;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// Crowdsale cap (how much can be raised total)
uint256 public cap = 14062.5 ether;
// Address where funds are collected
address public wallet;
// Predefined rate of PLAT to Ethereum (1/rate = crowdsale price)
uint256 public rate = 80000;
// Min/max purchase
uint256 public minContribution = 0.5 ether;
uint256 public maxContribution = 1500 ether;
// amount of raised money in wei
uint256 public weiRaised;
mapping (address => uint256) public contributions;
// Finalization flag for when we want to withdraw the remaining tokens after the end
bool public crowdsaleFinalized = false;
/**
* 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 BitGuildCrowdsale(uint256 _startTime, uint256 _endTime, address _token, address _wallet, address _whitelist) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_token != address(0));
require(_wallet != address(0));
require(_whitelist != address(0));
startTime = _startTime;
endTime = _endTime;
token = BitGuildToken(_token);
wallet = _wallet;
whitelist = BitGuildWhitelist(_whitelist);
}
// 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(whitelist.whitelist(beneficiary));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = getTokenAmount(weiAmount);
// update total and individual contributions
weiRaised = weiRaised.add(weiAmount);
contributions[beneficiary] = contributions[beneficiary].add(weiAmount);
// Send tokens
token.transfer(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
// Send funds
wallet.transfer(msg.value);
}
// Returns true if crowdsale event has ended
function hasEnded() public view returns (bool) {
bool capReached = weiRaised >= cap;
bool endTimeReached = now > endTime;
return capReached || endTimeReached || crowdsaleFinalized;
}
// Bonuses for larger purchases (in hundredths of percent)
function bonusPercentForWeiAmount(uint256 weiAmount) public pure returns(uint256) {
if (weiAmount >= 500 ether) return 1000; // 10%
if (weiAmount >= 250 ether) return 750; // 7.5%
if (weiAmount >= 100 ether) return 500; // 5%
if (weiAmount >= 50 ether) return 375; // 3.75%
if (weiAmount >= 15 ether) return 250; // 2.5%
if (weiAmount >= 5 ether) return 125; // 1.25%
return 0; // 0% bonus if lower than 5 eth
}
// Returns you how much tokens do you get for the wei passed
function getTokenAmount(uint256 weiAmount) internal view returns(uint256) {
uint256 tokens = weiAmount.mul(rate);
uint256 bonus = bonusPercentForWeiAmount(weiAmount);
tokens = tokens.mul(10000 + bonus).div(10000);
return tokens;
}
// Returns true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool moreThanMinPurchase = msg.value >= minContribution;
bool lessThanMaxPurchase = contributions[msg.sender] + msg.value <= maxContribution;
bool withinCap = weiRaised.add(msg.value) <= cap;
return withinPeriod && moreThanMinPurchase && lessThanMaxPurchase && withinCap && !crowdsaleFinalized;
}
// Escape hatch in case the sale needs to be urgently stopped
function finalizeCrowdsale() public {
require(msg.sender == wallet);
crowdsaleFinalized = true;
// send remaining tokens back to the admin
uint256 tokensLeft = token.balanceOf(this);
token.transfer(wallet, tokensLeft);
}
}
|
Bonuses for larger purchases (in hundredths of percent)
|
function bonusPercentForWeiAmount(uint256 weiAmount) public pure returns(uint256) {
}
| 10,689,321
|
pragma solidity ^0.4.17;
//the pragma line is the preprocessor directive, tells the version of solidity compiler
contract Lottery {
//struct used to store the user information
struct User {
address userAddress;
uint tokensBought;
uint[] guess;
}
// a list of the users
mapping (address => User) public users;
address[] public userAddresses;
address public owner;
bytes32 winningGuessSha3;
//contructor function
function Lottery(uint _winningGuess) {
// by default the owner of the contract is accounts[0] to set the owner change truffle.js
owner = msg.sender;
winningGuessSha3 = keccak256(_winningGuess);
}
// returns the number of tokens purchased by an account
function userTokens(address _user) view public returns (uint) {
return users[_user].tokensBought;
}
// returns the guess made by user so far
function userGuesses(address _user) view public returns(uint[]) {
return users[_user].guess;
}
// returns the winning guess
function winningGuess() view public returns(bytes32) {
return winningGuessSha3;
}
// to add a new user to the contract to make guesses
function makeUser() public{
users[msg.sender].userAddress = msg.sender;
users[msg.sender].tokensBought = 0;
userAddresses.push(msg.sender);
}
// function to add tokens to the user that calls the contract
// the money held in contract is sent using a payable modifier function
// money can be released using selfdestruct(address)
function addTokens() payable {
uint present = 0;
uint tokensToAdd = msg.value/(10**18);
for(uint i = 0; i < userAddresses.length; i++) {
if(userAddresses[i] == msg.sender) {
present = 1;
break;
}
}
// adding tokens if the user present in the userAddresses array
if (present == 1) {
users[msg.sender].tokensBought += tokensToAdd;
}
}
// to add user guesses
function makeGuess(uint _userGuess) {
require(_userGuess < 1000000 && users[msg.sender].tokensBought > 0);
users[msg.sender].guess.push(_userGuess);
users[msg.sender].tokensBought--;
}
// doesn't allow anyone to buy anymore tokens
function closeGame() returns(address){
// can only be called my the owner of the contract
require(owner == msg.sender);
address winner = winnerAddress();
return winner;
}
// returns the address of the winner once the game is closed
function winnerAddress() returns(address) {
for(uint i = 0; i < userAddresses.length; i++) {
User user= users[userAddresses[i]];
for(uint j = 0; j < user.guess.length; j++) {
if (keccak256(user.guess[j]) == winningGuessSha3) {
return user.userAddress;
}
}
}
// the owner wins if there are no winning guesses
return owner;
}
// sends 50% of the ETH in contract to the winner and rest of it to the owner
function getPrice() returns (uint){
require(owner == msg.sender);
address winner = winnerAddress();
if (winner == owner) {
owner.transfer(address(this).balance);
} else {
// returns the half the balance of the contract
uint toTransfer = address(this).balance / 2;
// transfer 50% to the winner
winner.transfer(toTransfer);
// transfer rest of the balance to the owner of the contract
owner.transfer(address(this).balance);
}
return address(this).balance;
}
}
|
function to add tokens to the user that calls the contract the money held in contract is sent using a payable modifier function money can be released using selfdestruct(address) adding tokens if the user present in the userAddresses array
|
function addTokens() payable {
uint present = 0;
uint tokensToAdd = msg.value/(10**18);
for(uint i = 0; i < userAddresses.length; i++) {
if(userAddresses[i] == msg.sender) {
present = 1;
break;
}
}
if (present == 1) {
users[msg.sender].tokensBought += tokensToAdd;
}
}
| 13,131,664
|
//Address: 0x151b11892dd6ab1f91055dcd01d23d03a2c47570
//Contract name: ServiceLocator
//Balance: 0 Ether
//Verification Date: 2/27/2018
//Transacion Count: 5
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @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 ServiceLocator is Ownable {
struct Registry {
// address to resolve
address addr;
// last updated time
uint256 updated;
// time to live for this record
uint32 ttl;
}
mapping (bytes32 => Registry) registry;
mapping (address => string) ptr;
// EVENTS
event Set(string namespace, address registryAddr, uint32 ttl);
event Remove(string namespace);
/**
* @dev Gets the address for a provided namespace
* in the service locator.
* @param _namespace - namespace string for the record.
* @return address for the stored record
*/
function get(string _namespace) constant public returns (address) {
Registry storage r = registry[keccak256(_namespace)];
if (r.ttl > 0 && r.updated + r.ttl < now) {
return address(0);
}
return r.addr;
}
/**
* @dev Gets the namespace for a provided address
* in the service locator.
* @param _addr - address for the record.
* @return namespace for the stored record
*/
function getNamespace(address _addr) constant public returns (string) {
string storage ns = ptr[_addr];
Registry storage r = registry[keccak256(ns)];
if (r.ttl > 0 && r.updated + r.ttl < now) {
return "";
}
return ns;
}
/**
* @dev Sets or Updates service locator registry
* @param _namespace - namespace string for the record.
* @param _addr - address of the contract to be stored.
* @param _ttl - How long in seconds will the record be valid. (0 means no ttl).
*/
function set(string _namespace, address _addr, uint32 _ttl) onlyOwner public {
require(isContract(_addr));
registry[keccak256(_namespace)] = Registry({
addr: _addr,
updated: now,
ttl: _ttl
});
// saves reverse record.
ptr[_addr] = _namespace;
Set(_namespace, _addr, _ttl);
}
/**
* @dev Removes a service locator registry
* @param _namespace - namespace string for the record.
*/
function remove(string _namespace) onlyOwner public {
bytes32 h = keccak256(_namespace);
delete ptr[ registry[h].addr ];
delete registry[ h ];
Remove(_namespace);
}
/**
* @dev Checks if the provided address is a contract.
* @param _addr - ethereum address
* @return bool true if provided address is a contract.
*/
function isContract(address _addr) private view returns (bool) {
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
}
|
Removes a service locator registry _namespace - namespace string for the record./
|
function remove(string _namespace) onlyOwner public {
bytes32 h = keccak256(_namespace);
delete ptr[ registry[h].addr ];
delete registry[ h ];
Remove(_namespace);
}
| 15,861,194
|
pragma solidity ^0.5.9;
import "./DelightArmyManagerInterface.sol";
import "./DelightManager.sol";
import "./DelightBuildingManager.sol";
import "./DelightItemManager.sol";
import "./DelightKnightItemInterface.sol";
import "./Util/SafeMath.sol";
contract DelightArmyManager is DelightArmyManagerInterface, DelightManager {
using SafeMath for uint;
// The maximum number of units on a single tile.
// ํ ์์น์ ์กด์ฌํ ์ ์๋ ์ต๋ ์ ๋ ์
uint constant private MAX_POSITION_UNIT_COUNT = 50;
// The default buff HP of a knight.
// ๊ธฐ์ฌ์ ๊ธฐ๋ณธ ๋ฒํ HP
uint constant private KNIGHT_DEFAULT_BUFF_HP = 10;
// Delight building manager
// Delight ๊ฑด๋ฌผ ๊ด๋ฆฌ์
DelightBuildingManager private buildingManager;
// Delight item manager
// Delight ์์ดํ
๊ด๋ฆฌ์
DelightItemManager private itemManager;
// ๊ธฐ์ฌ ์์ดํ
DelightKnightItemInterface private knightItem;
constructor(
DelightInfoInterface info,
DelightResource wood,
DelightResource stone,
DelightResource iron,
DelightResource ducat,
DelightKnightItemInterface _knightItem
) DelightManager(info, wood, stone, iron, ducat) public {
// Knight item.
// ๊ธฐ์ฌ ์์ดํ
knightItem = _knightItem;
// 0๋ฒ์ง๋ ์ฌ์ฉํ์ง ์์ต๋๋ค.
armies.push(Army({
unitKind : 99,
unitCount : 0,
knightItemId : 0,
col : COL_RANGE,
row : ROW_RANGE,
owner : address(0),
createTime : 0
}));
}
function setDelightBuildingManagerOnce(address addr) external {
// The address must be empty.
// ๋น์ด์๋ ์ฃผ์์ธ ๊ฒฝ์ฐ์๋ง
require(address(buildingManager) == address(0));
buildingManager = DelightBuildingManager(addr);
}
function setDelightItemManagerOnce(address addr) external {
// The address must be empty.
// ๋น์ด์๋ ์ฃผ์์ธ ๊ฒฝ์ฐ์๋ง
require(address(itemManager) == address(0));
itemManager = DelightItemManager(addr);
}
// Executed only when the sender is Delight.
// Sender๊ฐ Delight์ผ๋๋ง ์คํ
modifier onlyDelight() {
require(
msg.sender == delight ||
msg.sender == address(buildingManager) ||
msg.sender == address(itemManager)
);
_;
}
Army[] internal armies;
mapping(uint => mapping(uint => uint[])) internal positionToArmyIds;
mapping(uint => Reward) private battleIdToReward;
// Returns the total number of armies.
// ๋ถ๋์ ์ด ๊ฐ์๋ฅผ ๋ฐํํฉ๋๋ค.
function getArmyCount() view external returns (uint) {
return armies.length;
}
// Returns the information of the army.
// ๋ถ๋์ ์ ๋ณด๋ฅผ ๋ฐํํฉ๋๋ค.
function getArmyInfo(uint armyId) view external returns (
uint unitKind,
uint unitCount,
uint knightItemId,
uint col,
uint row,
address owner,
uint createTime
) {
Army memory army = armies[armyId];
return (
army.unitKind,
army.unitCount,
army.knightItemId,
army.col,
army.row,
army.owner,
army.createTime
);
}
// ๋ณด์ ์ ๋ณด๋ฅผ ๋ฐํํฉ๋๋ค.
function getRewardInfo(uint battleId) view external returns (
uint wood,
uint stone,
uint iron,
uint ducat
) {
Reward memory reward = battleIdToReward[battleId];
return (
reward.wood,
reward.stone,
reward.iron,
reward.ducat
);
}
// Gets the IDs of the armies in a specific tile.
// ํน์ ์์น์ ์กด์ฌํ๋ ๋ถ๋์ ID๋ค์ ๊ฐ์ ธ์ต๋๋ค.
function getPositionArmyIds(uint col, uint row) view external returns (uint[] memory) {
return positionToArmyIds[col][row];
}
// Gets the owners of the armies in a specific tile.
// ํน์ ์์น์ ์กด์ฌํ๋ ๋ถ๋์ ์์ ์ฃผ๋ฅผ ๊ฐ์ ธ์ต๋๋ค.
function getPositionOwner(uint col, uint row) view external returns (address) {
uint[] memory armyIds = positionToArmyIds[col][row];
for (uint i = 0; i < armyIds.length; i += 1) {
address owner = armies[armyIds[i]].owner;
if (owner != address(0)) {
return owner;
}
}
return address(0);
}
// ํน์ ์์น์ ์ด ์ ๋ ์ซ์๋ฅผ ๊ณ์ฐํฉ๋๋ค.
function getTotalUnitCount(uint distance, uint col, uint row) view public returns (uint) {
uint[] memory armyIds = positionToArmyIds[col][row];
uint totalUnitCount = 0;
for (uint i = 0; i < armyIds.length; i += 1) {
// Check if the unit can reach the distance.
// ์ด๋์ด ๊ฐ๋ฅํ ๊ฑฐ๋ฆฌ์ธ์ง ํ์ธํฉ๋๋ค.
if (distance <= info.getUnitMovableDistance(armies[armyIds[i]].unitKind)) {
totalUnitCount = totalUnitCount.add(armies[armyIds[i]].unitCount);
}
}
return totalUnitCount;
}
// Creates armies.
// ๋ถ๋๋ฅผ ์์ฐํฉ๋๋ค.
function createArmy(address owner, uint col, uint row, uint unitKind, uint unitCount) onlyDelight external {
uint[] storage armyIds = positionToArmyIds[col][row];
// The total number of units in the building's tile must not exceed the maximum unit number.
// ๊ฑด๋ฌผ์ด ์์นํ ๊ณณ์ ์ด ์ ๋ ์ซ์๊ฐ ์ต๋ ์ ๋ ์๋ฅผ ๋๊ธฐ๋ฉด ์๋ฉ๋๋ค.
require(getTotalUnitCount(0, col, row).add(unitCount) <= MAX_POSITION_UNIT_COUNT);
// ๊ธฐ์ฌ๋ ํ๋ ์ด์ ์์ฑํ ์ ์์ต๋๋ค.
require(unitKind != UNIT_KNIGHT || unitCount == 1);
uint materialWood = info.getUnitMaterialWood(unitKind).mul(unitCount);
uint materialStone = info.getUnitMaterialStone(unitKind).mul(unitCount);
uint materialIron = info.getUnitMaterialIron(unitKind).mul(unitCount);
uint materialDucat = info.getUnitMaterialDucat(unitKind).mul(unitCount);
// Checks if there's enough amount of required resources to create the army.
// ๋ถ๋๋ฅผ ์์ฑํ๋๋ฐ ํ์ํ ์์์ด ์ถฉ๋ถํ์ง ํ์ธํฉ๋๋ค.
require(
wood.balanceOf(owner) >= materialWood &&
stone.balanceOf(owner) >= materialStone &&
iron.balanceOf(owner) >= materialIron &&
ducat.balanceOf(owner) >= materialDucat
);
armyIds.length = UNIT_KIND_COUNT;
// If an army exists already, the number of units in the army increases.
// ๊ธฐ์กด์ ๋ถ๋๊ฐ ์กด์ฌํ๋ฉด ๋ถ๋์์ ์ซ์ ์ฆ๊ฐ
if (armyIds[unitKind] != 0) {
// ๊ธฐ์ฌ๋ ์ถ๊ฐํ ์ ์์ต๋๋ค.
require(unitKind != UNIT_KNIGHT);
armies[armyIds[unitKind]].unitCount = armies[armyIds[unitKind]].unitCount.add(unitCount);
}
// Creates a new army.
// ์ ๋ถ๋ ์์ฑ
else {
armyIds[unitKind] = armies.push(Army({
unitKind : unitKind,
unitCount : unitCount,
knightItemId : 0,
col : col,
row : row,
owner : owner,
createTime : now
})).sub(1);
}
// Transfers the resources to Delight.
// ์์์ Delight๋ก ์ด์ ํฉ๋๋ค.
wood.transferFrom(owner, delight, materialWood);
stone.transferFrom(owner, delight, materialStone);
iron.transferFrom(owner, delight, materialIron);
ducat.transferFrom(owner, delight, materialDucat);
// ์ด๋ฒคํธ ๋ฐ์
emit CreateArmy(armyIds[unitKind]);
}
// Equips items in the army.
// ๋ถ๋์ ์์ดํ
์ ์ฅ์ฐฉํฉ๋๋ค.
function attachItem(address owner, uint armyId, uint itemKind, uint unitCount) onlyDelight external {
Army storage army = armies[armyId];
// Checks the owner of the army.
// ๋ถ๋์ ์์ ์ฃผ๋ฅผ ํ์ธํฉ๋๋ค.
require(army.owner == owner);
// Checks if there's enough units.
// ์ ๋ ์๊ฐ ์ถฉ๋ถํ์ง ํ์ธํฉ๋๋ค.
require(army.unitCount >= unitCount);
// Checks if the item is available for the type of army.
// ๋ถ๋์ ์ฑ๊ฒฉ๊ณผ ์์ดํ
์ ์ฑ๊ฒฉ์ด ์ผ์นํ์ง ํ์ธํฉ๋๋ค.
require(
// Swordsmen
// ๊ฒ๋ณ
(
army.unitKind == UNIT_SWORDSMAN &&
(
itemKind == ITEM_AXE ||
itemKind == ITEM_SPEAR ||
itemKind == ITEM_SHIELD ||
itemKind == ITEM_HOOD
)
) ||
// Archers
// ๊ถ์
(
army.unitKind == UNIT_ARCHER &&
(
itemKind == ITEM_CROSSBOW ||
itemKind == ITEM_BALLISTA ||
itemKind == ITEM_CATAPULT
)
) ||
// Cavalry
// ๊ธฐ๋ง๋ณ
(
army.unitKind == UNIT_CAVALY &&
(
itemKind == ITEM_CAMEL ||
itemKind == ITEM_ELEPHANT
)
)
);
// Transfers items to Delight.
// ์์ดํ
์ Delight๋ก ์ด์ ํฉ๋๋ค.
itemManager.attachItem(owner, itemKind, unitCount);
// Creates a new army, changing some of the units.
// ์ ๋์ ์ผ๋ถ๋ฅผ ๋ณ๊ฒฝํ์ฌ ์๋ก์ด ๋ถ๋๋ฅผ ์์ฑํฉ๋๋ค.
// The type of the units of the new army.
// ์ ๋ถ๋ ์ ๋์ ์ฑ๊ฒฉ
uint unitKind;
if (itemKind == ITEM_AXE) {
unitKind = UNIT_AXEMAN;
} else if (itemKind == ITEM_SPEAR) {
unitKind = UNIT_SPEARMAN;
} else if (itemKind == ITEM_SHIELD) {
unitKind = UNIT_SHIELDMAN;
} else if (itemKind == ITEM_HOOD) {
unitKind = UNIT_SPY;
}
else if (itemKind == ITEM_CROSSBOW) {
unitKind = UNIT_CROSSBOWMAN;
} else if (itemKind == ITEM_BALLISTA) {
unitKind = UNIT_BALLISTA;
} else if (itemKind == ITEM_CATAPULT) {
unitKind = UNIT_CATAPULT;
}
else if (itemKind == ITEM_CAMEL) {
unitKind = UNIT_CAMELRY;
} else if (itemKind == ITEM_ELEPHANT) {
unitKind = UNIT_WAR_ELEPHANT;
}
army.unitCount = army.unitCount.sub(unitCount);
uint[] storage armyIds = positionToArmyIds[army.col][army.row];
// If an army already exists, the number of units in the army increases.
// ๊ธฐ์กด์ ๋ถ๋๊ฐ ์กด์ฌํ๋ฉด ๋ถ๋์์ ์ซ์ ์ฆ๊ฐ
uint originArmyId = armyIds[unitKind];
if (originArmyId != 0) {
armies[originArmyId].unitCount = armies[originArmyId].unitCount.add(unitCount);
}
// Creates a new army.
// ์ ๋ถ๋ ์์ฑ
else {
armyIds[unitKind] = armies.push(Army({
unitKind : unitKind,
unitCount : unitCount,
knightItemId : 0,
col : army.col,
row : army.row,
owner : owner,
createTime : now
})).sub(1);
// ์ด๋ฒคํธ ๋ฐ์
emit CreateArmy(armyIds[unitKind]);
}
// ๊ธฐ์กด ๋ถ๋์์ด ๋จ์์์ง ์์ผ๋ฉด ์ ๊ฑฐํฉ๋๋ค.
if (army.unitCount == 0) {
delete armyIds[army.unitKind];
delete armies[armyId];
}
// ์ด๋ฒคํธ ๋ฐ์
emit AttachItem(armyId, armyIds[unitKind]);
}
// Equips an item to a knight.
// ๊ธฐ์ฌ์ ์์ดํ
์ ์ฅ์ฐฉํฉ๋๋ค.
function attachKnightItem(address owner, uint armyId, uint itemId) onlyDelight external {
Army storage army = armies[armyId];
// Check the army's owner.
// ๋ถ๋์ ์์ ์ฃผ๋ฅผ ํ์ธํฉ๋๋ค.
require(army.owner == owner);
// Check if it's a knight.
// ๊ธฐ์ฌ์ธ์ง ํ์ธํฉ๋๋ค.
require(army.unitKind == UNIT_KNIGHT);
// Check if the knight is already equipped with an item.
// ๊ธฐ์ฌ๊ฐ ์์ดํ
์ ์ฅ์ฐฉํ๊ณ ์์ง ์์์ง ํ์ธํฉ๋๋ค.
require(army.knightItemId == 0);
// Transfers the item to Delight.
// ์์ดํ
์ Delight๋ก ์ด์ ํฉ๋๋ค.
itemManager.attachKnightItem(owner, itemId);
// Assigns the knight item.
// ๊ธฐ์ฌ ์์ดํ
์ ์ง์ ํฉ๋๋ค.
army.knightItemId = itemId;
// ์ด๋ฒคํธ ๋ฐ์
emit AttachKnightItem(armyId);
}
// Moves an army.
// ๋ถ๋์ ์์น๋ฅผ ์ด์ ํฉ๋๋ค.
function moveArmy(uint fromCol, uint fromRow, uint toCol, uint toRow) onlyDelight external {
// ์์น๊ฐ ๋ฌ๋ผ์ผ ํฉ๋๋ค.
require(fromCol != toCol || fromRow != toRow);
// Calculates distance.
// ๊ฑฐ๋ฆฌ ๊ณ์ฐ
uint distance = (fromCol < toCol ? toCol - fromCol : fromCol - toCol) + (fromRow < toRow ? toRow - fromRow : fromRow - toRow);
uint[] storage armyIds = positionToArmyIds[fromCol][fromRow];
uint[] storage targetArmyIds = positionToArmyIds[toCol][toRow];
targetArmyIds.length = UNIT_KIND_COUNT;
// Calculate the total number of units in the tile where the merge take place.
// ๋ณํฉํ ์์น์ ์กด์ฌํ๋ ์ด ์ ๋ ์ซ์๋ฅผ ๊ณ์ฐํฉ๋๋ค.
uint totalUnitCount = getTotalUnitCount(0, toCol, toRow);
for (uint i = 0; i < UNIT_KIND_COUNT; i += 1) {
Army memory army = armies[armyIds[i]];
if (
// The number of units must be bigger than 0.
// ์ ๋์ ๊ฐ์๊ฐ 0๊ฐ ์ด์์ด์ด์ผ ํฉ๋๋ค.
army.unitCount > 0 &&
// Check if the unit can reach the distance.
// ์ด๋์ด ๊ฐ๋ฅํ ๊ฑฐ๋ฆฌ์ธ์ง ํ์ธํฉ๋๋ค.
distance <= info.getUnitMovableDistance(army.unitKind)) {
moveArmyOne(totalUnitCount, armyIds[i], army.unitCount, toCol, toRow);
}
}
}
// ๋จ์ผ ๋ถ๋์ ์์น๋ฅผ ์ด์ ํฉ๋๋ค.
function moveArmyOne(uint totalUnitCount, uint armyId, uint unitCount, uint toCol, uint toRow) onlyDelight public {
Army storage army = armies[armyId];
uint[] storage armyIds = positionToArmyIds[army.col][army.row];
uint[] storage targetArmyIds = positionToArmyIds[toCol][toRow];
targetArmyIds.length = UNIT_KIND_COUNT;
Army storage targetArmy = armies[targetArmyIds[army.unitKind]];
// If the number of units exceeds the maximum number when just moving,
// ๊ทธ๋๋ก ์ด๋ํ์ ๋ ์กด์ฌํ ์ ์๋ ์ต๋ ์ ๋์ ์ซ์๋ฅผ ๋๋ ๊ฒฝ์ฐ
if (totalUnitCount.add(unitCount) > MAX_POSITION_UNIT_COUNT) {
uint movableUnitCount = MAX_POSITION_UNIT_COUNT.sub(totalUnitCount);
// ์ด๋ํ ์ ๋์ 1๊ฐ ์ด์์ด์ด์ผํฉ๋๋ค.
require(movableUnitCount > 0);
// Creates a new army if it's empty.
// ๋น์ด์๋ ๊ณณ์ด๋ฉด ์ ๋ถ๋๋ฅผ ์์ฑํฉ๋๋ค.
if (targetArmy.unitCount == 0) {
targetArmyIds[army.unitKind] = armies.push(Army({
unitKind : army.unitKind,
unitCount : movableUnitCount,
knightItemId : 0,
col : toCol,
row : toRow,
owner : army.owner,
createTime : now
})).sub(1);
army.unitCount = army.unitCount.sub(movableUnitCount);
// ์ด๋ฒคํธ ๋ฐ์
emit CreateArmy(targetArmyIds[army.unitKind]);
}
// Merges with an existing army if it isn't empty.
// ๋น์ด์์ง ์์ผ๋ฉด ๋ณํฉํฉ๋๋ค.
else {
// ๊ธฐ์ฌ๋ ๋ณํฉํ ์ ์์ต๋๋ค.
require(army.unitKind != UNIT_KNIGHT);
targetArmy.unitCount = targetArmy.unitCount.add(movableUnitCount);
army.unitCount = army.unitCount.sub(movableUnitCount);
}
// ์ด๋ฒคํธ ๋ฐ์
emit MergeArmy(armyId, targetArmyIds[army.unitKind], movableUnitCount);
// ๊ธฐ์กด ๋ถ๋์์ด ๋จ์์์ง ์์ผ๋ฉด ์ ๊ฑฐํฉ๋๋ค.
if (army.unitCount == 0) {
delete armyIds[army.unitKind];
delete armies[armyId];
}
}
// ๋ชจ๋ ์ ๋ ์ด๋
else if (army.unitCount == unitCount) {
// move if the tile is empty.
// ๋น์ด์๋ ๊ณณ์ด๋ฉด ์ด์ ํฉ๋๋ค.
if (targetArmy.unitCount == 0) {
targetArmyIds[army.unitKind] = armyId;
army.col = toCol;
army.row = toRow;
// ์ด๋ฒคํธ ๋ฐ์
emit MoveArmy(armyId);
delete armyIds[army.unitKind];
}
// merge with an existing army if it isn't empty.
// ๋น์ด์์ง ์์ผ๋ฉด ๋ณํฉํฉ๋๋ค.
else {
// ๊ธฐ์ฌ๋ ๋ณํฉํ ์ ์์ต๋๋ค.
require(army.unitKind != UNIT_KNIGHT);
targetArmy.unitCount = targetArmy.unitCount.add(army.unitCount);
// ์ด๋ฒคํธ ๋ฐ์
emit MergeArmy(armyId, targetArmyIds[army.unitKind], army.unitCount);
delete armyIds[army.unitKind];
delete armies[armyId];
}
}
// ์ผ๋ถ ์ ๋ ์ด๋
else {
// Creates a new army if it's empty.
// ๋น์ด์๋ ๊ณณ์ด๋ฉด ์ ๋ถ๋๋ฅผ ์์ฑํฉ๋๋ค.
if (targetArmy.unitCount == 0) {
targetArmyIds[army.unitKind] = armies.push(Army({
unitKind : army.unitKind,
unitCount : unitCount,
knightItemId : 0,
col : toCol,
row : toRow,
owner : army.owner,
createTime : now
})).sub(1);
army.unitCount = army.unitCount.sub(unitCount);
// ์ด๋ฒคํธ ๋ฐ์
emit CreateArmy(targetArmyIds[army.unitKind]);
}
// Merges with an existing army if it isn't empty.
// ๋น์ด์์ง ์์ผ๋ฉด ๋ณํฉํฉ๋๋ค.
else {
// ๊ธฐ์ฌ๋ ๋ณํฉํ ์ ์์ต๋๋ค.
require(army.unitKind != UNIT_KNIGHT);
targetArmy.unitCount = targetArmy.unitCount.add(unitCount);
army.unitCount = army.unitCount.sub(unitCount);
}
// ์ด๋ฒคํธ ๋ฐ์
emit MergeArmy(armyId, targetArmyIds[army.unitKind], unitCount);
}
}
function getItemKindByUnitKind(uint unitKind) pure private returns (uint) {
if (unitKind == UNIT_AXEMAN) {
return ITEM_AXE;
} else if (unitKind == UNIT_SPEARMAN) {
return ITEM_SPEAR;
} else if (unitKind == UNIT_SHIELDMAN) {
return ITEM_SHIELD;
} else if (unitKind == UNIT_SPY) {
return ITEM_HOOD;
}
else if (unitKind == UNIT_CROSSBOWMAN) {
return ITEM_CROSSBOW;
} else if (unitKind == UNIT_BALLISTA) {
return ITEM_BALLISTA;
} else if (unitKind == UNIT_CATAPULT) {
return ITEM_CATAPULT;
}
else if (unitKind == UNIT_CAMELRY) {
return ITEM_CAMEL;
} else if (unitKind == UNIT_WAR_ELEPHANT) {
return ITEM_ELEPHANT;
}
return 0;
}
// Attack
// ๋ถ๋๋ฅผ ๊ณต๊ฒฉํฉ๋๋ค.
function attack(uint battleId, uint totalDamage, uint distance, uint col, uint row) onlyDelight external returns (uint totalDeadUnitCount) {
uint damage = totalDamage;
// Loot
// ์ ๋ฆฌํ
Reward storage reward = battleIdToReward[battleId];
uint[] storage armyIds = positionToArmyIds[col][row];
for (uint i = 0; i < UNIT_KIND_COUNT; i += 1) {
Army storage army = armies[armyIds[i]];
if (
// The number of units must be more than 0.
// ์ ๋์ ๊ฐ์๊ฐ 0๊ฐ ์ด์์ด์ด์ผ ํฉ๋๋ค.
army.unitCount > 0 &&
// Check if the units can reach the distance.
// ์ด๋์ด ๊ฐ๋ฅํ ๊ฑฐ๋ฆฌ์ธ์ง ํ์ธํฉ๋๋ค.
distance <= info.getUnitMovableDistance(army.unitKind)) {
// ์ ๋์ ์ฒด๋ ฅ์ ๊ณ์ฐํฉ๋๋ค.
uint unitHP = info.getUnitHP(army.unitKind).add(
// Adds the knight item's HP if the unit's a knight.
// ๊ธฐ์ฌ์ธ ๊ฒฝ์ฐ ๊ธฐ์ฌ ์์ดํ
์ HP๋ฅผ ์ถ๊ฐํฉ๋๋ค.
i == UNIT_KNIGHT ? knightItem.getItemHP(army.knightItemId) : (
// If the unit's not a knight, adds the knight's buff HP.
// ๊ธฐ์ฌ๊ฐ ์๋ ๊ฒฝ์ฐ ๊ธฐ์ฌ์ ๋ฒํ HP๋ฅผ ์ถ๊ฐํฉ๋๋ค.
armyIds[UNIT_KNIGHT] != 0 && distance <= info.getUnitMovableDistance(UNIT_KNIGHT) ? KNIGHT_DEFAULT_BUFF_HP + knightItem.getItemBuffHP(armies[armyIds[UNIT_KNIGHT]].knightItemId) : 0
)
).add(
// ์ด๋ ๊ฑฐ๋ฆฌ๊ฐ 0์ผ๋๋ง ๋ณ์ฌ ์์น์ ๊ฑด๋ฌผ์ ๋ฒํ HP๋ฅผ ๊ฐ์ ธ์ต๋๋ค.
distance == 0 ? buildingManager.getBuildingBuffHP(col, row) : 0
);
// Calcultes the HPs of the friendly army.
// ์๊ตฐ์ ์ฒด๋ ฅ์ ๊ณ์ฐํฉ๋๋ค.
uint armyHP = unitHP.mul(army.unitCount);
armyHP = armyHP <= damage ? 0 : armyHP.sub(damage);
// Calculates the result of the battle.
// ์ ํฌ ๊ฒฐ๊ณผ๋ฅผ ๊ณ์ฐํฉ๋๋ค.
uint remainUnitCount = armyHP.add(
// ๋๋จธ์ง๊ฐ ๋จ์ง ์๋๋ก
armyHP % unitHP == 0 ? 0 : unitHP.sub(armyHP % unitHP)
).div(unitHP);
uint deadUnitCount = army.unitCount.sub(remainUnitCount);
// Lowers the total damage of the enemy.
// ์ ์ ์ด ๋ฐ๋ฏธ์ง๋ฅผ ๋ฎ์ถฅ๋๋ค.
damage = damage <= deadUnitCount.mul(unitHP) ? 0 : damage.sub(deadUnitCount.mul(unitHP));
// ์๊ฑฐ๋ฆฌ ๊ณต๊ฒฉ์ธ ๊ฒฝ์ฐ
if (battleId == 0) {
// Gets materials back.
// ์ฌ๋ฃ๋ค์ ๋๋ ค๋ฐ์ต๋๋ค.
wood.transferFrom(delight, army.owner, info.getUnitMaterialWood(army.unitKind).mul(deadUnitCount));
stone.transferFrom(delight, army.owner, info.getUnitMaterialStone(army.unitKind).mul(deadUnitCount));
iron.transferFrom(delight, army.owner, info.getUnitMaterialIron(army.unitKind).mul(deadUnitCount));
ducat.transferFrom(delight, army.owner, info.getUnitMaterialDucat(army.unitKind).mul(deadUnitCount));
}
else {
// Adds loot.
// ์ ๋ฆฌํ์ ์ถ๊ฐํฉ๋๋ค.
reward.wood = reward.wood.add(info.getUnitMaterialWood(army.unitKind).mul(deadUnitCount));
reward.stone = reward.stone.add(info.getUnitMaterialStone(army.unitKind).mul(deadUnitCount));
reward.iron = reward.iron.add(info.getUnitMaterialIron(army.unitKind).mul(deadUnitCount));
reward.ducat = reward.ducat.add(info.getUnitMaterialDucat(army.unitKind).mul(deadUnitCount));
}
// Dismantles the equipped item.
// ์ฅ์ฐฉํ ์์ดํ
์ ๋ถํดํฉ๋๋ค.
if (getItemKindByUnitKind(army.unitKind) != 0) {
itemManager.disassembleItem(getItemKindByUnitKind(army.unitKind), deadUnitCount);
}
// Saves the number of remaining units.
// ๋จ์ ๋ณ์ฌ ์ซ์๋ฅผ ์ ์ฅํฉ๋๋ค.
army.unitCount = remainUnitCount;
// Adds to the number of total casualties.
// ์ด ์ฌ๋ง ๋ณ์ฌ ์ซ์์ ์ถ๊ฐํฉ๋๋ค.
totalDeadUnitCount = totalDeadUnitCount.add(deadUnitCount);
// ์ด๋ฒคํธ ๋ฐ์
if (deadUnitCount > 0) {
emit DeadUnits(armyIds[i]);
}
// The army was annihilated.
// ๋ถ๋๊ฐ ์ ๋ฉธํ์ต๋๋ค.
if (army.unitCount == 0) {
// ๊ธฐ์ฌ๊ฐ ๋ฌด๊ธฐ๋ฅผ ์ฅ์ฐฉํ ๊ฒฝ์ฐ
if (army.unitKind == UNIT_KNIGHT && army.knightItemId != 0) {
// ์๊ฑฐ๋ฆฌ ๊ณต๊ฒฉ์ธ ๊ฒฝ์ฐ
if (battleId == 0) {
// ๊ธฐ์ฌ ๋ฌด๊ธฐ๋ฅผ ๋๋ ค๋ฐ์ต๋๋ค.
itemManager.transferKnightItem(army.owner, army.knightItemId);
}
else {
// ๊ธฐ์ฌ ๋ฌด๊ธฐ๋ฅผ ์ ๋ฆฌํ์ ์ถ๊ฐํฉ๋๋ค.
reward.knightItemId = army.knightItemId;
}
}
delete armies[armyIds[i]];
delete armyIds[i];
}
// ์ด์๋จ์ ๋ถ๋์์ด ์์ผ๋ฉด, ๊ทธ๋๋ก ๊ณต๊ฒฉ ์ข
๋ฃ
else {
break;
}
}
}
}
// Destroys the building.
// ๊ฑด๋ฌผ์ ํ๊ดดํฉ๋๋ค.
function destroyBuilding(uint battleId, uint col, uint row) onlyDelight external {
// The building must exist.
// ๊ฑด๋ฌผ์ด ์กด์ฌํ๋ ๊ฒฝ์ฐ์๋ง
if (buildingManager.getPositionBuildingId(col, row) != 0) {
// Loot
// ์ ๋ฆฌํ
Reward storage reward = battleIdToReward[battleId];
(
uint wood,
uint stone,
uint iron,
uint ducat
) = buildingManager.destroyBuilding(col, row);
// Adds to the loot.
// ์ ๋ฆฌํ์ ์ถ๊ฐํฉ๋๋ค.
reward.wood = reward.wood.add(wood);
reward.stone = reward.stone.add(stone);
reward.iron = reward.iron.add(iron);
reward.ducat = reward.ducat.add(ducat);
}
}
// Achieved victory in the battle.
// ์ ํฌ์์ ์น๋ฆฌํ์ต๋๋ค.
function win(uint battleId, address winner) onlyDelight external {
// Loot
// ์ ๋ฆฌํ
Reward memory reward = battleIdToReward[battleId];
// The winner takes the loot.
// ์น๋ฆฌ์๋ ์ ๋ฆฌํ์ ์ทจํฉ๋๋ค.
wood.transferFrom(delight, winner, reward.wood);
stone.transferFrom(delight, winner, reward.stone);
iron.transferFrom(delight, winner, reward.iron);
ducat.transferFrom(delight, winner, reward.ducat);
// ๊ธฐ์ฌ ๋ฌด๊ธฐ๋ฅผ ์ ๋ฌํฉ๋๋ค.
if (reward.knightItemId != 0) {
itemManager.transferKnightItem(winner, reward.knightItemId);
}
}
}
|
Destroys the building. ๊ฑด๋ฌผ์ ํ๊ดดํฉ๋๋ค. The building must exist. ๊ฑด๋ฌผ์ด ์กด์ฌํ๋ ๊ฒฝ์ฐ์๋ง Loot ์ ๋ฆฌํ Adds to the loot. ์ ๋ฆฌํ์ ์ถ๊ฐํฉ๋๋ค.
|
function destroyBuilding(uint battleId, uint col, uint row) onlyDelight external {
if (buildingManager.getPositionBuildingId(col, row) != 0) {
Reward storage reward = battleIdToReward[battleId];
(
uint wood,
uint stone,
uint iron,
uint ducat
) = buildingManager.destroyBuilding(col, row);
reward.wood = reward.wood.add(wood);
reward.stone = reward.stone.add(stone);
reward.iron = reward.iron.add(iron);
reward.ducat = reward.ducat.add(ducat);
}
}
| 2,526,351
|
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Vault} from "./Vault.sol";
import {ShareMath} from "./ShareMath.sol";
import {IStrikeSelection} from "../interfaces/IRibbon.sol";
import {GnosisAuction} from "./GnosisAuction.sol";
import {DateTime} from "./DateTime.sol";
import {
IOtokenFactory,
IOtoken,
IController,
GammaTypes
} from "../interfaces/GammaInterface.sol";
import {IERC20Detailed} from "../interfaces/IERC20Detailed.sol";
import {IGnosisAuction} from "../interfaces/IGnosisAuction.sol";
import {SupportsNonCompliantERC20} from "./SupportsNonCompliantERC20.sol";
library VaultLifecycleTreasury {
using SafeMath for uint256;
using SupportsNonCompliantERC20 for IERC20;
struct CloseParams {
address OTOKEN_FACTORY;
address USDC;
address currentOption;
uint256 delay;
uint16 lastStrikeOverrideRound;
uint256 overriddenStrikePrice;
uint256 period;
}
/**
* @notice Initialization parameters for the vault.
* @param _owner is the owner of the vault with critical permissions
* @param _feeRecipient is the address to recieve vault performance and management fees
* @param _managementFee is the management fee pct.
* @param _performanceFee is the perfomance fee pct.
* @param _tokenName is the name of the token
* @param _tokenSymbol is the symbol of the token
* @param _optionsPremiumPricer is the address of the contract with the
black-scholes premium calculation logic
* @param _strikeSelection is the address of the contract with strike selection logic
* @param _premiumDiscount is the vault's discount applied to the premium
* @param _auctionDuration is the duration of the gnosis auction
* @param _period is the period between each option sales
*/
struct InitParams {
address _owner;
address _keeper;
address _feeRecipient;
uint256 _managementFee;
uint256 _performanceFee;
string _tokenName;
string _tokenSymbol;
address _optionsPremiumPricer;
address _strikeSelection;
uint32 _premiumDiscount;
uint256 _auctionDuration;
uint256 _period;
uint256 _maxDepositors;
uint256 _minDeposit;
}
/**
* @notice Sets the next option the vault will be shorting, and calculates its premium for the auction
* @param strikeSelection is the address of the contract with strike selection logic
* @param optionsPremiumPricer is the address of the contract with the
black-scholes premium calculation logic
* @param premiumDiscount is the vault's discount applied to the premium
* @param closeParams is the struct with details on previous option and strike selection details
* @param vaultParams is the struct with vault general data
* @param vaultState is the struct with vault accounting state
* @return otokenAddress is the address of the new option
* @return premium is the premium of the new option
* @return strikePrice is the strike price of the new option
* @return delta is the delta of the new option
*/
function commitAndClose(
address strikeSelection,
address optionsPremiumPricer,
uint256 premiumDiscount,
CloseParams calldata closeParams,
Vault.VaultParams storage vaultParams,
Vault.VaultState storage vaultState
)
external
returns (
address otokenAddress,
uint256 premium,
uint256 strikePrice,
uint256 delta
)
{
uint256 expiry;
// uninitialized state
if (closeParams.currentOption == address(0)) {
expiry = getNextExpiry(block.timestamp, closeParams.period);
} else {
expiry = getNextExpiry(
IOtoken(closeParams.currentOption).expiryTimestamp(),
closeParams.period
);
}
IStrikeSelection selection = IStrikeSelection(strikeSelection);
bool isPut = vaultParams.isPut;
address underlying = vaultParams.underlying;
address asset = vaultParams.asset;
(strikePrice, delta) = closeParams.lastStrikeOverrideRound ==
vaultState.round
? (closeParams.overriddenStrikePrice, 0)
: selection.getStrikePrice(expiry, isPut);
require(strikePrice != 0, "!strikePrice");
// retrieve address if option already exists, or deploy it
otokenAddress = getOrDeployOtoken(
closeParams,
vaultParams,
underlying,
asset,
strikePrice,
expiry,
isPut
);
// get the black scholes premium of the option
premium = GnosisAuction.getOTokenPremiumInStables(
otokenAddress,
optionsPremiumPricer,
premiumDiscount
);
require(premium > 0, "!premium");
return (otokenAddress, premium, strikePrice, delta);
}
/**
* @notice Verify the otoken has the correct parameters to prevent vulnerability to opyn contract changes
* @param otokenAddress is the address of the otoken
* @param vaultParams is the struct with vault general data
* @param collateralAsset is the address of the collateral asset
* @param USDC is the address of usdc
* @param delay is the delay between commitAndClose and rollToNextOption
*/
function verifyOtoken(
address otokenAddress,
Vault.VaultParams storage vaultParams,
address collateralAsset,
address USDC,
uint256 delay
) private view {
require(otokenAddress != address(0), "!otokenAddress");
IOtoken otoken = IOtoken(otokenAddress);
require(otoken.isPut() == vaultParams.isPut, "Type mismatch");
require(
otoken.underlyingAsset() == vaultParams.underlying,
"Wrong underlyingAsset"
);
require(
otoken.collateralAsset() == collateralAsset,
"Wrong collateralAsset"
);
// we just assume all options use USDC as the strike
require(otoken.strikeAsset() == USDC, "strikeAsset != USDC");
uint256 readyAt = block.timestamp.add(delay);
require(otoken.expiryTimestamp() >= readyAt, "Expiry before delay");
}
/**
* @param currentShareSupply is the supply of the shares invoked with totalSupply()
* @param asset is the address of the vault's asset
* @param decimals is the decimals of the asset
* @param lastQueuedWithdrawAmount is the amount queued for withdrawals from last round
* @param managementFee is the management fee percent to charge on the AUM
*/
struct RolloverParams {
uint256 decimals;
uint256 totalBalance;
uint256 currentShareSupply;
uint256 lastQueuedWithdrawAmount;
uint256 managementFee;
}
/**
* @notice Calculate the shares to mint, new price per share, and
amount of funds to re-allocate as collateral for the new round
* @param vaultState is the storage variable vaultState passed from RibbonVault
* @param params is the rollover parameters passed to compute the next state
* @return newLockedAmount is the amount of funds to allocate for the new round
* @return queuedWithdrawAmount is the amount of funds set aside for withdrawal
* @return newPricePerShare is the price per share of the new round
* @return mintShares is the amount of shares to mint from deposits
* @return managementFeeInAsset is the amount of management fee charged by vault
*/
function rollover(
Vault.VaultState storage vaultState,
RolloverParams calldata params
)
external
view
returns (
uint256 newLockedAmount,
uint256 queuedWithdrawAmount,
uint256 newPricePerShare,
uint256 mintShares,
uint256 managementFeeInAsset
)
{
uint256 currentBalance = params.totalBalance;
uint256 pendingAmount = vaultState.totalPending;
uint256 queuedWithdrawShares = vaultState.queuedWithdrawShares;
uint256 balanceForVaultFees;
{
uint256 pricePerShareBeforeFee =
ShareMath.pricePerShare(
params.currentShareSupply,
currentBalance,
pendingAmount,
params.decimals
);
uint256 queuedWithdrawBeforeFee =
params.currentShareSupply > 0
? ShareMath.sharesToAsset(
queuedWithdrawShares,
pricePerShareBeforeFee,
params.decimals
)
: 0;
// Deduct the difference between the newly scheduled withdrawals
// and the older withdrawals
// so we can charge them fees before they leave
uint256 withdrawAmountDiff =
queuedWithdrawBeforeFee > params.lastQueuedWithdrawAmount
? queuedWithdrawBeforeFee.sub(
params.lastQueuedWithdrawAmount
)
: 0;
balanceForVaultFees = currentBalance
.sub(queuedWithdrawBeforeFee)
.add(withdrawAmountDiff);
}
managementFeeInAsset = getManagementFee(
balanceForVaultFees,
vaultState.totalPending,
params.managementFee
);
// Take into account the fee
// so we can calculate the newPricePerShare
currentBalance = currentBalance.sub(managementFeeInAsset);
{
newPricePerShare = ShareMath.pricePerShare(
params.currentShareSupply,
currentBalance,
pendingAmount,
params.decimals
);
// After closing the short, if the options expire in-the-money
// vault pricePerShare would go down because vault's asset balance decreased.
// This ensures that the newly-minted shares do not take on the loss.
mintShares = ShareMath.assetToShares(
pendingAmount,
newPricePerShare,
params.decimals
);
uint256 newSupply = params.currentShareSupply.add(mintShares);
queuedWithdrawAmount = newSupply > 0
? ShareMath.sharesToAsset(
queuedWithdrawShares,
newPricePerShare,
params.decimals
)
: 0;
}
return (
currentBalance.sub(queuedWithdrawAmount), // new locked balance subtracts the queued withdrawals
queuedWithdrawAmount,
newPricePerShare,
mintShares,
managementFeeInAsset
);
}
/**
* @notice Creates the actual Opyn short position by depositing collateral and minting otokens
* @param gammaController is the address of the opyn controller contract
* @param marginPool is the address of the opyn margin contract which holds the collateral
* @param oTokenAddress is the address of the otoken to mint
* @param depositAmount is the amount of collateral to deposit
* @return the otoken mint amount
*/
function createShort(
address gammaController,
address marginPool,
address oTokenAddress,
uint256 depositAmount
) external returns (uint256) {
IController controller = IController(gammaController);
uint256 newVaultID =
(controller.getAccountVaultCounter(address(this))).add(1);
// An otoken's collateralAsset is the vault's `asset`
// So in the context of performing Opyn short operations we call them collateralAsset
IOtoken oToken = IOtoken(oTokenAddress);
address collateralAsset = oToken.collateralAsset();
uint256 collateralDecimals =
uint256(IERC20Detailed(collateralAsset).decimals());
uint256 mintAmount;
if (oToken.isPut()) {
// For minting puts, there will be instances where the full depositAmount will not be used for minting.
// This is because of an issue with precision.
//
// For ETH put options, we are calculating the mintAmount (10**8 decimals) using
// the depositAmount (10**18 decimals), which will result in truncation of decimals when scaling down.
// As a result, there will be tiny amounts of dust left behind in the Opyn vault when minting put otokens.
//
// For simplicity's sake, we do not refund the dust back to the address(this) on minting otokens.
// We retain the dust in the vault so the calling contract can withdraw the
// actual locked amount + dust at settlement.
//
// To test this behavior, we can console.log
// MarginCalculatorInterface(0x7A48d10f372b3D7c60f6c9770B91398e4ccfd3C7).getExcessCollateral(vault)
// to see how much dust (or excess collateral) is left behind.
mintAmount = depositAmount
.mul(10**Vault.OTOKEN_DECIMALS)
.mul(10**18) // we use 10**18 to give extra precision
.div(oToken.strikePrice().mul(10**(10 + collateralDecimals)));
} else {
mintAmount = depositAmount;
if (collateralDecimals > 8) {
uint256 scaleBy = 10**(collateralDecimals.sub(8)); // oTokens have 8 decimals
if (mintAmount > scaleBy) {
mintAmount = depositAmount.div(scaleBy); // scale down from 10**18 to 10**8
}
}
}
// double approve to fix non-compliant ERC20s
IERC20 collateralToken = IERC20(collateralAsset);
collateralToken.safeApproveNonCompliant(marginPool, depositAmount);
IController.ActionArgs[] memory actions =
new IController.ActionArgs[](3);
actions[0] = IController.ActionArgs(
IController.ActionType.OpenVault,
address(this), // owner
address(this), // receiver
address(0), // asset, otoken
newVaultID, // vaultId
0, // amount
0, //index
"" //data
);
actions[1] = IController.ActionArgs(
IController.ActionType.DepositCollateral,
address(this), // owner
address(this), // address to transfer from
collateralAsset, // deposited asset
newVaultID, // vaultId
depositAmount, // amount
0, //index
"" //data
);
actions[2] = IController.ActionArgs(
IController.ActionType.MintShortOption,
address(this), // owner
address(this), // address to transfer to
oTokenAddress, // option address
newVaultID, // vaultId
mintAmount, // amount
0, //index
"" //data
);
controller.operate(actions);
return mintAmount;
}
/**
* @notice Close the existing short otoken position. Currently this implementation is simple.
* It closes the most recent vault opened by the contract. This assumes that the contract will
* only have a single vault open at any given time. Since calling `_closeShort` deletes vaults by
calling SettleVault action, this assumption should hold.
* @param gammaController is the address of the opyn controller contract
* @return amount of collateral redeemed from the vault
*/
function settleShort(address gammaController) external returns (uint256) {
IController controller = IController(gammaController);
// gets the currently active vault ID
uint256 vaultID = controller.getAccountVaultCounter(address(this));
GammaTypes.Vault memory vault =
controller.getVault(address(this), vaultID);
require(vault.shortOtokens.length > 0, "No short");
// An otoken's collateralAsset is the vault's `asset`
// So in the context of performing Opyn short operations we call them collateralAsset
IERC20 collateralToken = IERC20(vault.collateralAssets[0]);
// The short position has been previously closed, or all the otokens have been burned.
// So we return early.
if (address(collateralToken) == address(0)) {
return 0;
}
// This is equivalent to doing IERC20(vault.asset).balanceOf(address(this))
uint256 startCollateralBalance =
collateralToken.balanceOf(address(this));
// If it is after expiry, we need to settle the short position using the normal way
// Delete the vault and withdraw all remaining collateral from the vault
IController.ActionArgs[] memory actions =
new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.SettleVault,
address(this), // owner
address(this), // address to transfer to
address(0), // not used
vaultID, // vaultId
0, // not used
0, // not used
"" // not used
);
controller.operate(actions);
uint256 endCollateralBalance = collateralToken.balanceOf(address(this));
return endCollateralBalance.sub(startCollateralBalance);
}
/**
* @notice Exercises the ITM option using existing long otoken position. Currently this implementation is simple.
* It calls the `Redeem` action to claim the payout.
* @param gammaController is the address of the opyn controller contract
* @param oldOption is the address of the old option
* @param asset is the address of the vault's asset
* @return amount of asset received by exercising the option
*/
function settleLong(
address gammaController,
address oldOption,
address asset
) external returns (uint256) {
IController controller = IController(gammaController);
uint256 oldOptionBalance = IERC20(oldOption).balanceOf(address(this));
if (controller.getPayout(oldOption, oldOptionBalance) == 0) {
return 0;
}
uint256 startAssetBalance = IERC20(asset).balanceOf(address(this));
// If it is after expiry, we need to redeem the profits
IController.ActionArgs[] memory actions =
new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.Redeem,
address(0), // not used
address(this), // address to send profits to
oldOption, // address of otoken
0, // not used
oldOptionBalance, // otoken balance
0, // not used
"" // not used
);
controller.operate(actions);
uint256 endAssetBalance = IERC20(asset).balanceOf(address(this));
return endAssetBalance.sub(startAssetBalance);
}
/**
* @notice Burn the remaining oTokens left over from auction. Currently this implementation is simple.
* It burns oTokens from the most recent vault opened by the contract. This assumes that the contract will
* only have a single vault open at any given time.
* @param gammaController is the address of the opyn controller contract
* @param currentOption is the address of the current option
* @return amount of collateral redeemed by burning otokens
*/
function burnOtokens(address gammaController, address currentOption)
external
returns (uint256)
{
uint256 numOTokensToBurn =
IERC20(currentOption).balanceOf(address(this));
require(numOTokensToBurn > 0, "No oTokens to burn");
IController controller = IController(gammaController);
// gets the currently active vault ID
uint256 vaultID = controller.getAccountVaultCounter(address(this));
GammaTypes.Vault memory vault =
controller.getVault(address(this), vaultID);
require(vault.shortOtokens.length > 0, "No short");
IERC20 collateralToken = IERC20(vault.collateralAssets[0]);
uint256 startCollateralBalance =
collateralToken.balanceOf(address(this));
// Burning `amount` of oTokens from the ribbon vault,
// then withdrawing the corresponding collateral amount from the vault
IController.ActionArgs[] memory actions =
new IController.ActionArgs[](2);
actions[0] = IController.ActionArgs(
IController.ActionType.BurnShortOption,
address(this), // owner
address(this), // address to transfer from
address(vault.shortOtokens[0]), // otoken address
vaultID, // vaultId
numOTokensToBurn, // amount
0, //index
"" //data
);
actions[1] = IController.ActionArgs(
IController.ActionType.WithdrawCollateral,
address(this), // owner
address(this), // address to transfer to
address(collateralToken), // withdrawn asset
vaultID, // vaultId
vault.collateralAmounts[0].mul(numOTokensToBurn).div(
vault.shortAmounts[0]
), // amount
0, //index
"" //data
);
controller.operate(actions);
uint256 endCollateralBalance = collateralToken.balanceOf(address(this));
return endCollateralBalance.sub(startCollateralBalance);
}
/**
* @notice Calculates the management fee for this week's round
* @param currentBalance is the balance of funds held on the vault after closing short
* @param pendingAmount is the pending deposit amount
* @param managementFeePercent is the management fee pct.
* @return managementFeeInAsset is the management fee
*/
function getManagementFee(
uint256 currentBalance,
uint256 pendingAmount,
uint256 managementFeePercent
) internal pure returns (uint256 managementFeeInAsset) {
// At the first round, currentBalance=0, pendingAmount>0
// so we just do not charge anything on the first round
uint256 lockedBalanceSansPending =
currentBalance > pendingAmount
? currentBalance.sub(pendingAmount)
: 0;
uint256 _managementFeeInAsset;
// Always charge management fee regardless of whether the vault is
// making a profit from the previous options sale
_managementFeeInAsset = managementFeePercent > 0
? lockedBalanceSansPending.mul(managementFeePercent).div(
100 * Vault.FEE_MULTIPLIER
)
: 0;
return _managementFeeInAsset;
}
/**
* @notice Either retrieves the option token if it already exists, or deploy it
* @param closeParams is the struct with details on previous option and strike selection details
* @param vaultParams is the struct with vault general data
* @param underlying is the address of the underlying asset of the option
* @param collateralAsset is the address of the collateral asset of the option
* @param strikePrice is the strike price of the option
* @param expiry is the expiry timestamp of the option
* @param isPut is whether the option is a put
* @return the address of the option
*/
function getOrDeployOtoken(
CloseParams calldata closeParams,
Vault.VaultParams storage vaultParams,
address underlying,
address collateralAsset,
uint256 strikePrice,
uint256 expiry,
bool isPut
) internal returns (address) {
IOtokenFactory factory = IOtokenFactory(closeParams.OTOKEN_FACTORY);
address otokenFromFactory =
factory.getOtoken(
underlying,
closeParams.USDC,
collateralAsset,
strikePrice,
expiry,
isPut
);
if (otokenFromFactory != address(0)) {
return otokenFromFactory;
}
address otoken =
factory.createOtoken(
underlying,
closeParams.USDC,
collateralAsset,
strikePrice,
expiry,
isPut
);
verifyOtoken(
otoken,
vaultParams,
collateralAsset,
closeParams.USDC,
closeParams.delay
);
return otoken;
}
/**
* @notice Starts the gnosis auction
* @param auctionDetails is the struct with all the custom parameters of the auction
* @return the auction id of the newly created auction
*/
function startAuction(GnosisAuction.AuctionDetails calldata auctionDetails)
external
returns (uint256)
{
return GnosisAuction.startAuction(auctionDetails);
}
/**
* @notice Settles the gnosis auction
* @param gnosisEasyAuction is the contract address of Gnosis easy auction protocol
* @param auctionID is the auction ID of the gnosis easy auction
*/
function settleAuction(address gnosisEasyAuction, uint256 auctionID)
internal
{
IGnosisAuction(gnosisEasyAuction).settleAuction(auctionID);
}
/**
* @notice Places a bid in an auction
* @param bidDetails is the struct with all the details of the
bid including the auction's id and how much to bid
*/
function placeBid(GnosisAuction.BidDetails calldata bidDetails)
external
returns (
uint256 sellAmount,
uint256 buyAmount,
uint64 userId
)
{
return GnosisAuction.placeBid(bidDetails);
}
/**
* @notice Claims the oTokens belonging to the vault
* @param auctionSellOrder is the sell order of the bid
* @param gnosisEasyAuction is the address of the gnosis auction contract
holding custody to the funds
* @param counterpartyThetaVault is the address of the counterparty theta
vault of this delta vault
*/
function claimAuctionOtokens(
Vault.AuctionSellOrder calldata auctionSellOrder,
address gnosisEasyAuction,
address counterpartyThetaVault
) external {
GnosisAuction.claimAuctionOtokens(
auctionSellOrder,
gnosisEasyAuction,
counterpartyThetaVault
);
}
/**
* @notice Verify the constructor params satisfy requirements
* @param _initParams is the initialization parameter including owner, keeper, etc.
* @param _vaultParams is the struct with vault general data
*/
function verifyInitializerParams(
InitParams calldata _initParams,
Vault.VaultParams calldata _vaultParams,
uint256 _min_auction_duration
) external pure {
require(_initParams._owner != address(0), "!_owner");
require(_initParams._keeper != address(0), "!_keeper");
require(_initParams._feeRecipient != address(0), "!_feeRecipient");
require(
_initParams._performanceFee < 100 * Vault.FEE_MULTIPLIER,
"performanceFee >= 100%"
);
require(
_initParams._managementFee < 100 * Vault.FEE_MULTIPLIER,
"managementFee >= 100%"
);
require(bytes(_initParams._tokenName).length > 0, "!_tokenName");
require(bytes(_initParams._tokenSymbol).length > 0, "!_tokenSymbol");
require(
(_initParams._period == 7) ||
(_initParams._period == 14) ||
(_initParams._period == 30) ||
(_initParams._period == 90) ||
(_initParams._period == 180),
"!_period"
);
require(
_initParams._optionsPremiumPricer != address(0),
"!_optionsPremiumPricer"
);
require(
_initParams._strikeSelection != address(0),
"!_strikeSelection"
);
require(
_initParams._premiumDiscount > 0 &&
_initParams._premiumDiscount <
100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER,
"!_premiumDiscount"
);
require(
_initParams._auctionDuration >= _min_auction_duration,
"!_auctionDuration"
);
require(_initParams._maxDepositors > 0, "!_maxDepositors");
require(_initParams._minDeposit > 0, "!_minDeposit");
require(_vaultParams.asset != address(0), "!asset");
require(_vaultParams.underlying != address(0), "!underlying");
require(_vaultParams.minimumSupply > 0, "!minimumSupply");
require(_vaultParams.cap > 0, "!cap");
require(
_vaultParams.cap > _vaultParams.minimumSupply,
"cap has to be higher than minimumSupply"
);
}
/**
* @notice Gets the next options expiry timestamp, this function should be called
when there is sufficient guard to ensure valid period
* @param timestamp is the expiry timestamp of the current option
* @param period is no. of days in between option sales. Available periods are:
* 7(1w), 14(2w), 30(1m), 90(3m), 180(6m)
*/
function getNextExpiry(uint256 timestamp, uint256 period)
internal
pure
returns (uint256 nextExpiry)
{
if (period == 7) {
nextExpiry = DateTime.getNextFriday(timestamp);
nextExpiry = nextExpiry <= timestamp
? nextExpiry + 1 weeks
: nextExpiry;
} else if (period == 14) {
nextExpiry = DateTime.getNextFriday(timestamp);
nextExpiry = nextExpiry <= timestamp
? nextExpiry + 2 weeks
: nextExpiry;
} else if (period == 30) {
nextExpiry = DateTime.getMonthLastFriday(timestamp);
nextExpiry = nextExpiry <= timestamp
? DateTime.getMonthLastFriday(nextExpiry + 1 weeks)
: nextExpiry;
} else if (period == 90) {
nextExpiry = DateTime.getQuarterLastFriday(timestamp);
nextExpiry = nextExpiry <= timestamp
? DateTime.getQuarterLastFriday(nextExpiry + 1 weeks)
: nextExpiry;
} else if (period == 180) {
nextExpiry = DateTime.getBiannualLastFriday(timestamp);
nextExpiry = nextExpiry <= timestamp
? DateTime.getBiannualLastFriday(nextExpiry + 1 weeks)
: nextExpiry;
}
nextExpiry = nextExpiry - (nextExpiry % (24 hours)) + (8 hours);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
library Vault {
/************************************************
* IMMUTABLES & CONSTANTS
***********************************************/
// Fees are 6-decimal places. For example: 20 * 10**6 = 20%
uint256 internal constant FEE_MULTIPLIER = 10**6;
// Premium discount has 1-decimal place. For example: 80 * 10**1 = 80%. Which represents a 20% discount.
uint256 internal constant PREMIUM_DISCOUNT_MULTIPLIER = 10;
// Otokens have 8 decimal places.
uint256 internal constant OTOKEN_DECIMALS = 8;
// Percentage of funds allocated to options is 2 decimal places. 10 * 10**2 = 10%
uint256 internal constant OPTION_ALLOCATION_MULTIPLIER = 10**2;
// Placeholder uint value to prevent cold writes
uint256 internal constant PLACEHOLDER_UINT = 1;
struct VaultParams {
// Option type the vault is selling
bool isPut;
// Token decimals for vault shares
uint8 decimals;
// Asset used in Theta / Delta Vault
address asset;
// Underlying asset of the options sold by vault
address underlying;
// Minimum supply of the vault shares issued, for ETH it's 10**10
uint56 minimumSupply;
// Vault cap
uint104 cap;
}
struct OptionState {
// Option that the vault is shorting / longing in the next cycle
address nextOption;
// Option that the vault is currently shorting / longing
address currentOption;
// The timestamp when the `nextOption` can be used by the vault
uint32 nextOptionReadyAt;
}
struct VaultState {
// 32 byte slot 1
// Current round number. `round` represents the number of `period`s elapsed.
uint16 round;
// Amount that is currently locked for selling options
uint104 lockedAmount;
// Amount that was locked for selling options in the previous round
// used for calculating performance fee deduction
uint104 lastLockedAmount;
// 32 byte slot 2
// Stores the total tally of how much of `asset` there is
// to be used to mint rTHETA tokens
uint128 totalPending;
// Amount locked for scheduled withdrawals;
uint128 queuedWithdrawShares;
}
struct DepositReceipt {
// Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years.
uint16 round;
// Deposit amount, max 20,282,409,603,651 or 20 trillion ETH deposit
uint104 amount;
// Unredeemed shares balance
uint128 unredeemedShares;
}
struct Withdrawal {
// Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years.
uint16 round;
// Number of shares withdrawn
uint128 shares;
}
struct AuctionSellOrder {
// Amount of `asset` token offered in auction
uint96 sellAmount;
// Amount of oToken requested in auction
uint96 buyAmount;
// User Id of delta vault in latest gnosis auction
uint64 userId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {Vault} from "./Vault.sol";
library ShareMath {
using SafeMath for uint256;
uint256 internal constant PLACEHOLDER_UINT = 1;
function assetToShares(
uint256 assetAmount,
uint256 assetPerShare,
uint256 decimals
) internal pure returns (uint256) {
// If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet
// which should never happen.
// Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes.
require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare");
return assetAmount.mul(10**decimals).div(assetPerShare);
}
function sharesToAsset(
uint256 shares,
uint256 assetPerShare,
uint256 decimals
) internal pure returns (uint256) {
// If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet
// which should never happen.
// Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes.
require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare");
return shares.mul(assetPerShare).div(10**decimals);
}
/**
* @notice Returns the shares unredeemed by the user given their DepositReceipt
* @param depositReceipt is the user's deposit receipt
* @param currentRound is the `round` stored on the vault
* @param assetPerShare is the price in asset per share
* @param decimals is the number of decimals the asset/shares use
* @return unredeemedShares is the user's virtual balance of shares that are owed
*/
function getSharesFromReceipt(
Vault.DepositReceipt memory depositReceipt,
uint256 currentRound,
uint256 assetPerShare,
uint256 decimals
) internal pure returns (uint256 unredeemedShares) {
if (depositReceipt.round > 0 && depositReceipt.round < currentRound) {
uint256 sharesFromRound =
assetToShares(depositReceipt.amount, assetPerShare, decimals);
return
uint256(depositReceipt.unredeemedShares).add(sharesFromRound);
}
return depositReceipt.unredeemedShares;
}
function pricePerShare(
uint256 totalSupply,
uint256 totalBalance,
uint256 pendingAmount,
uint256 decimals
) internal pure returns (uint256) {
uint256 singleShare = 10**decimals;
return
totalSupply > 0
? singleShare.mul(totalBalance.sub(pendingAmount)).div(
totalSupply
)
: singleShare;
}
/************************************************
* HELPERS
***********************************************/
function assertUint104(uint256 num) internal pure {
require(num <= type(uint104).max, "Overflow uint104");
}
function assertUint128(uint256 num) internal pure {
require(num <= type(uint128).max, "Overflow uint128");
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
interface IStrikeSelection {
function getStrikePrice(uint256 expiryTimestamp, bool isPut)
external
view
returns (uint256, uint256);
function delta() external view returns (uint256);
}
interface IOptionsPremiumPricer {
function getPremium(
uint256 strikePrice,
uint256 timeToExpiry,
bool isPut
) external view returns (uint256);
function getPremiumInStables(
uint256 strikePrice,
uint256 timeToExpiry,
bool isPut
) external view returns (uint256);
function getOptionDelta(
uint256 spotPrice,
uint256 strikePrice,
uint256 volatility,
uint256 expiryTimestamp
) external view returns (uint256 delta);
function getUnderlyingPrice() external view returns (uint256);
function priceOracle() external view returns (address);
function volatilityOracle() external view returns (address);
function pool() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DSMath} from "../vendor/DSMath.sol";
import {IGnosisAuction} from "../interfaces/IGnosisAuction.sol";
import {IOtoken} from "../interfaces/GammaInterface.sol";
import {IOptionsPremiumPricer} from "../interfaces/IRibbon.sol";
import {Vault} from "./Vault.sol";
import {IRibbonThetaVault} from "../interfaces/IRibbonThetaVault.sol";
library GnosisAuction {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event InitiateGnosisAuction(
address indexed auctioningToken,
address indexed biddingToken,
uint256 auctionCounter,
address indexed manager
);
event PlaceAuctionBid(
uint256 auctionId,
address indexed auctioningToken,
uint256 sellAmount,
uint256 buyAmount,
address indexed bidder
);
struct AuctionDetails {
address oTokenAddress;
address gnosisEasyAuction;
address asset;
uint256 assetDecimals;
uint256 oTokenPremium;
uint256 duration;
}
struct BidDetails {
address oTokenAddress;
address gnosisEasyAuction;
address asset;
uint256 assetDecimals;
uint256 auctionId;
uint256 lockedBalance;
uint256 optionAllocation;
uint256 optionPremium;
address bidder;
}
function startAuction(AuctionDetails calldata auctionDetails)
internal
returns (uint256 auctionID)
{
uint256 oTokenSellAmount =
getOTokenSellAmount(auctionDetails.oTokenAddress);
IERC20(auctionDetails.oTokenAddress).safeApprove(
auctionDetails.gnosisEasyAuction,
IERC20(auctionDetails.oTokenAddress).balanceOf(address(this))
);
// minBidAmount is total oTokens to sell * premium per oToken
// shift decimals to correspond to decimals of USDC for puts
// and underlying for calls
uint256 minBidAmount =
DSMath.wmul(
oTokenSellAmount.mul(10**10),
auctionDetails.oTokenPremium
);
minBidAmount = auctionDetails.assetDecimals > 18
? minBidAmount.mul(10**(auctionDetails.assetDecimals.sub(18)))
: minBidAmount.div(
10**(uint256(18).sub(auctionDetails.assetDecimals))
);
require(
minBidAmount <= type(uint96).max,
"optionPremium * oTokenSellAmount > type(uint96) max value!"
);
uint256 auctionEnd = block.timestamp.add(auctionDetails.duration);
auctionID = IGnosisAuction(auctionDetails.gnosisEasyAuction)
.initiateAuction(
// address of oToken we minted and are selling
auctionDetails.oTokenAddress,
// address of asset we want in exchange for oTokens. Should match vault `asset`
auctionDetails.asset,
// orders can be cancelled at any time during the auction
auctionEnd,
// order will last for `duration`
auctionEnd,
// we are selling all of the otokens minus a fee taken by gnosis
uint96(oTokenSellAmount),
// the minimum we are willing to sell all the oTokens for. A discount is applied on black-scholes price
uint96(minBidAmount),
// the minimum bidding amount must be 1 * 10 ** -assetDecimals
1,
// the min funding threshold
0,
// no atomic closure
false,
// access manager contract
address(0),
// bytes for storing info like a whitelist for who can bid
bytes("")
);
emit InitiateGnosisAuction(
auctionDetails.oTokenAddress,
auctionDetails.asset,
auctionID,
msg.sender
);
}
function placeBid(BidDetails calldata bidDetails)
internal
returns (
uint256 sellAmount,
uint256 buyAmount,
uint64 userId
)
{
// calculate how much to allocate
sellAmount = bidDetails
.lockedBalance
.mul(bidDetails.optionAllocation)
.div(100 * Vault.OPTION_ALLOCATION_MULTIPLIER);
// divide the `asset` sellAmount by the target premium per oToken to
// get the number of oTokens to buy (8 decimals)
buyAmount = sellAmount
.mul(10**(bidDetails.assetDecimals.add(Vault.OTOKEN_DECIMALS)))
.div(bidDetails.optionPremium)
.div(10**bidDetails.assetDecimals);
require(
sellAmount <= type(uint96).max,
"sellAmount > type(uint96) max value!"
);
require(
buyAmount <= type(uint96).max,
"buyAmount > type(uint96) max value!"
);
// approve that amount
IERC20(bidDetails.asset).safeApprove(
bidDetails.gnosisEasyAuction,
sellAmount
);
uint96[] memory _minBuyAmounts = new uint96[](1);
uint96[] memory _sellAmounts = new uint96[](1);
bytes32[] memory _prevSellOrders = new bytes32[](1);
_minBuyAmounts[0] = uint96(buyAmount);
_sellAmounts[0] = uint96(sellAmount);
_prevSellOrders[
0
] = 0x0000000000000000000000000000000000000000000000000000000000000001;
// place sell order with that amount
userId = IGnosisAuction(bidDetails.gnosisEasyAuction).placeSellOrders(
bidDetails.auctionId,
_minBuyAmounts,
_sellAmounts,
_prevSellOrders,
"0x"
);
emit PlaceAuctionBid(
bidDetails.auctionId,
bidDetails.oTokenAddress,
sellAmount,
buyAmount,
bidDetails.bidder
);
return (sellAmount, buyAmount, userId);
}
function claimAuctionOtokens(
Vault.AuctionSellOrder calldata auctionSellOrder,
address gnosisEasyAuction,
address counterpartyThetaVault
) internal {
bytes32 order =
encodeOrder(
auctionSellOrder.userId,
auctionSellOrder.buyAmount,
auctionSellOrder.sellAmount
);
bytes32[] memory orders = new bytes32[](1);
orders[0] = order;
IGnosisAuction(gnosisEasyAuction).claimFromParticipantOrder(
IRibbonThetaVault(counterpartyThetaVault).optionAuctionID(),
orders
);
}
function getOTokenSellAmount(address oTokenAddress)
internal
view
returns (uint256)
{
// We take our current oToken balance. That will be our sell amount
// but otokens will be transferred to gnosis.
uint256 oTokenSellAmount =
IERC20(oTokenAddress).balanceOf(address(this));
require(
oTokenSellAmount <= type(uint96).max,
"oTokenSellAmount > type(uint96) max value!"
);
return oTokenSellAmount;
}
function getOTokenPremium(
address oTokenAddress,
address optionsPremiumPricer,
uint256 premiumDiscount
) internal view returns (uint256) {
IOtoken newOToken = IOtoken(oTokenAddress);
IOptionsPremiumPricer premiumPricer =
IOptionsPremiumPricer(optionsPremiumPricer);
// Apply black-scholes formula (from rvol library) to option given its features
// and get price for 100 contracts denominated in the underlying asset for call option
// and USDC for put option
uint256 optionPremium =
premiumPricer.getPremium(
newOToken.strikePrice(),
newOToken.expiryTimestamp(),
newOToken.isPut()
);
// Apply a discount to incentivize arbitraguers
optionPremium = optionPremium.mul(premiumDiscount).div(
100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER
);
require(
optionPremium <= type(uint96).max,
"optionPremium > type(uint96) max value!"
);
return optionPremium;
}
function getOTokenPremiumInStables(
address oTokenAddress,
address optionsPremiumPricer,
uint256 premiumDiscount
) internal view returns (uint256) {
IOtoken newOToken = IOtoken(oTokenAddress);
IOptionsPremiumPricer premiumPricer =
IOptionsPremiumPricer(optionsPremiumPricer);
// Apply black-scholes formula (from rvol library) to option given its features
// and get price for 100 contracts denominated USDC for both call and put options
uint256 optionPremium =
premiumPricer.getPremiumInStables(
newOToken.strikePrice(),
newOToken.expiryTimestamp(),
newOToken.isPut()
);
// Apply a discount to incentivize arbitraguers
optionPremium = optionPremium.mul(premiumDiscount).div(
100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER
);
require(
optionPremium <= type(uint96).max,
"optionPremium > type(uint96) max value!"
);
return optionPremium;
}
function encodeOrder(
uint64 userId,
uint96 buyAmount,
uint96 sellAmount
) internal pure returns (bytes32) {
return
bytes32(
(uint256(userId) << 192) +
(uint256(buyAmount) << 96) +
uint256(sellAmount)
);
}
}
// SPDX-License-Identifier: MIT
// Source: https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
// ----------------------------------------------------------------------------
pragma solidity =0.8.4;
library DateTime {
uint256 constant SECONDS_PER_DAY = 24 * 60 * 60;
uint256 constant SECONDS_PER_HOUR = 60 * 60;
uint256 constant SECONDS_PER_MINUTE = 60;
int256 constant OFFSET19700101 = 2440588;
uint256 constant DOW_MON = 1;
uint256 constant DOW_TUE = 2;
uint256 constant DOW_WED = 3;
uint256 constant DOW_THU = 4;
uint256 constant DOW_FRI = 5;
uint256 constant DOW_SAT = 6;
uint256 constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(
uint256 year,
uint256 month,
uint256 day
) internal pure returns (uint256 _days) {
require(year >= 1970);
int256 _year = int256(year);
int256 _month = int256(month);
int256 _day = int256(day);
int256 __days =
_day -
32075 +
(1461 * (_year + 4800 + (_month - 14) / 12)) /
4 +
(367 * (_month - 2 - ((_month - 14) / 12) * 12)) /
12 -
(3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /
4 -
OFFSET19700101;
_days = uint256(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint256 _days)
internal
pure
returns (
uint256 year,
uint256 month,
uint256 day
)
{
int256 __days = int256(_days);
int256 L = __days + 68569 + OFFSET19700101;
int256 N = (4 * L) / 146097;
L = L - (146097 * N + 3) / 4;
int256 _year = (4000 * (L + 1)) / 1461001;
L = L - (1461 * _year) / 4 + 31;
int256 _month = (80 * L) / 2447;
int256 _day = L - (2447 * _month) / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint256(_year);
month = uint256(_month);
day = uint256(_day);
}
function isLeapYear(uint256 timestamp)
internal
pure
returns (bool leapYear)
{
(uint256 year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint256 year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function getDaysInMonth(uint256 timestamp)
internal
pure
returns (uint256 daysInMonth)
{
(uint256 year, uint256 month, ) =
_daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint256 year, uint256 month)
internal
pure
returns (uint256 daysInMonth)
{
if (
month == 1 ||
month == 3 ||
month == 5 ||
month == 7 ||
month == 8 ||
month == 10 ||
month == 12
) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint256 timestamp)
internal
pure
returns (uint256 dayOfWeek)
{
uint256 _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = ((_days + 3) % 7) + 1;
}
function getYear(uint256 timestamp) internal pure returns (uint256 year) {
(year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint256 timestamp) internal pure returns (uint256 month) {
(, month, ) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint256 timestamp) internal pure returns (uint256 day) {
(, , day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampFromDate(
uint256 year,
uint256 month,
uint256 day
) internal pure returns (uint256 timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
/**
* @notice Gets the Friday of the same week
* @param timestamp is the given date and time
* @return the Friday of the same week in unix time
*/
function getThisWeekFriday(uint256 timestamp)
internal
pure
returns (uint256)
{
return timestamp + 5 days - getDayOfWeek(timestamp) * 1 days;
}
/**
* @notice Gets the next friday after the given date and time
* @param timestamp is the given date and time
* @return the next friday after the given date and time
*/
function getNextFriday(uint256 timestamp) internal pure returns (uint256) {
uint256 friday = getThisWeekFriday(timestamp);
return friday >= timestamp ? friday : friday + 1 weeks;
}
/**
* @notice Gets the last day of the month
* @param timestamp is the given date and time
* @return the last day of the same month in unix time
*/
function getLastDayOfMonth(uint256 timestamp)
internal
pure
returns (uint256)
{
return
timestampFromDate(getYear(timestamp), getMonth(timestamp) + 1, 1) -
1 days;
}
/**
* @notice Gets the last Friday of the month
* @param timestamp is the given date and time
* @return the last Friday of the same month in unix time
*/
function getMonthLastFriday(uint256 timestamp)
internal
pure
returns (uint256)
{
uint256 lastDay = getLastDayOfMonth(timestamp);
uint256 friday = getThisWeekFriday(lastDay);
return friday > lastDay ? friday - 1 weeks : friday;
}
/**
* @notice Gets the last Friday of the quarter
* @param timestamp is the given date and time
* @return the last Friday of the quarter in unix time
*/
function getQuarterLastFriday(uint256 timestamp)
internal
pure
returns (uint256)
{
uint256 month = getMonth(timestamp);
uint256 quarterMonth =
(month <= 3) ? 3 : (month <= 6) ? 6 : (month <= 9) ? 9 : 12;
uint256 quarterDate =
timestampFromDate(getYear(timestamp), quarterMonth, 1);
return getMonthLastFriday(quarterDate);
}
/**
* @notice Gets the last Friday of the half-year
* @param timestamp is the given date and time
* @return the last friday of the half-year
*/
function getBiannualLastFriday(uint256 timestamp)
internal
pure
returns (uint256)
{
uint256 month = getMonth(timestamp);
uint256 biannualMonth = (month <= 6) ? 6 : 12;
uint256 biannualDate =
timestampFromDate(getYear(timestamp), biannualMonth, 1);
return getMonthLastFriday(biannualDate);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
library GammaTypes {
// vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults.
struct Vault {
// addresses of oTokens a user has shorted (i.e. written) against this vault
address[] shortOtokens;
// addresses of oTokens a user has bought and deposited in this vault
// user can be long oTokens without opening a vault (e.g. by buying on a DEX)
// generally, long oTokens will be 'deposited' in vaults to act as collateral
// in order to write oTokens against (i.e. in spreads)
address[] longOtokens;
// addresses of other ERC-20s a user has deposited as collateral in this vault
address[] collateralAssets;
// quantity of oTokens minted/written for each oToken address in shortOtokens
uint256[] shortAmounts;
// quantity of oTokens owned and held in the vault for each oToken address in longOtokens
uint256[] longAmounts;
// quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets
uint256[] collateralAmounts;
}
}
interface IOtoken {
function underlyingAsset() external view returns (address);
function strikeAsset() external view returns (address);
function collateralAsset() external view returns (address);
function strikePrice() external view returns (uint256);
function expiryTimestamp() external view returns (uint256);
function isPut() external view returns (bool);
}
interface IOtokenFactory {
function getOtoken(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external view returns (address);
function createOtoken(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external returns (address);
function getTargetOtokenAddress(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external view returns (address);
event OtokenCreated(
address tokenAddress,
address creator,
address indexed underlying,
address indexed strike,
address indexed collateral,
uint256 strikePrice,
uint256 expiry,
bool isPut
);
}
interface IController {
// possible actions that can be performed
enum ActionType {
OpenVault,
MintShortOption,
BurnShortOption,
DepositLongOption,
WithdrawLongOption,
DepositCollateral,
WithdrawCollateral,
SettleVault,
Redeem,
Call,
Liquidate
}
struct ActionArgs {
// type of action that is being performed on the system
ActionType actionType;
// address of the account owner
address owner;
// address which we move assets from or to (depending on the action type)
address secondAddress;
// asset that is to be transfered
address asset;
// index of the vault that is to be modified (if any)
uint256 vaultId;
// amount of asset that is to be transfered
uint256 amount;
// each vault can hold multiple short / long / collateral assets
// but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// any other data that needs to be passed in for arbitrary function calls
bytes data;
}
struct RedeemArgs {
// address to which we pay out the oToken proceeds
address receiver;
// oToken that is to be redeemed
address otoken;
// amount of oTokens that is to be redeemed
uint256 amount;
}
function getPayout(address _otoken, uint256 _amount)
external
view
returns (uint256);
function operate(ActionArgs[] calldata _actions) external;
function getAccountVaultCounter(address owner)
external
view
returns (uint256);
function oracle() external view returns (address);
function getVault(address _owner, uint256 _vaultId)
external
view
returns (GammaTypes.Vault memory);
function getProceed(address _owner, uint256 _vaultId)
external
view
returns (uint256);
function isSettlementAllowed(
address _underlying,
address _strike,
address _collateral,
uint256 _expiry
) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IERC20Detailed is IERC20 {
function decimals() external view returns (uint8);
function symbol() external view returns (string calldata);
function name() external view returns (string calldata);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
library AuctionType {
struct AuctionData {
IERC20 auctioningToken;
IERC20 biddingToken;
uint256 orderCancellationEndDate;
uint256 auctionEndDate;
bytes32 initialAuctionOrder;
uint256 minimumBiddingAmountPerOrder;
uint256 interimSumBidAmount;
bytes32 interimOrder;
bytes32 clearingPriceOrder;
uint96 volumeClearingPriceOrder;
bool minFundingThresholdNotReached;
bool isAtomicClosureAllowed;
uint256 feeNumerator;
uint256 minFundingThreshold;
}
}
interface IGnosisAuction {
function initiateAuction(
address _auctioningToken,
address _biddingToken,
uint256 orderCancellationEndDate,
uint256 auctionEndDate,
uint96 _auctionedSellAmount,
uint96 _minBuyAmount,
uint256 minimumBiddingAmountPerOrder,
uint256 minFundingThreshold,
bool isAtomicClosureAllowed,
address accessManagerContract,
bytes memory accessManagerContractData
) external returns (uint256);
function auctionCounter() external view returns (uint256);
function auctionData(uint256 auctionId)
external
view
returns (AuctionType.AuctionData memory);
function auctionAccessManager(uint256 auctionId)
external
view
returns (address);
function auctionAccessData(uint256 auctionId)
external
view
returns (bytes memory);
function FEE_DENOMINATOR() external view returns (uint256);
function feeNumerator() external view returns (uint256);
function settleAuction(uint256 auctionId) external returns (bytes32);
function placeSellOrders(
uint256 auctionId,
uint96[] memory _minBuyAmounts,
uint96[] memory _sellAmounts,
bytes32[] memory _prevSellOrders,
bytes calldata allowListCallData
) external returns (uint64);
function claimFromParticipantOrder(
uint256 auctionId,
bytes32[] memory orders
) external returns (uint256, uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* This library supports ERC20s that have quirks in their behavior.
* One such ERC20 is USDT, which requires allowance to be 0 before calling approve.
* We plan to update this library with ERC20s that display such idiosyncratic behavior.
*/
library SupportsNonCompliantERC20 {
address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
function safeApproveNonCompliant(
IERC20 token,
address spender,
uint256 amount
) internal {
if (address(token) == USDT) {
SafeERC20.safeApprove(token, spender, 0);
}
SafeERC20.safeApprove(token, spender, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
/// math.sol -- mixin for inline numerical wizardry
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >0.4.13;
library DSMath {
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");
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
//rounds to zero if x*y < WAD / 2
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
//rounds to zero if x*y < WAD / 2
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
//rounds to zero if x*y < WAD / 2
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
//rounds to zero if x*y < RAY / 2
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {Vault} from "../libraries/Vault.sol";
interface IRibbonThetaVault {
function currentOption() external view returns (address);
function nextOption() external view returns (address);
function vaultParams() external view returns (Vault.VaultParams memory);
function vaultState() external view returns (Vault.VaultState memory);
function optionState() external view returns (Vault.OptionState memory);
function optionAuctionID() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
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);
}
}
}
}
|
If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet which should never happen. Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes.
|
function sharesToAsset(
uint256 shares,
uint256 assetPerShare,
uint256 decimals
) internal pure returns (uint256) {
require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare");
return shares.mul(assetPerShare).div(10**decimals);
}
| 584,011
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol";
import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol";
import "@pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "./interface/IVBNB.sol";
import "./interface/CompleteVToken.sol";
import "../../lib/@harvest-finance/hardworkInterface/IStrategy.sol";
import "./interface/WBNB.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
contract VenusInteractorInitializable is Initializable, ReentrancyGuardUpgradeable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
IBEP20 public underlyingToken;
address payable public _wbnb;
CompleteVToken public vtoken;
ComptrollerInterface public comptroller;
constructor() public {
}
function initialize(
address _underlying,
address _vtoken,
address _comptroller
) public initializer {
__ReentrancyGuard_init();
// Comptroller:
comptroller = ComptrollerInterface(_comptroller);
underlyingToken = IBEP20(_underlying);
_wbnb = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c;
vtoken = CompleteVToken(_vtoken);
// Enter the market
address[] memory vTokens = new address[](1);
vTokens[0] = _vtoken;
comptroller.enterMarkets(vTokens);
}
/**
* Supplies BNB to Venus
* Unwraps WBNB to BNB, then invoke the special mint for vBNB
* We ask to supply "amount", if the "amount" we asked to supply is
* more than balance (what we really have), then only supply balance.
* If we the "amount" we want to supply is less than balance, then
* only supply that amount.
*/
function _supplyBNBInWBNB(uint256 amountInWBNB) internal nonReentrant {
// underlyingToken here is WBNB
uint256 balance = underlyingToken.balanceOf(address(this)); // supply at most "balance"
if (amountInWBNB < balance) {
balance = amountInWBNB; // only supply the "amount" if its less than what we have
}
WBNB wbnb = WBNB(payable(address(_wbnb)));
wbnb.withdraw(balance); // Unwrapping
IVBNB(address(vtoken)).mint.value(balance)();
}
/**
* Redeems BNB from Venus
* receives BNB. Wrap all the BNB that is in this contract.
*/
function _redeemBNBInvTokens(uint256 amountVTokens) internal nonReentrant {
_redeemInVTokens(amountVTokens);
WBNB wbnb = WBNB(payable(address(_wbnb)));
wbnb.deposit.value(address(this).balance)();
}
/**
* Supplies to Venus
*/
function _supply(uint256 amount) internal returns(uint256) {
uint256 balance = underlyingToken.balanceOf(address(this));
if (amount < balance) {
balance = amount;
}
underlyingToken.safeApprove(address(vtoken), 0);
underlyingToken.safeApprove(address(vtoken), balance);
uint256 mintResult = vtoken.mint(balance);
require(mintResult == 0, "Supplying failed");
return balance;
}
/**
* Borrows against the collateral
*/
function _borrow(uint256 amountUnderlying) internal {
// Borrow, check the balance for this contract's address
uint256 result = vtoken.borrow(amountUnderlying);
require(result == 0, "Borrow failed");
}
/**
* Borrows against the collateral
*/
function _borrowInWBNB(uint256 amountUnderlying) internal {
// Borrow BNB, wraps into WBNB
uint256 result = vtoken.borrow(amountUnderlying);
require(result == 0, "Borrow failed");
WBNB wbnb = WBNB(payable(address(_wbnb)));
wbnb.deposit.value(address(this).balance)();
}
/**
* Repays a loan
*/
function _repay(uint256 amountUnderlying) internal {
underlyingToken.safeApprove(address(vtoken), 0);
underlyingToken.safeApprove(address(vtoken), amountUnderlying);
vtoken.repayBorrow(amountUnderlying);
underlyingToken.safeApprove(address(vtoken), 0);
}
/**
* Repays a loan in BNB
*/
function _repayInWBNB(uint256 amountUnderlying) internal {
WBNB wbnb = WBNB(payable(address(_wbnb)));
wbnb.withdraw(amountUnderlying); // Unwrapping
IVBNB(address(vtoken)).repayBorrow.value(amountUnderlying)();
}
/**
* Redeem liquidity in vTokens
*/
function _redeemInVTokens(uint256 amountVTokens) internal {
if(amountVTokens > 0){
vtoken.redeem(amountVTokens);
}
}
/**
* Redeem liquidity in underlying
*/
function _redeemUnderlying(uint256 amountUnderlying) internal {
if (amountUnderlying > 0) {
vtoken.redeemUnderlying(amountUnderlying);
}
}
/**
* Redeem liquidity in underlying
*/
function redeemUnderlyingInWBNB(uint256 amountUnderlying) internal {
if (amountUnderlying > 0) {
_redeemUnderlying(amountUnderlying);
WBNB wbnb = WBNB(payable(address(_wbnb)));
wbnb.deposit.value(address(this).balance)();
}
}
/**
* Get XVS
*/
function claimVenus() public {
comptroller.claimVenus(address(this));
}
/**
* Redeem the minimum of the WBNB we own, and the WBNB that the vToken can
* immediately retrieve. Ensures that `redeemMaximum` doesn't fail silently
*/
function redeemMaximumWBNB() internal {
// amount of WBNB in contract
uint256 available = vtoken.getCash();
// amount of WBNB we own
uint256 owned = vtoken.balanceOfUnderlying(address(this));
// redeem the most we can redeem
redeemUnderlyingInWBNB(available < owned ? available : owned);
}
function redeemMaximumWithLoan(uint256 collateralFactorNumerator, uint256 collateralFactorDenominator, uint256 borrowMinThreshold) internal {
// amount of liquidity in Venus
uint256 available = vtoken.getCash();
// amount we supplied
uint256 supplied = vtoken.balanceOfUnderlying(address(this));
// amount we borrowed
uint256 borrowed = vtoken.borrowBalanceCurrent(address(this));
while (borrowed > borrowMinThreshold) {
uint256 requiredCollateral = borrowed
.mul(collateralFactorDenominator)
.add(collateralFactorNumerator.div(2))
.div(collateralFactorNumerator);
// redeem just as much as needed to repay the loan
uint256 wantToRedeem = supplied.sub(requiredCollateral);
_redeemUnderlying(SafeMath.min(wantToRedeem, available));
// now we can repay our borrowed amount
uint256 balance = underlyingToken.balanceOf(address(this));
_repay(SafeMath.min(borrowed, balance));
// update the parameters
available = vtoken.getCash();
borrowed = vtoken.borrowBalanceCurrent(address(this));
supplied = vtoken.balanceOfUnderlying(address(this));
}
// redeem the most we can redeem
_redeemUnderlying(SafeMath.min(available, supplied));
}
function redeemMaximumWBNBWithLoan(uint256 collateralFactorNumerator, uint256 collateralFactorDenominator, uint256 borrowMinThreshold) internal {
// amount of liquidity in Venus
uint256 available = vtoken.getCash();
// amount of WBNB we supplied
uint256 supplied = vtoken.balanceOfUnderlying(address(this));
// amount of WBNB we borrowed
uint256 borrowed = vtoken.borrowBalanceCurrent(address(this));
while (borrowed > borrowMinThreshold) {
uint256 requiredCollateral = borrowed
.mul(collateralFactorDenominator)
.add(collateralFactorNumerator.div(2))
.div(collateralFactorNumerator);
// redeem just as much as needed to repay the loan
uint256 wantToRedeem = supplied.sub(requiredCollateral);
redeemUnderlyingInWBNB(SafeMath.min(wantToRedeem, available));
// now we can repay our borrowed amount
uint256 balance = underlyingToken.balanceOf(address(this));
_repayInWBNB(SafeMath.min(borrowed, balance));
// update the parameters
available = vtoken.getCash();
borrowed = vtoken.borrowBalanceCurrent(address(this));
supplied = vtoken.balanceOfUnderlying(address(this));
}
// redeem the most we can redeem
redeemUnderlyingInWBNB(SafeMath.min(available, supplied));
}
function getLiquidity() external view returns(uint256) {
return vtoken.getCash();
}
function redeemMaximumToken() internal {
// amount of tokens in vtoken
uint256 available = vtoken.getCash();
// amount of tokens we own
uint256 owned = vtoken.balanceOfUnderlying(address(this));
// redeem the most we can redeem
_redeemUnderlying(available < owned ? available : owned);
}
receive() external payable {} // this is needed for the WBNB unwrapping
}
|
Redeem the minimum of the WBNB we own, and the WBNB that the vToken can immediately retrieve. Ensures that `redeemMaximum` doesn't fail silently/ amount of WBNB in contract amount of WBNB we own redeem the most we can redeem
|
function redeemMaximumWBNB() internal {
uint256 available = vtoken.getCash();
uint256 owned = vtoken.balanceOfUnderlying(address(this));
redeemUnderlyingInWBNB(available < owned ? available : owned);
}
| 1,037,916
|
./full_match/1/0x4f4fFE6f397F5BC985F4dc1EB5a0eB2D9B93D12D/sources/contracts/V3/LandingPage.sol
|
Allows users to buy tokens with USDT without specifying an inviting address. _usdtAmount The amount of USDT to spend on tokens.
|
function buyWithUsdt(uint256 _usdtAmount) external {
_buyWithUsdt(_usdtAmount, false);
}
| 3,146,069
|
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @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: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {IScaledBalanceToken} from './IScaledBalanceToken.sol';
interface IAToken is IERC20, IScaledBalanceToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param value The amount being
* @param index The new liquidity index of the reserve
**/
event Mint(address indexed from, uint256 value, uint256 index);
/**
* @dev Mints `amount` aTokens to `user`
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted after aTokens are burned
* @param from The owner of the aTokens, getting them burned
* @param target The address that will receive the underlying
* @param value The amount being burned
* @param index The new liquidity index of the reserve
**/
event Burn(address indexed from, address indexed target, uint256 value, uint256 index);
/**
* @dev Emitted during the transfer action
* @param from The user whose tokens are being transferred
* @param to The recipient
* @param value The amount being transferred
* @param index The new liquidity index of the reserve
**/
event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);
/**
* @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* @param user The owner of the aTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external;
/**
* @dev Mints aTokens to the reserve treasury
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external;
/**
* @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken
* @param from The address getting liquidated, current owner of the aTokens
* @param to The recipient
* @param value The amount of tokens getting transferred
**/
function transferOnLiquidation(
address from,
address to,
uint256 value
) external;
/**
* @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param user The recipient of the aTokens
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
interface ILendingPool {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
* @param amount The amount deposited
* @param referral The referral code used
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
* initiator of the transaction on flashLoan()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
* @param borrowRate The numeric rate at which the user has borrowed
* @param referral The referral code used
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on swapBorrowRateMode()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user swapping his rate mode
* @param rateMode The rate mode that the user wants to swap to
**/
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on rebalanceStableBorrowRate()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user for which the rebalance has been executed
**/
event RebalanceStableBorrowRate(address indexed reserve, address indexed user);
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param asset The address of the asset being flash borrowed
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
* @param referralCode The referral code used
**/
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint16 referralCode
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
* LendingPoolCollateral manager using a DELEGATECALL
* This allows to have the events in the generated ABI for LendingPool.
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
* @param liquidator The address of the liquidator
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external returns (uint256);
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function initReserve(
address reserve,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress)
external;
function setConfiguration(address reserve, uint256 configuration) external;
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset)
external
view
returns (DataTypes.ReserveConfigurationMap memory);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user)
external
view
returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromAfter,
uint256 balanceToBefore
) external;
function getReservesList() external view returns (address[] memory);
function getAddressesProvider() external view returns (ILendingPoolAddressesProvider);
function setPause(bool val) external;
function paused() external view returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title LendingPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Aave Governance
* @author Aave
**/
interface ILendingPoolAddressesProvider {
event MarketIdSet(string newMarketId);
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function getMarketId() external view returns (string memory);
function setMarketId(string calldata marketId) external;
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title LendingPoolAddressesProviderRegistry contract
* @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets
* - Used for indexing purposes of Aave protocol's markets
* - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with,
* for example with `0` for the Aave main market and `1` for the next created
* @author Aave
**/
interface ILendingPoolAddressesProviderRegistry {
event AddressesProviderRegistered(address indexed newAddress);
event AddressesProviderUnregistered(address indexed newAddress);
function getAddressesProvidersList() external view returns (address[] memory);
function getAddressesProviderIdByAddress(address addressesProvider)
external
view
returns (uint256);
function registerAddressesProvider(address provider, uint256 id) external;
function unregisterAddressesProvider(address provider) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.4.0;
import "./external/openzeppelin/OpenZeppelinSafeMath_V3_3_0.sol";
/**
* @author Brendan Asselstine
* @notice Provides basic fixed point math calculations.
*
* This library calculates integer fractions by scaling values by 1e18 then performing standard integer math.
*/
library FixedPoint {
using OpenZeppelinSafeMath_V3_3_0 for uint256;
// The scale to use for fixed point numbers. Same as Ether for simplicity.
uint256 internal constant SCALE = 1e18;
/**
* Calculates a Fixed18 mantissa given the numerator and denominator
*
* The mantissa = (numerator * 1e18) / denominator
*
* @param numerator The mantissa numerator
* @param denominator The mantissa denominator
* @return The mantissa of the fraction
*/
function calculateMantissa(uint256 numerator, uint256 denominator) internal pure returns (uint256) {
uint256 mantissa = numerator.mul(SCALE);
mantissa = mantissa.div(denominator);
return mantissa;
}
/**
* Multiplies a Fixed18 number by an integer.
*
* @param b The whole integer to multiply
* @param mantissa The Fixed18 number
* @return An integer that is the result of multiplying the params.
*/
function multiplyUintByMantissa(uint256 b, uint256 mantissa) internal pure returns (uint256) {
uint256 result = mantissa.mul(b);
result = result.div(SCALE);
return result;
}
/**
* Divides an integer by a fixed point 18 mantissa
*
* @param dividend The integer to divide
* @param mantissa The fixed point 18 number to serve as the divisor
* @return An integer that is the result of dividing an integer by a fixed point 18 mantissa
*/
function divideUintByMantissa(uint256 dividend, uint256 mantissa) internal pure returns (uint256) {
uint256 result = SCALE.mul(dividend);
result = result.div(mantissa);
return result;
}
}
// SPDX-License-Identifier: MIT
// NOTE: Copied from OpenZeppelin Contracts version 3.3.0
pragma solidity >=0.4.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 OpenZeppelinSafeMath_V3_3_0 {
/**
* @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.4.0 <0.8.0;
/// @title Defines the functions used to interact with a yield source. The Prize Pool inherits this contract.
/// @notice Prize Pools subclasses need to implement this interface so that yield can be generated.
interface IYieldSource {
/// @notice Returns the ERC20 asset token used for deposits.
/// @return The ERC20 asset token
function depositToken() external view returns (address);
/// @notice Returns the total balance (in asset tokens). This includes the deposits and interest.
/// @return The underlying balance of asset tokens
function balanceOfToken(address addr) external returns (uint256);
/// @notice Supplies tokens to the yield source. Allows assets to be supplied on other user's behalf using the `to` param.
/// @param amount The amount of `token()` to be supplied
/// @param to The user whose balance will receive the tokens
function supplyTokenTo(uint256 amount, address to) external;
/// @notice Redeems tokens from the yield source.
/// @param amount The amount of `token()` to withdraw. Denominated in `token()` as above.
/// @return The actual amount of tokens that were redeemed.
function redeemToken(uint256 amount) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
/**
* @title Abstract ownable contract with additional assetManager role
* @notice Contract module based on Ownable which provides a basic access control mechanism, where
* there is an account (an asset manager) that can be granted exclusive access to
* specific functions.
*
* The asset manager account needs to be set using {setAssetManager}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyAssetManager`, which can be applied to your functions to restrict their use to
* the asset manager.
*/
abstract contract AssetManager is ContextUpgradeable, OwnableUpgradeable {
address private _assetManager;
/**
* @dev Emitted when the _assetManager has been changed
* @param previousAssetManager address of the former _assetManager
* @param newAssetManager address of the new _assetManager
*/
event AssetManagerTransferred(address indexed previousAssetManager, address indexed newAssetManager);
/**
* @notice Gets the current _assetManager
* @dev Returns the address of the current asset manager.
* @return The address of the current _assetManager
*/
function assetManager() public view virtual returns (address) {
return _assetManager;
}
/**
* @dev Throws if called by any account other than the owner or asset manager.
*/
modifier onlyOwnerOrAssetManager() {
require(assetManager() == _msgSender() || owner() == _msgSender(), "onlyOwnerOrAssetManager: caller is not owner or asset manager");
_;
}
/**
* @notice Set the initial asset manager
* @dev Throws if called by any account other than the owner.
* @param newAssetManager The address of the desired new _assetManager
* @return Boolean to indicate if the operation was successful or not
*/
function setAssetManager(address newAssetManager) public virtual onlyOwner returns (bool) {
_assetManager = newAssetManager;
emit AssetManagerTransferred(address(0), newAssetManager);
return true;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "@aave/protocol-v2/contracts/interfaces/IAToken.sol";
interface ATokenInterface is IAToken {
/**
* @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)
**/
/* solhint-disable-next-line func-name-mixedcase */
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@pooltogether/yield-source-interface/contracts/IYieldSource.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/// @title The interface used for all Yield Sources for the PoolTogether protocol
/// @dev There are two privileged roles: the owner and the asset manager. The owner can configure the asset managers.
interface IProtocolYieldSource is IYieldSource {
/// @notice Allows the owner to transfer ERC20 tokens held by this contract to the target address.
/// @dev This function is callable by the owner or asset manager.
/// This function should not be able to transfer any tokens that represent user deposits.
/// @param token The ERC20 token to transfer
/// @param to The recipient of the tokens
/// @param amount The amount of tokens to transfer
function transferERC20(IERC20Upgradeable token, address to, uint256 amount) external;
/// @notice Allows someone to deposit into the yield source without receiving any shares. The deposited token will be the same as token()
/// This allows anyone to distribute tokens among the share holders.
function sponsor(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@aave/protocol-v2/contracts/interfaces/ILendingPool.sol";
import "@aave/protocol-v2/contracts/interfaces/ILendingPoolAddressesProvider.sol";
import "@aave/protocol-v2/contracts/interfaces/ILendingPoolAddressesProviderRegistry.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@pooltogether/fixed-point/contracts/FixedPoint.sol";
import "../access/AssetManager.sol";
import "../external/aave/ATokenInterface.sol";
import "../interfaces/IProtocolYieldSource.sol";
/// @title Aave Yield Source integration contract, implementing PoolTogether's generic yield source interface
/// @dev This contract inherits from the ERC20 implementation to keep track of users deposits
/// @dev This contract inherits AssetManager which extends OwnableUpgradable
/// @notice Yield source for a PoolTogether prize pool that generates yield by depositing into Aave V2
contract ATokenYieldSource is ERC20Upgradeable, IProtocolYieldSource, AssetManager, ReentrancyGuardUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @notice Emitted when the yield source is initialized
event ATokenYieldSourceInitialized(
IAToken indexed aToken,
ILendingPoolAddressesProviderRegistry lendingPoolAddressesProviderRegistry,
uint8 decimals,
string name,
string symbol,
address owner
);
/// @notice Emitted when asset tokens are redeemed from the yield source
event RedeemedToken(
address indexed from,
uint256 shares,
uint256 amount
);
/// @notice Emitted when asset tokens are supplied to the yield source
event SuppliedTokenTo(
address indexed from,
uint256 shares,
uint256 amount,
address indexed to
);
/// @notice Emitted when asset tokens are supplied to sponsor the yield source
event Sponsored(
address indexed from,
uint256 amount
);
/// @notice Emitted when ERC20 tokens other than yield source's aToken are withdrawn from the yield source
event TransferredERC20(
address indexed from,
address indexed to,
uint256 amount,
IERC20Upgradeable indexed token
);
/// @notice Interface for the yield-bearing Aave aToken
ATokenInterface public aToken;
/// @notice Interface for Aave lendingPoolAddressesProviderRegistry
ILendingPoolAddressesProviderRegistry public lendingPoolAddressesProviderRegistry;
/// @notice Mock Initializer to prevent
function freeze() public initializer {
//no-op
}
/// @notice Initializes the yield source with Aave aToken
/// @param _aToken Aave aToken address
/// @param _lendingPoolAddressesProviderRegistry Aave lendingPoolAddressesProviderRegistry address
/// @param _decimals Number of decimals the shares (inhereted ERC20) will have. Set as same as underlying asset to ensure sane ExchangeRates
/// @param _symbol Token symbol for the underlying shares ERC20
/// @param _name Token name for the underlying shares ERC20
function initialize(
ATokenInterface _aToken,
ILendingPoolAddressesProviderRegistry _lendingPoolAddressesProviderRegistry,
uint8 _decimals,
string calldata _symbol,
string calldata _name,
address _owner
)
public
initializer
returns (bool)
{
aToken = _aToken;
lendingPoolAddressesProviderRegistry = _lendingPoolAddressesProviderRegistry;
__Ownable_init();
transferOwnership(_owner);
__ERC20_init(_name,_symbol);
require(_decimals > 0, "ATokenYieldSource/decimals-gt-zero");
_setupDecimals(_decimals);
emit ATokenYieldSourceInitialized (
_aToken,
_lendingPoolAddressesProviderRegistry,
_decimals,
_name,
_symbol,
_owner
);
return true;
}
/// @notice Returns the ERC20 asset token used for deposits
/// @return The ERC20 asset token address
function depositToken() public view override returns (address) {
return _tokenAddress();
}
/// @notice Returns the underlying asset token address
/// @return Underlying asset token address
function _tokenAddress() internal view returns (address) {
return aToken.UNDERLYING_ASSET_ADDRESS();
}
/// @notice Returns user total balance (in asset tokens). This includes the deposits and interest.
/// @param addr User address
/// @return The underlying balance of asset tokens
function balanceOfToken(address addr) external override returns (uint256) {
return _sharesToToken(balanceOf(addr));
}
/// @notice Calculates the number of shares that should be mint or burned when a user deposit or withdraw
/// @param tokens Amount of tokens
/// @return Number of shares
function _tokenToShares(uint256 tokens) internal view returns (uint256) {
uint256 shares = 0;
if (totalSupply() == 0) {
shares = tokens;
} else {
// rate = tokens / shares
// shares = tokens * (totalShares / yieldSourceTotalSupply)
uint256 exchangeMantissa = FixedPoint.calculateMantissa(totalSupply(), aToken.balanceOf(address(this)));
shares = FixedPoint.multiplyUintByMantissa(tokens, exchangeMantissa);
}
return shares;
}
/// @notice Calculates the number of tokens a user has in the yield source
/// @param shares Amount of shares
/// @return Number of tokens
function _sharesToToken(uint256 shares) internal view returns (uint256) {
uint256 tokens = 0;
if (totalSupply() == 0) {
tokens = shares;
} else {
// tokens = shares * (yieldSourceTotalSupply / totalShares)
uint256 exchangeMantissa = FixedPoint.calculateMantissa(aToken.balanceOf(address(this)), totalSupply());
tokens = FixedPoint.multiplyUintByMantissa(shares, exchangeMantissa);
}
return tokens;
}
/// @notice Deposit asset tokens to Aave
/// @param mintAmount The amount of asset tokens to be deposited
/// @return 0 if successful
function _depositToAave(uint256 mintAmount) internal returns (uint256) {
IERC20Upgradeable _depositToken = IERC20Upgradeable(_tokenAddress());
_depositToken.safeTransferFrom(msg.sender, address(this), mintAmount);
_depositToken.safeApprove(address(_lendingPool()), mintAmount);
_lendingPool().deposit(address(_tokenAddress()), mintAmount, address(this), _getRefferalCode());
return 0;
}
/// @notice Supplies asset tokens to the yield source
/// @dev Shares corresponding to the number of tokens supplied are mint to the user's balance
/// @dev Asset tokens are supplied to the yield source, then deposited into Aave
/// @param mintAmount The amount of asset tokens to be supplied
/// @param to The user whose balance will receive the tokens
function supplyTokenTo(uint256 mintAmount, address to) external override nonReentrant {
uint256 shares = _tokenToShares(mintAmount);
require(shares > 0, "ATokenYieldSource/shares-equal-zero");
_depositToAave(mintAmount);
_mint(to, shares);
emit SuppliedTokenTo(msg.sender, shares, mintAmount, to);
}
/// @notice Redeems asset tokens from the yield source
/// @dev Shares corresponding to the number of tokens withdrawn are burnt from the user's balance
/// @dev Asset tokens are withdrawn from Aave, then transferred from the yield source to the user's wallet
/// @param redeemAmount The amount of asset tokens to be redeemed
/// @return The actual amount of asset tokens that were redeemed
function redeemToken(uint256 redeemAmount) external override nonReentrant returns (uint256) {
uint256 shares = _tokenToShares(redeemAmount);
_burn(msg.sender, shares);
uint256 beforeBalance = aToken.balanceOf(address(this));
_lendingPool().withdraw(address(_tokenAddress()), redeemAmount, address(this));
uint256 afterBalance = aToken.balanceOf(address(this));
uint256 balanceDiff = beforeBalance.sub(afterBalance);
IERC20Upgradeable(depositToken()).safeTransfer(msg.sender, balanceDiff);
emit RedeemedToken(msg.sender, shares, redeemAmount);
return balanceDiff;
}
/// @notice Transfer ERC20 tokens other than the aAtokens held by this contract to the recipient address
/// @dev This function is only callable by the owner or asset manager
/// @param erc20Token The ERC20 token to transfer
/// @param to The recipient of the tokens
/// @param amount The amount of tokens to transfer
function transferERC20(IERC20Upgradeable erc20Token, address to, uint256 amount) external override onlyOwnerOrAssetManager {
require(address(erc20Token) != address(aToken), "ATokenYieldSource/aToken-transfer-not-allowed");
erc20Token.safeTransfer(to, amount);
emit TransferredERC20(msg.sender, to, amount, erc20Token);
}
/// @notice Allows someone to deposit into the yield source without receiving any shares
/// @dev This allows anyone to distribute tokens among the share holders
/// @param amount The amount of tokens to deposit
function sponsor(uint256 amount) external override {
_depositToAave(amount);
emit Sponsored(msg.sender, amount);
}
/// @notice Used to get Aave LendingPoolAddressesProvider's ID
/// @dev This function could evolve in the future if we decide to support other markets
/// @return Returns Aave genesis market LendingPoolAddressesProvider's ID
function _getAddressesProviderId() internal pure returns (uint256) {
return uint256(0);
}
/// @notice Used to get PoolTogther's Aave Referral Code when calling depositTo Aave
/// @return Returns PoolTogether's Referral Code
function _getRefferalCode() internal pure returns (uint16) {
return uint16(188);
}
/// @notice Retrieves Aave LendingPoolAddressesProvider address
/// @return A reference to LendingPoolAddressesProvider interface
function _lendingPoolProvider() internal view returns (ILendingPoolAddressesProvider) {
uint256 addressesProviderId = _getAddressesProviderId();
return ILendingPoolAddressesProvider(lendingPoolAddressesProviderRegistry.getAddressesProvidersList()[addressesProviderId]);
}
/// @notice Retrieves Aave LendingPool address
/// @return A reference to LendingPool interface
function _lendingPool() internal view returns (ILendingPool) {
return ILendingPool(_lendingPoolProvider().getLendingPool());
}
}
|
Calculates the number of shares that should be mint or burned when a user deposit or withdraw tokens Amount of tokens return Number of shares rate = tokens / shares shares = tokens (totalShares / yieldSourceTotalSupply)
|
function _tokenToShares(uint256 tokens) internal view returns (uint256) {
uint256 shares = 0;
if (totalSupply() == 0) {
shares = tokens;
uint256 exchangeMantissa = FixedPoint.calculateMantissa(totalSupply(), aToken.balanceOf(address(this)));
shares = FixedPoint.multiplyUintByMantissa(tokens, exchangeMantissa);
}
return shares;
}
| 5,718,228
|
./full_match/3/0xFbd0aEef07bB33778E610741564F67Ccbcd551E7/sources/contracts/VestingMartin1.sol
|
Calculate the vested and unclaimed months and tokens available for `_grantId` to claim Due to rounding errors once grant duration is reached, returns the entire left grant amount Returns (0, 0) if cliff has not been reached For grants created with a future start date, that hasn't been reached, return 0, 0 If over vesting duration, all tokens vested
|
function calculateGrantClaim(uint256 _grantId) public view returns (uint16, uint256) {
Grant storage tokenGrant = tokenGrants[_grantId];
if (currentTime() < tokenGrant.startTime) {
return (0, 0);
}
uint elapsedDays = elapsedTime/(SECONDS_PER_DAY);
if (elapsedDays < tokenGrant.vestingCliff*(30)) {
return (uint16(elapsedDays), 0);
}
if (elapsedDays >= tokenGrant.vestingDuration*(30)) {
uint256 remainingGrant = tokenGrant.amount-(tokenGrant.totalClaimed);
return (tokenGrant.vestingDuration, remainingGrant);
uint16 timeVested = uint16(elapsedDays-(tokenGrant.daysClaimed));
uint256 amountVestedPerDay = tokenGrant.amount/(uint256(tokenGrant.vestingDuration*(30)));
uint256 amountVested = uint256(timeVested*(amountVestedPerDay));
return (timeVested, amountVested);
}
}
| 8,109,900
|
pragma solidity ^0.5.2;
contract Ownable {
address private _owner;
event OWNERSHIPTRANSFERRED275(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = msg.sender;
emit OWNERSHIPTRANSFERRED275(address(0), _owner);
}
function OWNER625() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER263() { //inject NONSTANDARD NAMING
require(ISOWNER221());
_;
}
function ISOWNER221() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
function RENOUNCEOWNERSHIP563() public ONLYOWNER263 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED275(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP811(address newOwner) public ONLYOWNER263 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP827(newOwner);
}
function _TRANSFEROWNERSHIP827(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED275(_owner, newOwner);
_owner = newOwner;
}
}
contract Secondary {
address private _primary;
event PRIMARYTRANSFERRED466( //inject NONSTANDARD NAMING
address recipient
);
constructor () internal {
_primary = msg.sender;
emit PRIMARYTRANSFERRED466(_primary);
}
modifier ONLYPRIMARY116() { //inject NONSTANDARD NAMING
require(msg.sender == _primary);
_;
}
function PRIMARY581() public view returns (address) { //inject NONSTANDARD NAMING
return _primary;
}
function TRANSFERPRIMARY630(address recipient) public ONLYPRIMARY116 { //inject NONSTANDARD NAMING
require(recipient != address(0));
_primary = recipient;
emit PRIMARYTRANSFERRED466(_primary);
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\IERC20.sol
interface IERC20 {
function TRANSFER568(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE366(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM855(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TOTALSUPPLY96() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF58(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE511(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
event TRANSFER836(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL290(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol
library SafeMath {
function MUL97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB631(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD445(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD309(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function TOTALSUPPLY96() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF58(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE511(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER568(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER261(msg.sender, to, value);
return true;
}
function APPROVE366(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE283(msg.sender, spender, value);
return true;
}
function TRANSFERFROM855(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER261(from, to, value);
_APPROVE283(from, msg.sender, _allowed[from][msg.sender].SUB631(value));
return true;
}
function INCREASEALLOWANCE464(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE283(msg.sender, spender, _allowed[msg.sender][spender].ADD445(addedValue));
return true;
}
function DECREASEALLOWANCE302(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE283(msg.sender, spender, _allowed[msg.sender][spender].SUB631(subtractedValue));
return true;
}
function _TRANSFER261(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB631(value);
_balances[to] = _balances[to].ADD445(value);
emit TRANSFER836(from, to, value);
}
function _MINT945(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.ADD445(value);
_balances[account] = _balances[account].ADD445(value);
emit TRANSFER836(address(0), account, value);
}
function _BURN542(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.SUB631(value);
_balances[account] = _balances[account].SUB631(value);
emit TRANSFER836(account, address(0), value);
}
function _APPROVE283(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit APPROVAL290(owner, spender, value);
}
function _BURNFROM236(address account, uint256 value) internal { //inject NONSTANDARD NAMING
_BURN542(account, value);
_APPROVE283(account, msg.sender, _allowed[account][msg.sender].SUB631(value));
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Burnable.sol
contract ERC20Burnable is ERC20 {
function BURN435(uint256 value) public { //inject NONSTANDARD NAMING
_BURN542(msg.sender, value);
}
function BURNFROM369(address from, uint256 value) public { //inject NONSTANDARD NAMING
_BURNFROM236(from, value);
}
}
// File: node_modules\openzeppelin-solidity\contracts\access\Roles.sol
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function ADD445(Role storage role, address account) internal { //inject NONSTANDARD NAMING
require(account != address(0));
require(!HAS23(role, account));
role.bearer[account] = true;
}
function REMOVE600(Role storage role, address account) internal { //inject NONSTANDARD NAMING
require(account != address(0));
require(HAS23(role, account));
role.bearer[account] = false;
}
function HAS23(Role storage role, address account) internal view returns (bool) { //inject NONSTANDARD NAMING
require(account != address(0));
return role.bearer[account];
}
}
// File: node_modules\openzeppelin-solidity\contracts\access\roles\MinterRole.sol
contract MinterRole {
using Roles for Roles.Role;
event MINTERADDED570(address indexed account); //inject NONSTANDARD NAMING
event MINTERREMOVED239(address indexed account); //inject NONSTANDARD NAMING
Roles.Role private _minters;
constructor () internal {
_ADDMINTER827(msg.sender);
}
modifier ONLYMINTER291() { //inject NONSTANDARD NAMING
require(ISMINTER698(msg.sender));
_;
}
function ISMINTER698(address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _minters.HAS23(account);
}
function ADDMINTER239(address account) public ONLYMINTER291 { //inject NONSTANDARD NAMING
_ADDMINTER827(account);
}
function RENOUNCEMINTER237() public { //inject NONSTANDARD NAMING
_REMOVEMINTER650(msg.sender);
}
function _ADDMINTER827(address account) internal { //inject NONSTANDARD NAMING
_minters.ADD445(account);
emit MINTERADDED570(account);
}
function _REMOVEMINTER650(address account) internal { //inject NONSTANDARD NAMING
_minters.REMOVE600(account);
emit MINTERREMOVED239(account);
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Mintable.sol
contract ERC20Mintable is ERC20, MinterRole {
function MINT610(address to, uint256 value) public ONLYMINTER291 returns (bool) { //inject NONSTANDARD NAMING
_MINT945(to, value);
return true;
}
}
// File: contracts\ERC20Frozenable.sol
//truffle-flattener Token.sol
contract ERC20Frozenable is ERC20Burnable, ERC20Mintable, Ownable {
mapping (address => bool) private _frozenAccount;
event FROZENFUNDS807(address target, bool frozen); //inject NONSTANDARD NAMING
function FROZENACCOUNT782(address _address) public view returns(bool isFrozen) { //inject NONSTANDARD NAMING
return _frozenAccount[_address];
}
function FREEZEACCOUNT250(address target, bool freeze) public ONLYOWNER263 { //inject NONSTANDARD NAMING
require(_frozenAccount[target] != freeze, "Same as current");
_frozenAccount[target] = freeze;
emit FROZENFUNDS807(target, freeze);
}
function _TRANSFER261(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(!_frozenAccount[from], "error - frozen");
require(!_frozenAccount[to], "error - frozen");
super._TRANSFER261(from, to, value);
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Detailed.sol
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME858() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL418() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS361() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
contract Escrow is Secondary {
using SafeMath for uint256;
event DEPOSITED6(address indexed payee, uint256 weiAmount); //inject NONSTANDARD NAMING
event WITHDRAWN702(address indexed payee, uint256 weiAmount); //inject NONSTANDARD NAMING
mapping(address => uint256) private _deposits;
function DEPOSITSOF491(address payee) public view returns (uint256) { //inject NONSTANDARD NAMING
return _deposits[payee];
}
function DEPOSIT494(address payee) public ONLYPRIMARY116 payable { //inject NONSTANDARD NAMING
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee].ADD445(amount);
emit DEPOSITED6(payee, amount);
}
function WITHDRAW275(address payable payee) public ONLYPRIMARY116 { //inject NONSTANDARD NAMING
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.transfer(payment);
emit WITHDRAWN702(payee, payment);
}
}
contract PullPayment {
Escrow private _escrow;
constructor () internal {
_escrow = new Escrow();
}
function WITHDRAWPAYMENTS729(address payable payee) public { //inject NONSTANDARD NAMING
_escrow.WITHDRAW275(payee);
}
function PAYMENTS838(address dest) public view returns (uint256) { //inject NONSTANDARD NAMING
return _escrow.DEPOSITSOF491(dest);
}
function _ASYNCTRANSFER275(address dest, uint256 amount) internal { //inject NONSTANDARD NAMING
_escrow.DEPOSIT494.value(amount)(dest);
}
}
contract PaymentSplitter {
using SafeMath for uint256;
event PAYEEADDED416(address account, uint256 shares); //inject NONSTANDARD NAMING
event PAYMENTRELEASED38(address to, uint256 amount); //inject NONSTANDARD NAMING
event PAYMENTRECEIVED491(address from, uint256 amount); //inject NONSTANDARD NAMING
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
constructor (address[] memory payees, uint256[] memory shares) public payable {
require(payees.length == shares.length);
require(payees.length > 0);
for (uint256 i = 0; i < payees.length; i++) {
_ADDPAYEE628(payees[i], shares[i]);
}
}
function () external payable {
emit PAYMENTRECEIVED491(msg.sender, msg.value);
}
function TOTALSHARES81() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalShares;
}
function TOTALRELEASED129() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalReleased;
}
function SHARES670(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _shares[account];
}
function RELEASED874(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _released[account];
}
function PAYEE185(uint256 index) public view returns (address) { //inject NONSTANDARD NAMING
return _payees[index];
}
function RELEASE471(address payable account) public { //inject NONSTANDARD NAMING
require(_shares[account] > 0);
uint256 totalReceived = address(this).balance.ADD445(_totalReleased);
uint256 payment = totalReceived.MUL97(_shares[account]).DIV803(_totalShares).SUB631(_released[account]);
require(payment != 0);
_released[account] = _released[account].ADD445(payment);
_totalReleased = _totalReleased.ADD445(payment);
account.transfer(payment);
emit PAYMENTRELEASED38(account, payment);
}
function _ADDPAYEE628(address account, uint256 shares_) private { //inject NONSTANDARD NAMING
require(account != address(0));
require(shares_ > 0);
require(_shares[account] == 0);
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares.ADD445(shares_);
emit PAYEEADDED416(account, shares_);
}
}
contract ConditionalEscrow is Escrow {
function WITHDRAWALALLOWED82(address payee) public view returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW275(address payable payee) public { //inject NONSTANDARD NAMING
require(WITHDRAWALALLOWED82(payee));
super.WITHDRAW275(payee);
}
}
contract RefundEscrow is ConditionalEscrow {
enum State { Active, Refunding, Closed }
event REFUNDSCLOSED652(); //inject NONSTANDARD NAMING
event REFUNDSENABLED266(); //inject NONSTANDARD NAMING
State private _state;
address payable private _beneficiary;
constructor (address payable beneficiary) public {
require(beneficiary != address(0));
_beneficiary = beneficiary;
_state = State.Active;
}
function STATE442() public view returns (State) { //inject NONSTANDARD NAMING
return _state;
}
function BENEFICIARY91() public view returns (address) { //inject NONSTANDARD NAMING
return _beneficiary;
}
function DEPOSIT494(address refundee) public payable { //inject NONSTANDARD NAMING
require(_state == State.Active);
super.DEPOSIT494(refundee);
}
function CLOSE124() public ONLYPRIMARY116 { //inject NONSTANDARD NAMING
require(_state == State.Active);
_state = State.Closed;
emit REFUNDSCLOSED652();
}
function ENABLEREFUNDS102() public ONLYPRIMARY116 { //inject NONSTANDARD NAMING
require(_state == State.Active);
_state = State.Refunding;
emit REFUNDSENABLED266();
}
function BENEFICIARYWITHDRAW365() public { //inject NONSTANDARD NAMING
require(_state == State.Closed);
_beneficiary.transfer(address(this).balance);
}
function WITHDRAWALALLOWED82(address) public view returns (bool) { //inject NONSTANDARD NAMING
return _state == State.Refunding;
}
}
// File: contracts\Token.sol
//truffle-flattener Token.sol
contract DeltaBlocks is ERC20Frozenable, ERC20Detailed {
constructor()
ERC20Detailed("Delta Blocks", "DTB", 18)
public {
uint256 supply = 10000000000;
uint256 initialSupply = supply * uint(10) ** DECIMALS361();
_MINT945(msg.sender, initialSupply);
}
}
|
inject NONSTANDARD NAMING
|
function TOTALRELEASED129() public view returns (uint256) {
| 7,302,987
|
pragma solidity ^0.4.23;
import "./IStateMachine.sol";
import "../lifecycle/OnlyOnce.sol";
import {StateMachineLib as SM} from "../libraries/StateMachineLib.sol";
contract StateMachine is IStateMachine, OnlyOnce {
// todo exp branch replace statemachine lib with modifiers for each state -- and check for gas
/**
* ## State Machine implementation
*/
using SM for SM.StateMachine;
/// @dev Structure holding the state of the contract
SM.StateMachine internal stateMachine;
event StateChanged(uint8 oldState, uint8 newState);
modifier requireAllowedTransition(uint8 _newState) {
stateMachine.isTransitionAllowed(_newState);
_;
}
/// @notice Returns current state of the contract state machine
/// @dev Shortcut to receive current state from external contracts
function currentState() public view returns (
uint8 /// Current state
) {
return stateMachine.currentState;
}
/// @dev State transition function
function transitionToState(
uint8 _newState /// New state to transition into
) public {
uint8 oldState = stateMachine.currentState;
stateMachine.currentState = _newState;
emit StateChanged(oldState, stateMachine.currentState);
_fireStateEvent();
}
//
// /// @dev State transition function from StateMachineLib put into modifier form.
// /// **Important:** state transition happens _before_ the main code of the calling function, and _after_ the
// /// execution contract is returned to the original state.
// modifier transitionThroughState(
// uint8 _transitionState /// Intermediary state to transition through
// ) {
// uint8 initialState = stateMachine.currentState;
// stateMachine.transitionThroughState(_transitionState);
// emit StateChanged(initialState, stateMachine.currentState);
// _fireStateEvent();
// _;
// stateMachine.currentState = initialState;
// emit StateChanged(_transitionState, stateMachine.currentState);
// _fireStateEvent();
// }
/// @dev Modifier requiring contract to be present in certain state; otherwise the exception is generated and the
/// function does not execute
modifier requireState(
uint8 _requiredState /// Required state
) {
require(stateMachine.currentState == _requiredState);
_;
}
/// @dev Modifier requiring contract to be present in one of two certain states; otherwise an exception is
/// generated and the function does not execute
modifier requireStates2(
uint8 _requiredState1, /// Required state, option 1
uint8 _requiredState2 /// Required state, option 2
) {
stateMachine.requireStates2(_requiredState1, _requiredState2);
_;
}
/// @dev Private method initializing state machine. Must be called only once from the contract constructor
function _initStateMachine() internal onlyOnce("_initStateMachine") {
// Initializing state machine via library code
stateMachine.initStateMachine();
}
/// @dev Hook for inherited contracts to fire contract-specific state change events
function _fireStateEvent() internal {
// Implemented by child contracts
}
}
|
Private method initializing state machine. Must be called only once from the contract constructor Initializing state machine via library code
|
function _initStateMachine() internal onlyOnce("_initStateMachine") {
stateMachine.initStateMachine();
}
| 12,927,534
|
./partial_match/42/0x1fff21842a1c6A8e73a4C083ed57eec55C79FE72/sources/PortobelloToken.sol
|
See {IERC721-isApprovedForAll}./
|
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
| 3,327,644
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import "../utils/Ownable.sol";
/// Tempus Token with initial supply that be increased by up to 2% yearly after 4 years.
/// Holders have the ability to burn their own tokens.
/// Token holders have the ability to vote and participate in governance.
/// It also supports delegating voting rights.
contract TempusToken is Ownable, ERC20Votes {
/// @dev initial supply to be minted
uint256 public constant INITIAL_SUPPLY = 1_000_000_000e18;
/// @dev Minimum time between mints
uint256 public constant MIN_TIME_BETWEEN_MINTS = 1 days * 365;
/// @dev Cap on the percentage of totalSupply that can be minted at each mint
uint256 public constant MINT_CAP = 2;
/// @dev The timestamp after which minting may occur
uint256 public immutable mintingAllowedAfter;
/// @dev The timestamp of last minting
uint256 public lastMintingTime;
constructor() ERC20("Tempus", "TEMP") ERC20Permit("Tempus") {
mintingAllowedAfter = block.timestamp + 4 * 365 * 1 days;
lastMintingTime = block.timestamp;
_mint(msg.sender, INITIAL_SUPPLY);
}
/// Creates `amount` new tokens for `to`.
/// @param account Recipient address to mint tokens to
/// @param amount Number of tokens to mint
function mint(address account, uint256 amount) external onlyOwner {
require(account != address(0), "Can not mint to 0x0.");
require(block.timestamp >= mintingAllowedAfter, "Minting not allowed yet.");
require(block.timestamp >= (lastMintingTime + MIN_TIME_BETWEEN_MINTS), "Not enough time between mints.");
require(amount <= ((MINT_CAP * totalSupply()) / 100), "Mint cap limit.");
lastMintingTime = block.timestamp;
_mint(account, amount);
}
/// Destroys `amount` tokens from the caller.
/// @param amount Number of tokens to burn.
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./draft-ERC20Permit.sol";
import "../../../utils/math/Math.sol";
import "../../../utils/math/SafeCast.sol";
import "../../../utils/cryptography/ECDSA.sol";
/**
* @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
*
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
* Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this
* will significantly increase the base gas cost of transfers.
*
* _Available since v4.2._
*/
abstract contract ERC20Votes is ERC20Permit {
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to an account's voting power.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCast.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual returns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view returns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
//
// During the loop, the index of the wanted checkpoint remains in the range [low, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
// - If the middle checkpoint is before `blockNumber`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
// the same.
uint256 high = ckpts.length;
uint256 low = 0;
while (low < high) {
uint256 mid = Math.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : ckpts[high - 1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual {
return _delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
return _delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCast.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)}));
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.6;
import "@openzeppelin/contracts/utils/Context.sol";
/// Implements Ownable with a two step transfer of ownership
abstract contract Ownable is Context {
address private _owner;
address private _proposedOwner;
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 Proposes a transfer of 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");
_proposedOwner = newOwner;
}
/**
* @dev Accepts ownership of the contract by a proposed account.
* Can only be called by the proposed owner.
*/
function acceptOwnership() public virtual {
require(msg.sender == _proposedOwner, "Ownable: Only proposed owner can accept ownership");
_setOwner(_proposedOwner);
_proposedOwner = address(0);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.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) 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 {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual 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();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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);
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @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 <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(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 <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* 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]
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// 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 recover(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 recover(hash, r, vs);
} else {
revert("ECDSA: invalid signature length");
}
}
/**
* @dev Overload of {ECDSA-recover} 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.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n รท 2 + 1, and for v in (282): v โ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(
uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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.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 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, 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
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @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;
}
}
|
Creates `amount` new tokens for `to`. account Recipient address to mint tokens to amount Number of tokens to mint
|
function mint(address account, uint256 amount) external onlyOwner {
require(account != address(0), "Can not mint to 0x0.");
require(block.timestamp >= mintingAllowedAfter, "Minting not allowed yet.");
require(block.timestamp >= (lastMintingTime + MIN_TIME_BETWEEN_MINTS), "Not enough time between mints.");
require(amount <= ((MINT_CAP * totalSupply()) / 100), "Mint cap limit.");
lastMintingTime = block.timestamp;
_mint(account, amount);
}
| 12,056,000
|
./full_match/1/0x2ACDFE510384c08e62556dA121eD81242DaB7aAd/sources/contracts/CitizensOfOverworld.sol
|
Given an index (derived from the Citizen's "background" trait), returns the html-styled background string, which will be inserted into the svg. If the Citizen is legendary, the background will be black & white./
|
function getBackgroundStyleFromDnaIndex(uint256 index, bool isLegendary)
private
view
returns (string memory)
{
if (isLegendary)
return "background: radial-gradient(white 0%, black 120%);";
else if (index > 5)
return
string.concat(
"background: linear-gradient(to bottom right, ",
"#",
backgrounds[index % 6],
", #",
backgrounds[(index + 1) % 6],
", #",
backgrounds[(index + 2) % 6],
", #",
backgrounds[(index + 3) % 6],
");"
);
else
return
string.concat(
"background: radial-gradient(antiquewhite 0%, #",
backgrounds[index],
" 60%);"
);
}
| 9,682,676
|
./full_match/5/0x458B00b6c2bc0B9a0A4fee7F4527a752CD4feA7C/sources/contracts/ERC721AModified.sol
|
Your custom implementation here
|
function mintTo(address to, string calldata uri)
external
returns (uint256)
{
}
| 1,852,229
|
./full_match/1/0x18629759e72eabBf53566263708e78Ddf191ef46/sources/contracts/iUSTP.sol
|
the exchange rate of iUSTP/
|
function pricePerToken() external view returns (uint256) {
return IrUSTP(address(rUSTP)).getrUSTPAmountByShares(1 ether);
}
| 8,365,465
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
/*
___ ___ ___ ___ ___
/\ \ /\__\ /\ \ /\ \ /\ \
/::\ \ /:/ _/_ /::\ \ _\:\ \ \:\ \
\:\:\__\ /:/_/\__\ /::\:\__\ /\/::\__\ /::\__\
\::/ / \:\/:/ / \:\::/ / \::/\/__/ /:/\/__/
/:/ / \::/ / \::/ / \:\__\ \/__/
\/__/ \/__/ \/__/ \/__/
*
* MIT License
* ===========
*
* Copyright (c) 2021 QubitFinance
*
* 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.
*/
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/IQBridgeHandler.sol";
import "../library/PausableUpgradeable.sol";
import "../library/AccessControlIndexUpgradeable.sol";
import "../library/SafeToken.sol";
contract QBridge is PausableUpgradeable, AccessControlIndexUpgradeable {
using SafeMath for uint;
using SafeToken for address;
/* ========== CONSTANT VARIABLES ========== */
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
uint public constant MAX_RELAYERS = 200;
enum ProposalStatus {Inactive, Active, Passed, Executed, Cancelled}
struct Proposal {
ProposalStatus _status;
uint200 _yesVotes; // bitmap, 200 maximum votes
uint8 _yesVotesTotal;
uint40 _proposedBlock; // 1099511627775 maximum block
}
/* ========== STATE VARIABLES ========== */
uint8 public domainID;
uint8 public relayerThreshold;
uint128 public fee;
uint40 public expiry;
mapping(uint8 => uint64) public _depositCounts; // destinationDomainID => number of deposits
mapping(bytes32 => address) public resourceIDToHandlerAddress; // resourceID => handler address
mapping(uint72 => mapping(bytes32 => Proposal)) private _proposals; // destinationDomainID + depositNonce => dataHash => Proposal
/* ========== EVENTS ========== */
event RelayerThresholdChanged(uint256 newThreshold);
event RelayerAdded(address relayer);
event RelayerRemoved(address relayer);
event Deposit(uint8 destinationDomainID, bytes32 resourceID, uint64 depositNonce, address indexed user, bytes data);
event ProposalEvent(uint8 originDomainID, uint64 depositNonce, ProposalStatus status, bytes data);
event ProposalVote(uint8 originDomainID, uint64 depositNonce, ProposalStatus status, bytes32 dataHash);
event FailedHandlerExecution(bytes lowLevelData);
/* ========== INITIALIZER ========== */
function initialize(uint8 _domainID, uint8 _relayerThreshold, uint128 _fee, uint40 _expiry) external initializer {
__PausableUpgradeable_init();
__AccessControl_init();
domainID = _domainID;
relayerThreshold = _relayerThreshold;
fee = _fee;
expiry = _expiry;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/* ========== MODIFIERS ========== */
modifier onlyRelayers() {
require(hasRole(RELAYER_ROLE, msg.sender), "QBridge: caller is not the relayer");
_;
}
modifier onlyOwnerOrRelayers() {
require(owner() == msg.sender || hasRole(RELAYER_ROLE, msg.sender), "QBridge: caller is not the owner or relayer");
_;
}
/* ========== RESTRICTED FUNCTIONS ========== */
function setRelayerThreshold(uint8 newThreshold) external onlyOwner {
relayerThreshold = newThreshold;
emit RelayerThresholdChanged(newThreshold);
}
function addRelayer(address relayer) external onlyOwner {
require(!hasRole(RELAYER_ROLE, relayer), "QBridge: duplicated relayer");
require(totalRelayers() < MAX_RELAYERS, "QBridge: relayers limit reached");
grantRole(RELAYER_ROLE, relayer);
emit RelayerAdded(relayer);
}
function removeRelayer(address relayer) external onlyOwner {
require(hasRole(RELAYER_ROLE, relayer), "QBridge: invalid relayer");
revokeRole(RELAYER_ROLE, relayer);
emit RelayerRemoved(relayer);
}
function setResource(address handlerAddress, bytes32 resourceID, address tokenAddress) external onlyOwner {
resourceIDToHandlerAddress[resourceID] = handlerAddress;
IQBridgeHandler(handlerAddress).setResource(resourceID, tokenAddress);
}
function setBurnable(address handlerAddress, address tokenAddress) external onlyOwner {
IQBridgeHandler(handlerAddress).setBurnable(tokenAddress);
}
function setDepositNonce(uint8 _domainID, uint64 nonce) external onlyOwner {
require(nonce > _depositCounts[_domainID], "QBridge: decrements not allowed");
_depositCounts[_domainID] = nonce;
}
function setFee(uint128 newFee) external onlyOwner {
fee = newFee;
}
function manualRelease(address handlerAddress, address tokenAddress, address recipient, uint amount) external onlyOwner {
IQBridgeHandler(handlerAddress).withdraw(tokenAddress, recipient, amount);
}
function sweep() external onlyOwner {
SafeToken.safeTransferETH(msg.sender, address(this).balance);
}
/* ========== VIEWS ========== */
function isRelayer(address relayer) external view returns (bool) {
return hasRole(RELAYER_ROLE, relayer);
}
function totalRelayers() public view returns (uint) {
return AccessControlIndexUpgradeable.getRoleMemberCount(RELAYER_ROLE);
}
/**
@notice Returns a proposalID.
@param _domainID Chain ID.
@param nonce ID of proposal generated by proposal's origin Bridge contract.
*/
function combinedProposalId(uint8 _domainID, uint64 nonce) public pure returns (uint72 proposalID) {
proposalID = (uint72(nonce) << 8) | uint72(_domainID);
}
/**
@notice Returns a proposal.
@param originDomainID Chain ID deposit originated from.
@param depositNonce ID of proposal generated by proposal's origin Bridge contract.
@param dataHash Hash of data to be provided when deposit proposal is executed.
*/
function getProposal(uint8 originDomainID, uint64 depositNonce, bytes32 dataHash, address relayer) external view returns (Proposal memory proposal, bool hasVoted) {
uint72 proposalID = combinedProposalId(originDomainID, depositNonce);
proposal = _proposals[proposalID][dataHash];
hasVoted = _hasVoted(proposal, relayer);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
@notice Initiates a transfer using a specified handler contract.
@notice Only callable when Bridge is not paused.
@param destinationDomainID ID of chain deposit will be bridged to.
@param resourceID ResourceID used to find address of handler to be used for deposit.
@param data Additional data to be passed to specified handler.
@notice Emits {Deposit} event with all necessary parameters
*/
function deposit(uint8 destinationDomainID, bytes32 resourceID, bytes calldata data) external payable notPaused {
require(msg.value == fee, "QBridge: invalid fee");
address handler = resourceIDToHandlerAddress[resourceID];
require(handler != address(0), "QBridge: invalid resourceID");
uint64 depositNonce = ++_depositCounts[destinationDomainID];
IQBridgeHandler(handler).deposit(resourceID, msg.sender, data);
emit Deposit(destinationDomainID, resourceID, depositNonce, msg.sender, data);
}
function depositETH(uint8 destinationDomainID, bytes32 resourceID, bytes calldata data) external payable notPaused {
uint option;
uint amount;
(option, amount) = abi.decode(data, (uint, uint));
require(msg.value == amount.add(fee), "QBridge: invalid fee");
address handler = resourceIDToHandlerAddress[resourceID];
require(handler != address(0), "QBridge: invalid resourceID");
uint64 depositNonce = ++_depositCounts[destinationDomainID];
IQBridgeHandler(handler).depositETH{value:amount}(resourceID, msg.sender, data);
emit Deposit(destinationDomainID, resourceID, depositNonce, msg.sender, data);
}
/**
@notice When called, {msg.sender} will be marked as voting in favor of proposal.
@notice Only callable by relayers when Bridge is not paused.
@param originDomainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param data Data originally provided when deposit was made.
@notice Proposal must not have already been passed or executed.
@notice {msg.sender} must not have already voted on proposal.
@notice Emits {ProposalEvent} event with status indicating the proposal status.
@notice Emits {ProposalVote} event.
*/
function voteProposal(uint8 originDomainID, uint64 depositNonce, bytes32 resourceID, bytes calldata data) external onlyRelayers notPaused {
address handlerAddress = resourceIDToHandlerAddress[resourceID];
require(handlerAddress != address(0), "QBridge: invalid handler");
uint72 proposalID = combinedProposalId(originDomainID, depositNonce);
bytes32 dataHash = keccak256(abi.encodePacked(handlerAddress, data));
Proposal memory proposal = _proposals[proposalID][dataHash];
if (proposal._status == ProposalStatus.Passed) {
executeProposal(originDomainID, depositNonce, resourceID, data, true);
return;
}
require(uint(proposal._status) <= 1, "QBridge: proposal already executed/cancelled");
require(!_hasVoted(proposal, msg.sender), "QBridge: relayer already voted");
if (proposal._status == ProposalStatus.Inactive) {
proposal = Proposal({_status : ProposalStatus.Active, _yesVotes : 0, _yesVotesTotal : 0, _proposedBlock : uint40(block.number)});
emit ProposalEvent(originDomainID, depositNonce, ProposalStatus.Active, data);
}
// else if (uint40(block.number.sub(proposal._proposedBlock)) > expiry) {
// proposal._status = ProposalStatus.Cancelled;
// emit ProposalEvent(originDomainID, depositNonce, ProposalStatus.Cancelled, dataHash);
// }
if (proposal._status != ProposalStatus.Cancelled) {
proposal._yesVotes = _bitmap(proposal._yesVotes, _relayerBit(msg.sender));
proposal._yesVotesTotal++;
emit ProposalVote(originDomainID, depositNonce, proposal._status, dataHash);
if (proposal._yesVotesTotal >= relayerThreshold) {
proposal._status = ProposalStatus.Passed;
emit ProposalEvent(originDomainID, depositNonce, ProposalStatus.Passed, data);
}
}
_proposals[proposalID][dataHash] = proposal;
if (proposal._status == ProposalStatus.Passed) {
executeProposal(originDomainID, depositNonce, resourceID, data, false);
}
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param originDomainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param resourceID ResourceID to be used when making deposits.
@param data Data originally provided when deposit was made.
@param revertOnFail Decision if the transaction should be reverted in case of handler's executeProposal is reverted or not.
@notice Proposal must have Passed status.
@notice Hash of {data} must equal proposal's {dataHash}.
@notice Emits {ProposalEvent} event with status {Executed}.
@notice Emits {FailedExecution} event with the failed reason.
*/
function executeProposal(uint8 originDomainID, uint64 depositNonce, bytes32 resourceID, bytes calldata data, bool revertOnFail) public onlyRelayers notPaused {
address handlerAddress = resourceIDToHandlerAddress[resourceID];
uint72 proposalID = combinedProposalId(originDomainID, depositNonce);
bytes32 dataHash = keccak256(abi.encodePacked(handlerAddress, data));
Proposal storage proposal = _proposals[proposalID][dataHash];
require(proposal._status == ProposalStatus.Passed, "QBridge: Proposal must have Passed status");
proposal._status = ProposalStatus.Executed;
IQBridgeHandler handler = IQBridgeHandler(handlerAddress);
if (revertOnFail) {
handler.executeProposal(resourceID, data);
} else {
try handler.executeProposal(resourceID, data) {
} catch (bytes memory lowLevelData) {
proposal._status = ProposalStatus.Passed;
emit FailedHandlerExecution(lowLevelData);
return;
}
}
emit ProposalEvent(originDomainID, depositNonce, ProposalStatus.Executed, data);
}
/**
@notice Cancels a deposit proposal that has not been executed yet.
@notice Only callable by relayers when Bridge is not paused.
@param originDomainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param resourceID ResourceID to be used when making deposits.
@param data Data originally provided when deposit was made.
@notice Proposal must be past expiry threshold.
@notice Emits {ProposalEvent} event with status {Cancelled}.
*/
function cancelProposal(uint8 originDomainID, uint64 depositNonce, bytes32 resourceID, bytes calldata data) public onlyOwnerOrRelayers {
address handlerAddress = resourceIDToHandlerAddress[resourceID];
uint72 proposalID = combinedProposalId(originDomainID, depositNonce);
bytes32 dataHash = keccak256(abi.encodePacked(handlerAddress, data));
Proposal memory proposal = _proposals[proposalID][dataHash];
ProposalStatus currentStatus = proposal._status;
require(currentStatus == ProposalStatus.Active || currentStatus == ProposalStatus.Passed, "QBridge: cannot be cancelled");
require(uint40(block.number.sub(proposal._proposedBlock)) > expiry, "QBridge: not at expiry threshold");
proposal._status = ProposalStatus.Cancelled;
_proposals[proposalID][dataHash] = proposal;
emit ProposalEvent(originDomainID, depositNonce, ProposalStatus.Cancelled, data);
}
/* ========== PRIVATE FUNCTIONS ========== */
function _relayerBit(address relayer) private view returns (uint) {
if (relayer == address(0)) return 0;
return uint(1) << AccessControlIndexUpgradeable.getRoleMemberIndex(RELAYER_ROLE, relayer).sub(1);
}
function _hasVoted(Proposal memory proposal, address relayer) private view returns (bool) {
return (_relayerBit(relayer) & uint(proposal._yesVotes)) > 0;
}
function _bitmap(uint200 source, uint bit) internal pure returns (uint200) {
uint value = source | bit;
require(value < 2 ** 200, "QBridge: value does not fit in 200 bits");
return uint200(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.12;
pragma experimental ABIEncoderV2;
interface IQBridgeHandler {
/**
@notice Correlates {resourceID} with {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function setResource(bytes32 resourceID, address contractAddress) external;
/**
@notice Marks {contractAddress} as mintable/burnable.
@param contractAddress Address of contract to be used when making or executing deposits.
*/
function setBurnable(address contractAddress) external;
/**
@notice It is intended that deposit are made using the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of additional data needed for a specific deposit.
*/
function deposit(bytes32 resourceID, address depositer, bytes calldata data) external;
function depositETH(bytes32 resourceID, address depositer, bytes calldata data) external payable;
/**
@notice It is intended that proposals are executed by the Bridge contract.
@param data Consists of additional data needed for a specific deposit execution.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external;
/**
@notice Used to manually release funds from ERC safes.
@param tokenAddress Address of token contract to release.
@param recipient Address to release tokens to.
@param amount the amount of ERC20 tokens to release.
*/
function withdraw(address tokenAddress, address recipient, uint amount) external;
}
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Docs: https://docs.synthetix.io/
*
*
* MIT License
* ===========
*
* Copyright (c) 2020 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
abstract contract PausableUpgradeable is OwnableUpgradeable {
uint public lastPauseTime;
bool public paused;
event PauseChanged(bool isPaused);
modifier notPaused {
require(!paused, "PausableUpgradeable: cannot be performed while the contract is paused");
_;
}
function __PausableUpgradeable_init() internal initializer {
__Ownable_init();
require(owner() != address(0), "PausableUpgradeable: owner must be set");
}
function setPaused(bool _paused) external onlyOwner {
if (_paused == paused) {
return;
}
paused = _paused;
if (paused) {
lastPauseTime = now;
}
emit PauseChanged(paused);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.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 AccessControlIndexUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.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 index of the account that have `role`.
*/
function getRoleMemberIndex(bytes32 role, address account) public view returns (uint256) {
return _roles[role].members._inner._indexes[bytes32(uint256(account))];
}
/**
* @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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface ERC20Interface {
function balanceOf(address user) external view returns (uint);
}
library SafeToken {
function myBalance(address token) internal view returns (uint) {
return ERC20Interface(token).balanceOf(address(this));
}
function balanceOf(address token, address user) internal view returns (uint) {
return ERC20Interface(token).balanceOf(user);
}
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))), "!safeApprove");
}
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))), "!safeTransfer");
}
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))), "!safeTransferFrom");
}
function safeTransferETH(address to, uint value) internal {
(bool success, ) = to.call{ value: value }(new bytes(0));
require(success, "!safeTransferETH");
}
}
// 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;
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.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;
import "../utils/ContextUpgradeable.sol";
|
bytes4(keccak256(bytes('transfer(address,uint256)')));
|
function safeTransfer(
address token,
address to,
uint value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "!safeTransfer");
}
| 11,686,820
|
./partial_match/4/0xA1F3D61edAE8c712f9365622987DD178F664Ddfb/sources/JustswapExchange.sol
|
Public price function for TRX to Token trades with an exact input. trx_sold Amount of TRX sold. return Amount of Tokens that can be bought with input TRX./
|
function getTrxToTokenInputPrice(uint256 trx_sold) public view returns (uint256) {
require(trx_sold > 0, "trx sold must greater than 0");
uint256 token_reserve = token.balanceOf(address(this));
return getInputPrice(trx_sold, address(this).balance, token_reserve);
}
| 16,996,562
|
./full_match/5/0x1eF1F851689b6494f4eE6563c1979B5b018be51d/sources/data/source/services/MonitoringService.sol
|
This message shows the intention of the signer to pay a reward to a Monitoring Service, provided that the call of updateNonClosingBalanceProof() succeeds. The triple (non_closing_participant, non_closing_signature, token_network_address) uniquely identifies the call that's supposed to be made. (Just checking non_closing_signature is not enough because when an attacker tampers with the payload, the signature verification doesn't fail but emits a different address.) (Without a token_network, there will be some ambiguity what the payload means.)
|
function recoverAddressFromRewardProof(
uint256 chain_id,
address token_network_address,
address non_closing_participant,
bytes memory non_closing_signature,
uint256 reward_amount,
bytes memory signature
)
internal
view
returns (address signature_address)
{
bytes32 message_hash = keccak256(abi.encodePacked(
address(this),
chain_id,
uint256(MessageTypeId.MSReward),
token_network_address,
non_closing_participant,
non_closing_signature,
reward_amount
));
signature_address = ECVerify.ecverify(message_hash, signature);
require(signature_address == non_closing_participant, "Reward proof with wrong non_closing_participant");
}
| 1,868,239
|
./full_match/80001/0x03f0D290821Ba68201617071BdA3E0093142D27B/sources/project:/contracts/extensions/Managerable.sol
|
solhint-disable-next-line func-name-mixedcase
|
function __Managerable_init() internal onlyInitializing {
__AccessControl_init();
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MANAGER_ROLE, msg.sender);
}
| 5,568,864
|
pragma solidity 0.7.6;
import "contracts/protocol/futures/StreamFuture.sol";
/**
* @title Contract for Aave Future
* @notice Handles the future mechanisms for the Aave platform
* @dev Implement directly the stream future abstraction as it fits the aToken IBT
*/
contract AaveFuture is StreamFuture {
}
pragma solidity 0.7.6;
import "contracts/protocol/futures/Future.sol";
/**
* @title Main future abstraction contract for the stream futures
* @notice Handles the stream future mecanisms
* @dev Basis of all mecanisms for futures (registrations, period switch)
*/
abstract contract StreamFuture is Future {
using SafeMathUpgradeable for uint256;
uint256[] internal scaledTotals;
/**
* @notice Intializer
* @param _controller the address of the controller
* @param _ibt the address of the corresponding IBT
* @param _periodDuration the length of the period (in days)
* @param _platformName the name of the platform and tools
* @param _deployerAddress the future deployer address
* @param _admin the address of the ACR admin
*/
function initialize(
address _controller,
address _ibt,
uint256 _periodDuration,
string memory _platformName,
address _deployerAddress,
address _admin
) public virtual override initializer {
super.initialize(_controller, _ibt, _periodDuration, _platformName, _deployerAddress, _admin);
scaledTotals.push();
scaledTotals.push();
}
/**
* @notice Sender registers an amount of IBT for the next period
* @param _user address to register to the future
* @param _amount amount of IBT to be registered
* @dev called by the controller only
*/
function register(address _user, uint256 _amount) public virtual override periodsActive nonReentrant depositsEnabled {
require(_amount > 0, "invalid amount to register");
IRegistry registry = IRegistry(controller.getRegistryAddress());
uint256 scaledInput =
IAPWineMaths(registry.getMathsUtils()).getScaledInput(
_amount,
scaledTotals[getNextPeriodIndex()],
ibt.balanceOf(address(this))
);
super.register(_user, scaledInput);
scaledTotals[getNextPeriodIndex()] = scaledTotals[getNextPeriodIndex()].add(scaledInput);
}
/**
* @notice Sender unregisters an amount of IBT for the next period
* @param _user user addresss
* @param _amount amount of IBT to be unregistered
* @dev 0 unregisters all
*/
function unregister(address _user, uint256 _amount) public virtual override nonReentrant withdrawalsEnabled {
require(hasRole(CONTROLLER_ROLE, msg.sender), "Caller is not allowed to unregister");
uint256 nextIndex = getNextPeriodIndex();
require(registrations[_user].startIndex == nextIndex, "There is no ongoing registration for the next period");
uint256 userScaledBalance = registrations[_user].scaledBalance;
IRegistry registry = IRegistry(controller.getRegistryAddress());
uint256 currentRegistered =
IAPWineMaths(registry.getMathsUtils()).getActualOutput(
userScaledBalance,
scaledTotals[nextIndex],
ibt.balanceOf(address(this))
);
uint256 scaledToUnregister;
uint256 toRefund;
if (_amount == 0) {
scaledToUnregister = userScaledBalance;
delete registrations[_user];
toRefund = currentRegistered;
} else {
require(currentRegistered >= _amount, "Invalid amount to unregister");
scaledToUnregister = (registrations[_user].scaledBalance.mul(_amount)).div(currentRegistered);
registrations[_user].scaledBalance = registrations[_user].scaledBalance.sub(scaledToUnregister);
toRefund = _amount;
}
scaledTotals[nextIndex] = scaledTotals[nextIndex].sub(scaledToUnregister);
ibt.transfer(_user, toRefund);
}
/**
* @notice Start a new period
* @dev needs corresponding permissions for sender
*/
function startNewPeriod() public virtual override nextPeriodAvailable periodsActive nonReentrant {
require(hasRole(CONTROLLER_ROLE, msg.sender), "Caller is not allowed to start the next period");
uint256 nextPeriodID = getNextPeriodIndex();
registrationsTotals[nextPeriodID] = ibt.balanceOf(address(this));
/* Yield */
uint256 yield = ibt.balanceOf(address(futureVault)).sub(apwibt.totalSupply());
futureWallet.registerExpiredFuture(yield); // Yield deposit in the futureWallet contract
if (yield > 0) assert(ibt.transferFrom(address(futureVault), address(futureWallet), yield));
/* Period Switch*/
if (registrationsTotals[nextPeriodID] > 0) {
apwibt.mint(address(this), registrationsTotals[nextPeriodID]); // Mint new apwIBTs
ibt.transfer(address(futureVault), registrationsTotals[nextPeriodID]); // Send IBT to future for the new period
}
registrationsTotals.push();
scaledTotals.push();
/* Future Yield Token */
address fytAddress = deployFutureYieldToken(nextPeriodID);
emit NewPeriodStarted(nextPeriodID, fytAddress);
}
/**
* @notice Getter for user registered amount
* @param _user user to return the registered funds of
* @return the registered amount, 0 if no registrations
* @dev the registration can be older than the next period
*/
function getRegisteredAmount(address _user) public view virtual override returns (uint256) {
uint256 periodID = registrations[_user].startIndex;
IRegistry registry = IRegistry(controller.getRegistryAddress());
if (periodID == getNextPeriodIndex()) {
return
IAPWineMaths(registry.getMathsUtils()).getActualOutput(
registrations[_user].scaledBalance,
scaledTotals[periodID],
ibt.balanceOf(address(this))
);
} else {
return 0;
}
}
/**
* @notice Getter for the amount of apwIBT that the user can claim
* @param _user user to check the check the claimable apwIBT of
* @return the amount of apwIBT claimable by the user
*/
function getClaimableAPWIBT(address _user) public view override returns (uint256) {
if (!hasClaimableAPWIBT(_user)) return 0;
IRegistry registry = IRegistry(controller.getRegistryAddress());
return
IAPWineMaths(registry.getMathsUtils()).getActualOutput(
registrations[_user].scaledBalance,
scaledTotals[registrations[_user].startIndex],
registrationsTotals[registrations[_user].startIndex]
);
}
/**
* @notice Getter for yield that is generated by the user funds during the current period
* @param _user user to check the unrealised yield of
* @return the yield (amount of IBT) currently generated by the locked funds of the user
*/
function getUnrealisedYield(address _user) public view override returns (uint256) {
return
(
(ibt.balanceOf(address(futureVault)).sub(apwibt.totalSupply())).mul(
fyts[getNextPeriodIndex() - 1].balanceOf(_user)
)
)
.div(fyts[getNextPeriodIndex() - 1].totalSupply());
}
}
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "contracts/interfaces/IProxyFactory.sol";
import "contracts/interfaces/apwine/tokens/IFutureYieldToken.sol";
import "contracts/interfaces/apwine/utils/IAPWineMath.sol";
import "contracts/interfaces/apwine/tokens/IAPWineIBT.sol";
import "contracts/interfaces/apwine/IFutureWallet.sol";
import "contracts/interfaces/apwine/IController.sol";
import "contracts/interfaces/apwine/IFutureVault.sol";
import "contracts/interfaces/apwine/ILiquidityGauge.sol";
import "contracts/interfaces/apwine/IRegistry.sol";
/**
* @title Main future abstraction contract
* @notice Handles the future mechanisms
* @dev Basis of all mecanisms for futures (registrations, period switch)
*/
abstract contract Future is Initializable, AccessControlUpgradeable, ReentrancyGuardUpgradeable {
using SafeMathUpgradeable for uint256;
/* Structs */
struct Registration {
uint256 startIndex;
uint256 scaledBalance;
}
uint256[] internal registrationsTotals;
/* ACR */
bytes32 public constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE");
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant FUTURE_DEPLOYER = keccak256("FUTURE_DEPLOYER");
/* State variables */
mapping(address => uint256) internal lastPeriodClaimed;
mapping(address => Registration) internal registrations;
IFutureYieldToken[] public fyts;
/* External contracts */
IFutureVault internal futureVault;
IFutureWallet internal futureWallet;
ILiquidityGauge internal liquidityGauge;
ERC20 internal ibt;
IAPWineIBT internal apwibt;
IController internal controller;
/* Settings */
uint256 public PERIOD_DURATION;
string public PLATFORM_NAME;
bool public PAUSED;
bool public WITHRAWALS_PAUSED;
bool public DEPOSITS_PAUSED;
/* Events */
event UserRegistered(address _userAddress, uint256 _amount, uint256 _periodIndex);
event NewPeriodStarted(uint256 _newPeriodIndex, address _fytAddress);
event FutureVaultSet(address _futureVault);
event FutureWalletSet(address _futureWallet);
event LiquidityGaugeSet(address _liquidityGauge);
event FundsWithdrawn(address _user, uint256 _amount);
event PeriodsPaused();
event PeriodsResumed();
event DepositsPaused();
event DepositsResumed();
event WithdrawalsPaused();
event WithdrawalsResumed();
event APWIBTSet(address _apwibt);
event LiquidityTransfersPaused();
event LiquidityTransfersResumed();
/* Modifiers */
modifier nextPeriodAvailable() {
uint256 controllerDelay = controller.STARTING_DELAY();
require(
controller.getNextPeriodStart(PERIOD_DURATION) < block.timestamp.add(controllerDelay),
"Next period start range not reached yet"
);
_;
}
modifier periodsActive() {
require(!PAUSED, "New periods are currently paused");
_;
}
modifier withdrawalsEnabled() {
require(!WITHRAWALS_PAUSED, "withdrawals are disabled");
_;
}
modifier depositsEnabled() {
require(!DEPOSITS_PAUSED, "desposits are disabled");
_;
}
/* Initializer */
/**
* @notice Intializer
* @param _controller the address of the controller
* @param _ibt the address of the corresponding IBT
* @param _periodDuration the length of the period (in days)
* @param _platformName the name of the platform and tools
* @param _admin the address of the ACR admin
*/
function initialize(
address _controller,
address _ibt,
uint256 _periodDuration,
string memory _platformName,
address _deployerAddress,
address _admin
) public virtual initializer {
controller = IController(_controller);
ibt = ERC20(_ibt);
PERIOD_DURATION = _periodDuration * (1 days);
PLATFORM_NAME = _platformName;
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(ADMIN_ROLE, _admin);
_setupRole(CONTROLLER_ROLE, _controller);
_setupRole(FUTURE_DEPLOYER, _deployerAddress);
registrationsTotals.push();
registrationsTotals.push();
fyts.push();
IRegistry registry = IRegistry(controller.getRegistryAddress());
string memory ibtSymbol = controller.getFutureIBTSymbol(ibt.symbol(), _platformName, PERIOD_DURATION);
bytes memory payload =
abi.encodeWithSignature(
"initialize(string,string,uint8,address)",
ibtSymbol,
ibtSymbol,
ibt.decimals(),
address(this)
);
apwibt = IAPWineIBT(
IProxyFactory(registry.getProxyFactoryAddress()).deployMinimal(registry.getAPWineIBTLogicAddress(), payload)
);
emit APWIBTSet(address(apwibt));
}
/* Period functions */
/**
* @notice Start a new period
* @dev needs corresponding permissions for sender
*/
function startNewPeriod() public virtual;
/**
* @notice Sender registers an amount of IBT for the next period
* @param _user address to register to the future
* @param _amount amount of IBT to be registered
* @dev called by the controller only
*/
function register(address _user, uint256 _amount) public virtual periodsActive depositsEnabled periodsActive {
require(hasRole(CONTROLLER_ROLE, msg.sender), "Caller is not allowed to register");
uint256 nextIndex = getNextPeriodIndex();
if (registrations[_user].scaledBalance == 0) {
// User has no record
_register(_user, _amount);
} else {
if (registrations[_user].startIndex == nextIndex) {
// User has already an existing registration for the next period
registrations[_user].scaledBalance = registrations[_user].scaledBalance.add(_amount);
} else {
// User had an unclaimed registation from a previous period
_claimAPWIBT(_user);
_register(_user, _amount);
}
}
emit UserRegistered(_user, _amount, nextIndex);
}
function _register(address _user, uint256 _initialScaledBalance) internal virtual {
registrations[_user] = Registration({startIndex: getNextPeriodIndex(), scaledBalance: _initialScaledBalance});
}
/**
* @notice Sender unregisters an amount of IBT for the next period
* @param _user user address
* @param _amount amount of IBT to be unregistered
*/
function unregister(address _user, uint256 _amount) public virtual;
/* Claim functions */
/**
* @notice Send the user their owed FYT (and apwIBT if there are some claimable)
* @param _user address of the user to send the FYT to
*/
function claimFYT(address _user) public virtual nonReentrant {
require(hasClaimableFYT(_user), "No FYT claimable for this address");
if (hasClaimableAPWIBT(_user)) _claimAPWIBT(_user);
else _claimFYT(_user);
}
function _claimFYT(address _user) internal virtual {
uint256 nextIndex = getNextPeriodIndex();
for (uint256 i = lastPeriodClaimed[_user] + 1; i < nextIndex; i++) {
claimFYTforPeriod(_user, i);
}
}
function claimFYTforPeriod(address _user, uint256 _periodIndex) internal virtual {
assert((lastPeriodClaimed[_user] + 1) == _periodIndex);
assert(_periodIndex < getNextPeriodIndex());
assert(_periodIndex != 0);
lastPeriodClaimed[_user] = _periodIndex;
fyts[_periodIndex].transfer(_user, apwibt.balanceOf(_user));
}
function _claimAPWIBT(address _user) internal virtual {
uint256 nextIndex = getNextPeriodIndex();
uint256 claimableAPWIBT = getClaimableAPWIBT(_user);
if (_hasOnlyClaimableFYT(_user)) _claimFYT(_user);
apwibt.transfer(_user, claimableAPWIBT);
for (uint256 i = registrations[_user].startIndex; i < nextIndex; i++) {
// get unclaimed fyt
fyts[i].transfer(_user, claimableAPWIBT);
}
lastPeriodClaimed[_user] = nextIndex - 1;
delete registrations[_user];
}
/**
* @notice Sender unlocks the locked funds corresponding to their apwIBT holding
* @param _user user adress
* @param _amount amount of funds to unlock
* @dev will require a transfer of FYT of the ongoing period corresponding to the funds unlocked
*/
function withdrawLockFunds(address _user, uint256 _amount) public virtual nonReentrant withdrawalsEnabled {
require(hasRole(CONTROLLER_ROLE, msg.sender), "Caller is not allowed to withdraw locked funds");
require((_amount > 0) && (_amount <= apwibt.balanceOf(_user)), "Invalid amount");
if (hasClaimableAPWIBT(_user)) {
_claimAPWIBT(_user);
} else if (hasClaimableFYT(_user)) {
_claimFYT(_user);
}
uint256 unlockableFunds = getUnlockableFunds(_user);
uint256 unrealisedYield = getUnrealisedYield(_user);
uint256 fundsToBeUnlocked = _amount.mul(unlockableFunds).div(apwibt.balanceOf(_user));
uint256 yieldToBeUnlocked = _amount.mul(unrealisedYield).div(apwibt.balanceOf(_user));
uint256 yieldToBeRedeemed;
if (PAUSED) {
yieldToBeRedeemed = yieldToBeUnlocked;
} else {
yieldToBeRedeemed = (yieldToBeUnlocked.mul(controller.getUnlockYieldFactor(PERIOD_DURATION))).div(1000);
}
ibt.transferFrom(address(futureVault), _user, fundsToBeUnlocked.add(yieldToBeRedeemed));
uint256 treasuryFee = unrealisedYield.sub(yieldToBeRedeemed);
if (treasuryFee > 0) {
ibt.transferFrom(
address(futureVault),
IRegistry(controller.getRegistryAddress()).getTreasuryAddress(),
treasuryFee
);
}
apwibt.burnFrom(_user, _amount);
fyts[getNextPeriodIndex() - 1].burnFrom(_user, _amount);
emit FundsWithdrawn(_user, _amount);
}
/* Utilitary functions */
function deployFutureYieldToken(uint256 _internalPeriodID) internal returns (address) {
IRegistry registry = IRegistry(controller.getRegistryAddress());
string memory tokenDenomination = controller.getFYTSymbol(apwibt.symbol(), PERIOD_DURATION);
bytes memory payload =
abi.encodeWithSignature(
"initialize(string,string,uint8,uint256,address)",
tokenDenomination,
tokenDenomination,
ibt.decimals(),
_internalPeriodID,
address(this)
);
IFutureYieldToken newToken =
IFutureYieldToken(
IProxyFactory(registry.getProxyFactoryAddress()).deployMinimal(registry.getFYTLogicAddress(), payload)
);
fyts.push(newToken);
newToken.mint(address(this), apwibt.totalSupply());
return address(newToken);
}
/* Getters */
/**
* @notice Check if a user has unclaimed FYT
* @param _user the user to check
* @return true if the user can claim some FYT, false otherwise
*/
function hasClaimableFYT(address _user) public view returns (bool) {
return hasClaimableAPWIBT(_user) || _hasOnlyClaimableFYT(_user);
}
function _hasOnlyClaimableFYT(address _user) internal view returns (bool) {
return lastPeriodClaimed[_user] != 0 && lastPeriodClaimed[_user] < getNextPeriodIndex() - 1;
}
/**
* @notice Check if a user has IBT not claimed
* @param _user the user to check
* @return true if the user can claim some IBT, false otherwise
*/
function hasClaimableAPWIBT(address _user) public view returns (bool) {
return (registrations[_user].startIndex < getNextPeriodIndex()) && (registrations[_user].scaledBalance > 0);
}
/**
* @notice Getter for next period index
* @return next period index
* @dev index starts at 1
*/
function getNextPeriodIndex() public view virtual returns (uint256) {
return registrationsTotals.length - 1;
}
/**
* @notice Getter for the amount of apwIBT that the user can claim
* @param _user user to check the check the claimable apwIBT of
* @return the amount of apwIBT claimable by the user
*/
function getClaimableAPWIBT(address _user) public view virtual returns (uint256);
/**
* @notice Getter for the amount of FYT that the user can claim for a certain period
* @param _user the user to check the claimable FYT of
* @param _periodID period ID to check the claimable FYT of
* @return the amount of FYT claimable by the user for this period ID
*/
function getClaimableFYTForPeriod(address _user, uint256 _periodID) public view virtual returns (uint256) {
if (
_periodID >= getNextPeriodIndex() ||
registrations[_user].startIndex == 0 ||
registrations[_user].scaledBalance == 0 ||
registrations[_user].startIndex > _periodID
) {
return 0;
} else {
return getClaimableAPWIBT(_user);
}
}
/**
* @notice Getter for user IBT amount that is unlockable
* @param _user the user to unlock the IBT from
* @return the amount of IBT the user can unlock
*/
function getUnlockableFunds(address _user) public view virtual returns (uint256) {
return apwibt.balanceOf(_user);
}
/**
* @notice Getter for user registered amount
* @param _user the user to return the registered funds of
* @return the registered amount, 0 if no registrations
* @dev the registration can be older than the next period
*/
function getRegisteredAmount(address _user) public view virtual returns (uint256);
/**
* @notice Getter for yield that is generated by the user funds during the current period
* @param _user the user to check the unrealized yield of
* @return the yield (amount of IBT) currently generated by the locked funds of the user
*/
function getUnrealisedYield(address _user) public view virtual returns (uint256);
/**
* @notice Getter for controller address
* @return the controller address
*/
function getControllerAddress() public view returns (address) {
return address(controller);
}
/**
* @notice Getter for future wallet address
* @return future wallet address
*/
function getFutureVaultAddress() public view returns (address) {
return address(futureVault);
}
/**
* @notice Getter for futureWallet address
* @return futureWallet address
*/
function getFutureWalletAddress() public view returns (address) {
return address(futureWallet);
}
/**
* @notice Getter for liquidity gauge address
* @return liquidity gauge address
*/
function getLiquidityGaugeAddress() public view returns (address) {
return address(liquidityGauge);
}
/**
* @notice Getter for the IBT address
* @return IBT address
*/
function getIBTAddress() public view returns (address) {
return address(ibt);
}
/**
* @notice Getter for future apwIBT address
* @return apwIBT address
*/
function getAPWIBTAddress() public view returns (address) {
return address(apwibt);
}
/**
* @notice Getter for FYT address of a particular period
* @param _periodIndex period index
* @return FYT address
*/
function getFYTofPeriod(uint256 _periodIndex) public view returns (address) {
require(_periodIndex < getNextPeriodIndex(), "No FYT for this period yet");
return address(fyts[_periodIndex]);
}
/* Admin function */
/**
* @notice Pause registrations and the creation of new periods
*/
function pausePeriods() public {
require(
(hasRole(ADMIN_ROLE, msg.sender) || hasRole(CONTROLLER_ROLE, msg.sender)),
"Caller is not allowed to pause future"
);
PAUSED = true;
emit PeriodsPaused();
}
/**
* @notice Resume registrations and the creation of new periods
*/
function resumePeriods() public {
require(
(hasRole(ADMIN_ROLE, msg.sender) || hasRole(CONTROLLER_ROLE, msg.sender)),
"Caller is not allowed to resume future"
);
PAUSED = false;
emit PeriodsResumed();
}
/**
* @notice Pause withdrawals
*/
function pauseWithdrawals() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to pause withdrawals");
WITHRAWALS_PAUSED = true;
emit WithdrawalsPaused();
}
/**
* @notice Resume withdrawals
*/
function resumeWithdrawals() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to resume withdrawals");
WITHRAWALS_PAUSED = false;
emit WithdrawalsResumed();
}
/**
* @notice Pause deposits
*/
function pauseDeposits() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to pause deposits");
DEPOSITS_PAUSED = true;
emit DepositsPaused();
}
/**
* @notice Resume deposits
*/
function resumeDeposits() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to resume deposits");
DEPOSITS_PAUSED = false;
emit DepositsResumed();
}
/**
* @notice Pause liquidity transfers
*/
function pauseLiquidityTransfers() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to pause liquidity transfer");
apwibt.pause();
emit LiquidityTransfersPaused();
}
/**
* @notice Resume liquidity transfers
*/
function resumeLiquidityTransfers() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to resume liquidity transfer");
apwibt.unpause();
emit LiquidityTransfersResumed();
}
/**
* @notice Set future wallet address
* @param _futureVault the address of the new future wallet
* @dev needs corresponding permissions for sender
*/
function setFutureVault(address _futureVault) public {
require(hasRole(FUTURE_DEPLOYER, msg.sender), "Caller is not allowed to set the future vault address");
futureVault = IFutureVault(_futureVault);
emit FutureVaultSet(_futureVault);
}
/**
* @notice Set futureWallet address
* @param _futureWallet the address of the new futureWallet
* @dev needs corresponding permissions for sender
*/
function setFutureWallet(address _futureWallet) public {
require(hasRole(FUTURE_DEPLOYER, msg.sender), "Caller is not allowed to set the future wallet address");
futureWallet = IFutureWallet(_futureWallet);
emit FutureWalletSet(_futureWallet);
}
/**
* @notice Set liquidity gauge address
* @param _liquidityGauge the address of the new liquidity gauge
* @dev needs corresponding permissions for sender
*/
function setLiquidityGauge(address _liquidityGauge) public {
require(hasRole(FUTURE_DEPLOYER, msg.sender), "Caller is not allowed to set the liquidity gauge address");
liquidityGauge = ILiquidityGauge(_liquidityGauge);
emit LiquidityGaugeSet(_liquidityGauge);
}
/**
* @notice Set apwibt address
* @param _apwibt the address of the new apwibt
* @dev used only for exceptional purpose
*/
function setAPWIBT(address _apwibt) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to set the apwibt");
apwibt = IAPWineIBT(_apwibt);
emit APWIBTSet(_apwibt);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../GSN/ContextUpgradeable.sol";
import "../proxy/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, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
pragma solidity 0.7.6;
interface IProxyFactory {
function deployMinimal(address _logic, bytes memory _data) external returns (address proxy);
}
pragma solidity 0.7.6;
import "contracts/interfaces/ERC20.sol";
interface IFutureYieldToken is ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) external;
/**
* @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) external;
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) external;
}
pragma solidity 0.7.6;
interface IAPWineMaths {
/**
* @notice scale an input
* @param _actualValue the original value of the input
* @param _initialSum the scaled value of the sum of the inputs
* @param _actualSum the current value of the sum of the inputs
*/
function getScaledInput(
uint256 _actualValue,
uint256 _initialSum,
uint256 _actualSum
) external pure returns (uint256);
/**
* @notice scale back a value to the output
* @param _scaledOutput the current scaled output
* @param _initialSum the scaled value of the sum of the inputs
* @param _actualSum the current value of the sum of the inputs
*/
function getActualOutput(
uint256 _scaledOutput,
uint256 _initialSum,
uint256 _actualSum
) external pure returns (uint256);
}
pragma solidity 0.7.6;
import "contracts/interfaces/ERC20.sol";
interface IAPWineIBT is ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) external;
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) external;
/**
* @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) external;
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() external;
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() external;
}
pragma solidity 0.7.6;
interface IFutureWallet {
/**
* @notice Intializer
* @param _futureAddress the address of the corresponding future
* @param _adminAddress the address of the ACR admin
*/
function initialize(address _futureAddress, address _adminAddress) external;
/**
* @notice register the yield of an expired period
* @param _amount the amount of yield to be registered
*/
function registerExpiredFuture(uint256 _amount) external;
/**
* @notice redeem the yield of the underlying yield of the FYT held by the sender
* @param _periodIndex the index of the period to redeem the yield from
*/
function redeemYield(uint256 _periodIndex) external;
/**
* @notice return the yield that could be redeemed by an address for a particular period
* @param _periodIndex the index of the corresponding period
* @param _tokenHolder the FYT holder
* @return the yield that could be redeemed by the token holder for this period
*/
function getRedeemableYield(uint256 _periodIndex, address _tokenHolder) external view returns (uint256);
/**
* @notice getter for the address of the future corresponding to this future wallet
* @return the address of the future
*/
function getFutureAddress() external view returns (address);
/**
* @notice getter for the address of the IBT corresponding to this future wallet
* @return the address of the IBT
*/
function getIBTAddress() external view returns (address);
}
pragma solidity 0.7.6;
interface IController {
/* Getters */
function STARTING_DELAY() external view returns (uint256);
/* Initializer */
/**
* @notice Initializer of the Controller contract
* @param _admin the address of the admin
*/
function initialize(address _admin) external;
/* Future Settings Setters */
/**
* @notice Change the delay for starting a new period
* @param _startingDelay the new delay (+-) to start the next period
*/
function setPeriodStartingDelay(uint256 _startingDelay) external;
/**
* @notice Set the next period switch timestamp for the future with corresponding duration
* @param _periodDuration the duration of a period
* @param _nextPeriodTimestamp the next period switch timestamp
*/
function setNextPeriodSwitchTimestamp(uint256 _periodDuration, uint256 _nextPeriodTimestamp) external;
/**
* @notice Set a new factor for the portion of the yield that is claimable when withdrawing funds during an ongoing period
* @param _periodDuration the duration of the periods
* @param _claimableYieldFactor the portion of the yield that is claimable
*/
function setUnlockClaimableFactor(uint256 _periodDuration, uint256 _claimableYieldFactor) external;
/* User Methods */
/**
* @notice Register an amount of IBT from the sender to the corresponding future
* @param _future the address of the future to be registered to
* @param _amount the amount to register
*/
function register(address _future, uint256 _amount) external;
/**
* @notice Unregister an amount of IBT from the sender to the corresponding future
* @param _future the address of the future to be unregistered from
* @param _amount the amount to unregister
*/
function unregister(address _future, uint256 _amount) external;
/**
* @notice Withdraw deposited funds from APWine
* @param _future the address of the future to withdraw the IBT from
* @param _amount the amount to withdraw
*/
function withdrawLockFunds(address _future, uint256 _amount) external;
/**
* @notice Claim FYT of the msg.sender
* @param _future the future from which to claim the FYT
*/
function claimFYT(address _future) external;
/**
* @notice Get the list of futures from which a user can claim FYT
* @param _user the user to check
*/
function getFuturesWithClaimableFYT(address _user) external view returns (address[] memory);
/**
* @notice Getter for the registry address of the protocol
* @return the address of the protocol registry
*/
function getRegistryAddress() external view returns (address);
/**
* @notice Getter for the symbol of the apwIBT of one future
* @param _ibtSymbol the IBT of the external protocol
* @param _platform the external protocol name
* @param _periodDuration the duration of the periods for the future
* @return the generated symbol of the apwIBT
*/
function getFutureIBTSymbol(
string memory _ibtSymbol,
string memory _platform,
uint256 _periodDuration
) external pure returns (string memory);
/**
* @notice Getter for the symbol of the FYT of one future
* @param _apwibtSymbol the apwIBT symbol for this future
* @param _periodDuration the duration of the periods for this future
* @return the generated symbol of the FYT
*/
function getFYTSymbol(string memory _apwibtSymbol, uint256 _periodDuration) external view returns (string memory);
/**
* @notice Getter for the period index depending on the period duration of the future
* @param _periodDuration the periods duration
* @return the period index
*/
function getPeriodIndex(uint256 _periodDuration) external view returns (uint256);
/**
* @notice Getter for beginning timestamp of the next period for the futures with a defined periods duration
* @param _periodDuration the periods duration
* @return the timestamp of the beginning of the next period
*/
function getNextPeriodStart(uint256 _periodDuration) external view returns (uint256);
/**
* @notice Getter for the factor of claimable yield when unlocking
* @param _periodDuration the periods duration
* @return the factor of claimable yield of the last period
*/
function getUnlockYieldFactor(uint256 _periodDuration) external view returns (uint256);
/**
* @notice Getter for the list of future durations registered in the contract
* @return the list of futures duration
*/
function getDurations() external view returns (uint256[] memory);
/**
* @notice Register a newly created future in the registry
* @param _newFuture the address of the new future
*/
function registerNewFuture(address _newFuture) external;
/**
* @notice Unregister a future from the registry
* @param _future the address of the future to unregister
*/
function unregisterFuture(address _future) external;
/**
* @notice Start all the futures that have a defined periods duration to synchronize them
* @param _periodDuration the periods duration of the futures to start
*/
function startFuturesByPeriodDuration(uint256 _periodDuration) external;
/**
* @notice Getter for the futures by periods duration
* @param _periodDuration the periods duration of the futures to return
*/
function getFuturesWithDuration(uint256 _periodDuration) external view returns (address[] memory);
/**
* @notice Register the sender to the corresponding future
* @param _user the address of the user
* @param _futureAddress the addresses of the futures to claim the fyts from
*/
function claimSelectedYield(address _user, address[] memory _futureAddress) external;
function getRoleMember(bytes32 role, uint256 index) external view returns (address); // OZ ACL getter
/**
* @notice Interrupt a future avoiding news registrations
* @param _future the address of the future to pause
* @dev should only be called in extraordinary situations by the admin of the contract
*/
function pauseFuture(address _future) external;
/**
* @notice Resume a future that has been paused
* @param _future the address of the future to resume
* @dev should only be called in extraordinary situations by the admin of the contract
*/
function resumeFuture(address _future) external;
}
pragma solidity 0.7.6;
interface IFutureVault {
/**
* @notice Intializer
* @param _futureAddress the address of the corresponding future
* @param _adminAddress the address of the corresponding admin
*/
function initialize(address _futureAddress, address _adminAddress) external;
/**
* @notice Getter for the future address
* @return the future address linked to this vault
*/
function getFutureAddress() external view returns (address);
/**
* @notice Approve another token to be transfered from this contract by the future
*/
function approveAdditionalToken(address _tokenAddress) external;
}
pragma solidity 0.7.6;
interface ILiquidityGauge {
/**
* @notice Contract Initializer
* @param _gaugeController the address of the gauge controller
* @param _future the address of the corresponding future
*/
function initialize(address _gaugeController, address _future) external;
/**
* @notice Register new liquidity added to the future
* @param _amount the liquidity amount added
* @dev must be called from the future contract
*/
function registerNewFutureLiquidity(uint256 _amount) external;
/**
* @notice Unregister liquidity withdrawn from to the future
* @param _amount the liquidity amount withdrawn
* @dev must be called from the future contract
*/
function unregisterFutureLiquidity(uint256 _amount) external;
/**
* @notice update gauge and user liquidity state then return the new redeemable
* @param _user the user to update and return the redeemable of
*/
function updateAndGetRedeemable(address _user) external returns (uint256);
/**
* @notice Log an update of the inflated volume
*/
function updateInflatedVolume() external;
/**
* @notice Getter for the last inflated amount
* @return the last inflated amount
*/
function getLastInflatedAmount() external view returns (uint256);
/**
* @notice Getter for redeemable APWs of one user
* @param _user the user to check the redeemable APW of
* @return the amount of redeemable APW
*/
function getUserRedeemable(address _user) external view returns (uint256);
/**
* @notice Register new user liquidity
* @param _user the user to register the liquidity of
*/
function registerUserLiquidity(address _user) external;
/**
* @notice Delete a user liquidity registration
* @param _user the user to delete the liquidity registration of
*/
function deleteUserLiquidityRegistration(address _user) external;
/**
* @notice Register new user liquidity
* @param _sender the user to transfer the liquidity from
* @param _receiver the user to transfer the liquidity to
* @param _amount the amount of liquidity to transfer
*/
function transferUserLiquidty(
address _sender,
address _receiver,
uint256 _amount
) external;
/**
* @notice Update the current stored liquidity of one user
* @param _user the user to update the liquidity of
*/
function updateUserLiquidity(address _user) external;
/**
* @notice Remove liquidity from on user address
* @param _user the user to remove the liquidity from
* @param _amount the amount of liquidity to remove
*/
function removeUserLiquidity(address _user, uint256 _amount) external;
}
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
interface IRegistry {
/**
* @notice Initializer of the contract
* @param _admin the address of the admin of the contract
*/
function initialize(address _admin) external;
/* Setters */
/**
* @notice Setter for the treasury address
* @param _newTreasury the address of the new treasury
*/
function setTreasury(address _newTreasury) external;
/**
* @notice Setter for the gauge controller address
* @param _newGaugeController the address of the new gauge controller
*/
function setGaugeController(address _newGaugeController) external;
/**
* @notice Setter for the controller address
* @param _newController the address of the new controller
*/
function setController(address _newController) external;
/**
* @notice Setter for the APW token address
* @param _newAPW the address of the APW token
*/
function setAPW(address _newAPW) external;
/**
* @notice Setter for the proxy factory address
* @param _proxyFactory the address of the new proxy factory
*/
function setProxyFactory(address _proxyFactory) external;
/**
* @notice Setter for the liquidity gauge address
* @param _liquidityGaugeLogic the address of the new liquidity gauge logic
*/
function setLiquidityGaugeLogic(address _liquidityGaugeLogic) external;
/**
* @notice Setter for the APWine IBT logic address
* @param _APWineIBTLogic the address of the new APWine IBT logic
*/
function setAPWineIBTLogic(address _APWineIBTLogic) external;
/**
* @notice Setter for the APWine FYT logic address
* @param _FYTLogic the address of the new APWine FYT logic
*/
function setFYTLogic(address _FYTLogic) external;
/**
* @notice Setter for the maths utils address
* @param _mathsUtils the address of the new math utils
*/
function setMathsUtils(address _mathsUtils) external;
/**
* @notice Setter for the naming utils address
* @param _namingUtils the address of the new naming utils
*/
function setNamingUtils(address _namingUtils) external;
/**
* @notice Getter for the controller address
* @return the address of the controller
*/
function getControllerAddress() external view returns (address);
/**
* @notice Getter for the treasury address
* @return the address of the treasury
*/
function getTreasuryAddress() external view returns (address);
/**
* @notice Getter for the gauge controller address
* @return the address of the gauge controller
*/
function getGaugeControllerAddress() external view returns (address);
/**
* @notice Getter for the DAO address
* @return the address of the DAO that has admin rights on the APW token
*/
function getDAOAddress() external returns (address);
/**
* @notice Getter for the APW token address
* @return the address the APW token
*/
function getAPWAddress() external view returns (address);
/**
* @notice Getter for the vesting contract address
* @return the vesting contract address
*/
function getVestingAddress() external view returns (address);
/**
* @notice Getter for the proxy factory address
* @return the proxy factory address
*/
function getProxyFactoryAddress() external view returns (address);
/**
* @notice Getter for liquidity gauge logic address
* @return the liquidity gauge logic address
*/
function getLiquidityGaugeLogicAddress() external view returns (address);
/**
* @notice Getter for APWine IBT logic address
* @return the APWine IBT logic address
*/
function getAPWineIBTLogicAddress() external view returns (address);
/**
* @notice Getter for APWine FYT logic address
* @return the APWine FYT logic address
*/
function getFYTLogicAddress() external view returns (address);
/**
* @notice Getter for math utils address
* @return the math utils address
*/
function getMathsUtils() external view returns (address);
/**
* @notice Getter for naming utils address
* @return the naming utils address
*/
function getNamingUtils() external view returns (address);
/* Future factory */
/**
* @notice Register a new future factory in the registry
* @param _futureFactory the address of the future factory contract
* @param _futureFactoryName the name of the future factory
*/
function addFutureFactory(address _futureFactory, string memory _futureFactoryName) external;
/**
* @notice Getter to check if a future factory is registered
* @param _futureFactory the address of the future factory contract to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFutureFactory(address _futureFactory) external view returns (bool);
/**
* @notice Getter for the future factory registered at an index
* @param _index the index of the future factory to return
* @return the address of the corresponding future factory
*/
function getFutureFactoryAt(uint256 _index) external view returns (address);
/**
* @notice Getter for number of future factories registered
* @return the number of future factory registered
*/
function futureFactoryCount() external view returns (uint256);
/**
* @notice Getter for name of a future factory contract
* @param _futureFactory the address of a future factory
* @return the name of the corresponding future factory contract
*/
function getFutureFactoryName(address _futureFactory) external view returns (string memory);
/* Future platform */
/**
* @notice Register a new future platform in the registry
* @param _futureFactory the address of the future factory
* @param _futurePlatformName the name of the future platform
* @param _future the address of the future contract logic
* @param _futureWallet the address of the future wallet contract logic
* @param _futureVault the name of the future vault contract logic
*/
function addFuturePlatform(
address _futureFactory,
string memory _futurePlatformName,
address _future,
address _futureWallet,
address _futureVault
) external;
/**
* @notice Getter to check if a future platform is registered
* @param _futurePlatformName the name of the future platform to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFuturePlatform(string memory _futurePlatformName) external view returns (bool);
/**
* @notice Getter for the future platform contracts
* @param _futurePlatformName the name of the future platform
* @return the addresses of 0) the future logic 1) the future wallet logic 2) the future vault logic
*/
function getFuturePlatform(string memory _futurePlatformName) external view returns (address[3] memory);
/**
* @notice Getter the total count of future platftroms registered
* @return the number of future platforms registered
*/
function futurePlatformsCount() external view returns (uint256);
/**
* @notice Getter the list of platforms names registered
* @return the list of platform names registered
*/
function getFuturePlatformNames() external view returns (string[] memory);
/**
* @notice Remove a future platform from the registry
* @param _futurePlatformName the name of the future platform to remove from the registry
*/
function removeFuturePlatform(string memory _futurePlatformName) external;
/* Futures */
/**
* @notice Add a future to the registry
* @param _future the address of the future to add to the registry
*/
function addFuture(address _future) external;
/**
* @notice Remove a future from the registry
* @param _future the address of the future to remove from the registry
*/
function removeFuture(address _future) external;
/**
* @notice Getter to check if a future is registered
* @param _future the address of the future to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFuture(address _future) external view returns (bool);
/**
* @notice Getter for the future registered at an index
* @param _index the index of the future to return
* @return the address of the corresponding future
*/
function getFutureAt(uint256 _index) external view returns (address);
/**
* @notice Getter for number of future registered
* @return the number of future registered
*/
function futureCount() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface ERC20 is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external returns (string memory);
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external returns (uint8);
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
|
Set liquidity gauge address _liquidityGauge the address of the new liquidity gauge needs corresponding permissions for sender/
|
function setLiquidityGauge(address _liquidityGauge) public {
require(hasRole(FUTURE_DEPLOYER, msg.sender), "Caller is not allowed to set the liquidity gauge address");
liquidityGauge = ILiquidityGauge(_liquidityGauge);
emit LiquidityGaugeSet(_liquidityGauge);
}
| 5,944,938
|
./full_match/1/0x184e48FA8B332D3D3FB08eDa535Fd7591e340Bb2/sources/contracts/NFT/NFTByMetadrop.sol
|
==================================================================================================================== MINTING =====================================================================================================================/ ____________________________________________________________________________________________________________________ -->MINT (function) metadropMint Mint tokens. Can only be called from a valid primary market contract --------------------------------------------------------------------------------------------------------------------- caller_ The address that has called mint through the primary sale module. --------------------------------------------------------------------------------------------------------------------- recipient_ The address that will receive new assets. --------------------------------------------------------------------------------------------------------------------- allowanceAddress_ The address that has an allowance being used in this mint. This will be the same as the calling address in almost all cases. An example of when they may differ is in a list mint where the caller is a delegate of another address with an allowance in the list. The caller is performing the mint, but it is the allowance for the allowance address that is being checked and decremented in this mint. --------------------------------------------------------------------------------------------------------------------- quantityToMint_ The quantity of tokens to be minted --------------------------------------------------------------------------------------------------------------------- unitPrice_ The unit price for each token --------------------------------------------------------------------------------------------------------------------- _____________________________________________________________________________________________________________________/
|
function metadropMint(
address caller_,
address recipient_,
address allowanceAddress_,
uint256 quantityToMint_,
uint256 unitPrice_
) external {
if (recipient_ == address(0) || recipient_ == BURN_ADDRESS) {
revert InvalidRecipient();
}
if (mintingComplete) {
revert MintingIsClosedForever();
}
if (!validPrimaryMarketAddress[msg.sender]) revert InvalidAddress();
if (allocationMethod != TokenAllocationMethod.sequential) {
revert InvalidTokenAllocationMethod();
}
uint256[] memory tokenIds = _mintSequential(recipient_, quantityToMint_);
emit MetadropMint(
allowanceAddress_,
recipient_,
caller_,
msg.sender,
unitPrice_,
tokenIds
);
}
| 4,935,075
|
./partial_match/80001/0x636C4701Fdd1C46e47177cef7032b26402Bf7251/sources/minter1.sol
|
Returns an Ethereum Signed Data with intended validator, created from a `validator` and `data` according to the version 0 of EIP-191. See {recover}./
|
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x00", validator, data));
}
| 8,818,693
|
/**
*Submitted for verification at Etherscan.io on 2022-03-15
*/
/**
*Submitted for verification at Etherscan.io on 2022-03-15
*/
/**
*Submitted for verification at Etherscan.io on 2022-03-05
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.9;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @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);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
/**
* @dev Retuaiodjoaijdoaijdioasoaisdrting on
* overflow.
* aiodjoaijdoaijdioasoaisd
* Couaiodjoaijdoaijdioasoaisd+` operator.
* aiodjoaijdoaijdioasoaisd
* Requirements:
* aiodjoaijdoaijdioasoaisd
* - 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;
}
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;
}
/**
* @dev Raiodjoaijdoaijdioasoaisd reverting on
* overflow.
*
* Caiodjoaijdoaijdioasoaisdtor.
* aiodjoaijdoaijdioasoaisd
* Requirements:
* aiodjoaijdoaijdioasoaisd
* - 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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev aiodjoaijdoaijdioasoaisderts with custom message on
* divisaiodjoaijdoaijdioasoaisdro.
*
* Countaiodjoaijdoaijdioasoaisds function uses a
* `revaiodjoaijdoaijdioasoaisdwhile Solidity
* usesaiodjoaijdoaijdioasoaisdining 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 Returnsaiodjoaijdoaijdioasoaisdgned integer modulo),
* Reaiodjoaijdoaijdioasoaisdero.
*
* Countaiodjoaijdoaijdioasoaisdfunction 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.
*
* CounterpaaiodjoaijdoaijdioasoaisdThis function uses a `revert`
* opcaiodjoaijdoaijdioasoaisdtouched) while Solidity uses an
* invaliaiodjoaijdoaijdioasoaisdaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev aiodjoaijdoaijdioasoaisd
*
* [IMPORTANT]
* ====
* It aiodjoaijdoaijdioasoaisd
* falseaiodjoaijdoaijdioasoaisdaiodjoaijdoaijdioasoaisdact.
*
* Amonaiodjoaijdoaijdioasoaisdaiodjoaijdoaijdioasoaisdlowing
* types of addresses:
*
* - an exaiodjoaijdoaijdioasoaisdaiodjoaijdoaijdioasoaisd
* - a adadadadadadfadnklajdnaodjaiodjoaijdoaijdioasoaisd
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plasthshjsfjsfjdfjdfjfdjdfgjdfgjdfjdfgjdghjdhjdeghyjdghjdghs
* function instead.
*
* If `tasghjsfghjsfhsdfhldmpghยด~mjsghmdpgmhpsยดhdfghd
* funsfghfdshdfghdfhjdfhdfhdfghdfghdfgh.
*
* 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.
* - callinsghdfghรงldkgยด[hdkghkdpยดfghdghdgh.
*
* _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 trsfgsfhshshshsd`.
*
* Requirements:
*
* - the callshhsfghshfsdhsfghfsdghsfh`value`.
* - theshgshjdfsjsjdgfjdgjsjhgdjdhgjgdj
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* thesdfsfsdfsfsfsdfsdfsfsdfsdfsess to
* specific functions.
*
* By defsdfsfsdfsdfsdfdsfsafdfaone that dadfsfasfasdfad
* can later be changed with {transferOwnership}.
*
* Thiadgagaghsadhgsdhsdhglsdngpksdnpgkjsdopkgjsdkgkdsgsdgsdf
* `onlsfgsdfgsfglรงsmnfรงlgksรงlkgnmskfgsgsfgsfgto
* the owner.
*/
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownehjgfhjgfjghjgjhgnew 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;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(block.timestamp > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
// pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Charity(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 ttbcurn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract PoodleShibaInu is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
mapping (address => bool) private bots;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 10000000000 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "Poodle Shiba Inu";
string private _symbol = "POOSHIB";
uint8 private _decimals = 18;
address payable marketingWallet;
address payable treasuryWallet;
uint256 public _taxFee = 0;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 2;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 public _marketingFee = 6;
uint256 private _previousMarketingFee = _marketingFee;
uint256 public _treasuryFee = 6;
uint256 private _previousTreasuryFee = _treasuryFee;
//Sale fees
uint256 public _saleTaxFee = 0;
uint256 public _saleLiquidityFee = 2;
uint256 public _saleTreasuryFee = 6;
uint256 public _saleMarketingFee = 6;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
event SwapAndLiquify(
uint256 tokensIntoLiqudity,
uint256 ethReceived
);
uint256 public minimumTokensBeforeSwap = 1000000 * 10**18;
uint256 public _maxTxAmount = 100000000 * 10**18;
uint256 public maxWalletToken = 200000000 * (10**18);
event SwapTokensForETH(
uint256 amountIn,
address[] path
);
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor(address payable _marketingWallet, address payable _treasuryWallet)
{
_rOwned[owner()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
marketingWallet = _marketingWallet;
treasuryWallet = _treasuryWallet;
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[_treasuryWallet] = true;
_isExcludedFromFee[_marketingWallet] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), owner(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function removeAllFee() private
{
_taxFee = 0;
_liquidityFee = 0;
_treasuryFee = 0;
_marketingFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
_marketingFee = _previousMarketingFee;
_treasuryFee = _previousTreasuryFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private
{
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
bool excludedAccount = _isExcludedFromFee[from] || _isExcludedFromFee[to];
if (from == uniswapV2Pair && !excludedAccount) {
uint256 contractBalanceRecepient = balanceOf(to);
require(contractBalanceRecepient + amount <= maxWalletToken, "Exceeds maximum wallet token amount.");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
to == uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = minimumTokensBeforeSwap;
//add liquidity and send bnb to treasury and marketing wallet
swapAndLiquify(contractTokenBalance);
}
_tokenTransfer(from,to,amount);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 tokensForLiquidity = contractTokenBalance.mul(_saleLiquidityFee).div(_saleLiquidityFee.add(_saleTreasuryFee).add(_saleMarketingFee));
uint256 tokensForMarketingAndTreasury = contractTokenBalance.sub(tokensForLiquidity);
// split the Liquidity token balance into halves
uint256 half = tokensForLiquidity.div(2);
uint256 otherHalf = tokensForLiquidity.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half, address(this)); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
// swap and Send Eth to wallets
swapTokensForEth(tokensForMarketingAndTreasury, address(this));
uint256 marketingEthShare = address(this).balance.mul(_saleMarketingFee).div(_saleMarketingFee.add(_saleTreasuryFee));
marketingWallet.transfer(marketingEthShare);
treasuryWallet.transfer(address(this).balance);
emit SwapAndLiquify(half, newBalance);
}
function swapTokensForEth(uint256 tokenAmount, address _to) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
if(allowance(address(this), address(uniswapV2Router)) < tokenAmount) {
_approve(address(this), address(uniswapV2Router), ~uint256(0));
}
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
_to,
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
//this method is responsible for taking all fee where fee is require to be deducted.
function _tokenTransfer(address sender, address recipient, uint256 amount) private
{
if(recipient==uniswapV2Pair)
{
setAllFees(_saleTaxFee, _saleLiquidityFee, _saleTreasuryFee, _saleMarketingFee);
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient])
{
removeAllFee();
}
else
{
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private
{
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
(tTransferAmount, rTransferAmount) = takeMarketing(sender, tTransferAmount, rTransferAmount, tAmount);
(tTransferAmount, rTransferAmount) = takeTreasury(sender, tTransferAmount, rTransferAmount, tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function takeTreasury(address sender, uint256 tTransferAmount, uint256 rTransferAmount, uint256 tAmount) private
returns (uint256, uint256)
{
if(_treasuryFee==0) { return(tTransferAmount, rTransferAmount); }
uint256 tTreasury = tAmount.div(100).mul(_treasuryFee);
uint256 rTreasury = tTreasury.mul(_getRate());
rTransferAmount = rTransferAmount.sub(rTreasury);
tTransferAmount = tTransferAmount.sub(tTreasury);
_rOwned[address(this)] = _rOwned[address(this)].add(rTreasury);
emit Transfer(sender, address(this), tTreasury);
return(tTransferAmount, rTransferAmount);
}
function takeMarketing(address sender, uint256 tTransferAmount, uint256 rTransferAmount, uint256 tAmount) private
returns (uint256, uint256)
{
if(_marketingFee==0) { return(tTransferAmount, rTransferAmount); }
uint256 tMarketing = tAmount.div(100).mul(_marketingFee);
uint256 rMarketing = tMarketing.mul(_getRate());
rTransferAmount = rTransferAmount.sub(rMarketing);
tTransferAmount = tTransferAmount.sub(tMarketing);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketing);
emit Transfer(sender, address(this), tMarketing);
return(tTransferAmount, rTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function setTreasuryWallet(address payable newWallet) external onlyOwner() {
treasuryWallet = newWallet;
}
function setMarketingWallet(address payable newWallet) external onlyOwner() {
marketingWallet = newWallet;
}
function setAllFees(uint256 taxFee, uint256 liquidityFee, uint256 treasuryFee, uint256 marketingFee) private {
_taxFee = taxFee;
_liquidityFee = liquidityFee;
_treasuryFee = treasuryFee;
_marketingFee = marketingFee;
}
function setBuyFees(uint256 taxFee, uint256 liquidityFee, uint256 treasuryFee, uint256 marketingFee)
external onlyOwner() {
setAllFees(taxFee, liquidityFee, treasuryFee, marketingFee);
_previousTaxFee = taxFee;
_previousLiquidityFee = liquidityFee;
_previousMarketingFee = marketingFee;
_previousTreasuryFee = treasuryFee;
}
function setSaleFees(uint256 taxFee, uint256 liquidityFee, uint256 treasuryFee, uint256 marketingFee)
external onlyOwner() {
_saleTaxFee = taxFee;
_saleLiquidityFee = liquidityFee;
_saleTreasuryFee = treasuryFee;
_saleMarketingFee = marketingFee;
}
function setMinimumTokensBeforeSwap(uint256 newAmt) external onlyOwner() {
minimumTokensBeforeSwap = newAmt * (10**18);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function setMaxWalletTokend(uint256 _maxToken) external onlyOwner {
maxWalletToken = _maxToken * (10**18);
}
function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
_maxTxAmount = maxTxAmount * (10**18);
}
}
|
this method is responsible for taking all fee where fee is require to be deducted.
|
function _tokenTransfer(address sender, address recipient, uint256 amount) private
{
if(recipient==uniswapV2Pair)
{
setAllFees(_saleTaxFee, _saleLiquidityFee, _saleTreasuryFee, _saleMarketingFee);
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient])
{
removeAllFee();
}
else
{
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
restoreAllFee();
}
| 2,282,058
|
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./LightToken.sol";
interface IMigratorLight {
enum Platform{
uniswap,
sushiswap
}
// Perform LP token migration from legacy UniswapV2 to LightSwap.
// 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.
// LightSwap must mint EXACTLY the same amount of LightSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token, Platform platform) external returns (IERC20);
}
// LightMain is the master of Light. He can make Light 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 LIGHT is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract LightMain is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant MinMinters = 20;
enum Region{
master,
slave
}
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of LIGHTs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accLightPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accLightPerShare` (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.
uint256 accReward;
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. LIGHTs to distribute per block.
uint256 lastRewardBlock; // Last block number that LIGHTs distribution occurs.
uint256 accLightPerShare; // Accumulated LIGHTs per share, times 1e12. See below.
// Lock LP, until the end of mining.
bool lock;
}
// The LIGHT TOKEN!
LightToken public light;
// LIGHT tokens created per block.
uint256 public lightPerBlock;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorLight public migrator;
// The buy back contract.
address public buyBackContract;
// 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 LIGHT mining starts.
uint256 public startBlock;
uint256 public halfPeriod;
uint256 public maxBlocks;
uint256 public maxSupply;
uint256 public createAreaFee;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
LightToken _light,
uint256 _createAreaFee,
uint256 _lightPerBlock,
uint256 _startBlock,
uint256 _halfPeriod,
uint256 _maxBlocks,
uint256 _maxSupply
) public {
light = _light;
createAreaFee = _createAreaFee;
lightPerBlock = _lightPerBlock;
startBlock = _startBlock;
halfPeriod = _halfPeriod;
maxBlocks = _maxBlocks;
maxSupply = _maxSupply;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, bool _lock) public onlyOwner {
if (_withUpdate) {
massUpdatePools(Region.master);
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accLightPerShare: 0,
lock: _lock
}));
}
// Update the given pool's LIGHT allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools(Region.master);
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending LIGHTs on frontend.
function pendingLight(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accLightPerShare = pool.accLightPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blockRewards = getBlockRewards(pool.lastRewardBlock, block.number, Region.master);
uint256 lightReward = blockRewards.mul(pool.allocPoint).div(totalAllocPoint);
accLightPerShare = accLightPerShare.add(lightReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accLightPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools(Region region) public {
if(region == Region.master){
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}else if(region == Region.master){
uint256 length = slavePoolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updateSlavePool(pid);
}
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 blockRewards = getBlockRewards(pool.lastRewardBlock, block.number, Region.master);
uint256 lightReward = blockRewards.mul(pool.allocPoint).div(totalAllocPoint);
light.mint(address(this), lightReward);
pool.accLightPerShare = pool.accLightPerShare.add(lightReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to LightMain for LIGHT allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accLightPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeLightTransfer(msg.sender, pending);
user.accReward = user.accReward.add(pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accLightPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from LightMain.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.lock == false || pool.lock && block.number >= (startBlock + maxBlocks + 5760));
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accLightPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeLightTransfer(msg.sender, pending);
user.accReward = user.accReward.add(pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accLightPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe light transfer function, just in case if rounding error causes pool to not have enough LIGHTs.
function safeLightTransfer(address _to, uint256 _amount) internal {
uint256 lightBal = light.balanceOf(address(this));
if (_amount > lightBal) {
light.transfer(_to, lightBal);
} else {
light.transfer(_to, _amount);
}
}
// Reduce by 50% per halfPeriod blocks.
function getBlockReward(uint256 number, Region region) public view returns (uint256) {
if (number < startBlock){
return 0;
}
uint256 mintBlocks = number.sub(startBlock);
if (mintBlocks >= maxBlocks){
return 0;
}
uint256 exp = mintBlocks.div(halfPeriod);
uint256 blockReward = lightPerBlock.mul(5 ** exp).div(10 ** exp);
if(blockReward > 0 && blockReward <= lightPerBlock){
if(region == Region.master){
return blockReward.mul(8).div(10);
}
if(region == Region.slave){
return blockReward.mul(2).div(10);
}
return blockReward;
}
return 0;
}
function getBlockRewardNow() public view returns (uint256) {
return getBlockReward(block.number, Region.master) + getBlockReward(block.number, Region.slave);
}
function getBlockRewards(uint256 from, uint256 to, Region region) public view returns (uint256) {
if(light.totalSupply() >= maxSupply){
return 0;
}
if(from < startBlock){
from = startBlock;
}
if(to > startBlock.add(maxBlocks)){
to = startBlock.add(maxBlocks).sub(1);
}
if(from >= to){
return 0;
}
uint256 blockReward1 = getBlockReward(from, region);
uint256 blockReward2 = getBlockReward(to, region);
uint256 blockGap = to.sub(from);
if(blockReward1 != blockReward2){
uint256 blocks2 = to.mod(halfPeriod);
if(blockGap < blocks2){
return 0;
}
uint256 blocks1 = blockGap.sub(blocks2);
return blocks1.mul(blockReward1).add(blocks2.mul(blockReward2));
}
return blockGap.mul(blockReward1);
}
// ------------------------------------------------------------
// --- SLAVE POOLs AND AREAs
// ------------------------------------------------------------
event SlaveDeposit(address indexed user, uint256 indexed pid, uint256 amount);
event SlaveWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event SlaveEmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
// Info of each area.
struct AreaInfo {
address creator;
uint256 creationBlock;
uint256 members;
uint256 amount;
uint256 rewardDebt;
string name;
}
// Info of each area that stakes LP tokens.
mapping (uint256 => AreaInfo[]) public areaInfo;
struct SlaveUserInfo {
uint256 aid;
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of LIGHTs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accLightPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accLightPerShare` (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.
uint256 accReward;
}
// Info of each pool.
struct SlavePoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. LIGHTs to distribute per block.
uint256 lastRewardBlock; // Last block number that LIGHTs distribution occurs.
uint256 minerAccLightPerShare; // Accumulated LIGHTs per share, times 1e12. See below.
uint256 creatorAccLightPerShare; // Accumulated LIGHTs per share, times 1e12. See below.
uint256 totalBadAreaBalance;
uint256 ethForBuyBack;
}
// Info of each pool.
SlavePoolInfo[] public slavePoolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => SlaveUserInfo)) public slaveUserInfo;
uint256 public slaveTotalAllocPoint = 0;
function createArea(uint256 _pid, string memory _name) payable public {
require(msg.value == createAreaFee);
areaInfo[_pid].push(AreaInfo({
creator: msg.sender,
creationBlock: block.number,
members: 0,
amount: 0,
rewardDebt: 0,
name: _name
}));
// Buy back LIGHTs for creators.
SlavePoolInfo storage pool = slavePoolInfo[_pid];
if(buyBackContract != address(0)){
bytes memory callData = abi.encodeWithSignature("buyBackLightForCreators(uint256)", _pid);
(bool success, ) = buyBackContract.call{value: pool.ethForBuyBack.add(msg.value)}(callData);
if(success){
pool.ethForBuyBack = 0;
}
}else{
pool.ethForBuyBack = pool.ethForBuyBack.add(createAreaFee);
}
}
function slavePoolLength() external view returns (uint256) {
return slavePoolInfo.length;
}
function areaLength(uint256 _pid) external view returns (uint256) {
return areaInfo[_pid].length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function addSlavePool(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools(Region.slave);
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
slaveTotalAllocPoint = slaveTotalAllocPoint.add(_allocPoint);
slavePoolInfo.push(SlavePoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
minerAccLightPerShare: 0,
creatorAccLightPerShare: 0,
totalBadAreaBalance: 0,
ethForBuyBack: 0
}));
}
// Update the given pool's LIGHT allocation point. Can only be called by the owner.
function setSlavePool(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools(Region.slave);
}
slaveTotalAllocPoint = slaveTotalAllocPoint.sub(slavePoolInfo[_pid].allocPoint).add(_allocPoint);
slavePoolInfo[_pid].allocPoint = _allocPoint;
}
function slavePendingLightByAid(uint256 _pid, uint256 _aid, address _user) external view returns (uint256) {
if(slaveUserInfo[_pid][_user].aid != _aid){
return 0;
}
return slavePendingLight(_pid, _user);
}
// View function to see pending LIGHTs on frontend.
function slavePendingLight(uint256 _pid, address _user) public view returns (uint256) {
SlavePoolInfo storage pool = slavePoolInfo[_pid];
SlaveUserInfo storage user = slaveUserInfo[_pid][_user];
uint256 minerAccLightPerShare = pool.minerAccLightPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blockRewards = getBlockRewards(pool.lastRewardBlock, block.number, Region.slave);
uint256 lightReward = blockRewards.mul(pool.allocPoint).div(slaveTotalAllocPoint);
uint256 lightRewardForMiner = lightReward.mul(95).div(100);
minerAccLightPerShare = minerAccLightPerShare.add(lightRewardForMiner.mul(1e12).div(lpSupply));
}
return user.amount.mul(minerAccLightPerShare).div(1e12).sub(user.rewardDebt);
}
function slavePendingLightForCreatorByAid(uint256 _pid, uint256 _aid, address _user) external view returns (uint256) {
if(slaveUserInfo[_pid][_user].aid != _aid){
return 0;
}
return slavePendingLightForCreator(_pid, _user);
}
function slavePendingLightForCreator(uint256 _pid, address _user) public view returns (uint256) {
SlaveUserInfo storage user = slaveUserInfo[_pid][_user];
AreaInfo storage area = areaInfo[_pid][user.aid];
if(area.creator != _user || area.members < MinMinters){
return 0;
}
SlavePoolInfo storage pool = slavePoolInfo[_pid];
uint256 creatorAccLightPerShare = pool.creatorAccLightPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blockRewards = getBlockRewards(pool.lastRewardBlock, block.number, Region.slave);
uint256 lightReward = blockRewards.mul(pool.allocPoint).div(slaveTotalAllocPoint);
uint256 lightRewardForCreator = lightReward.mul(5).div(100);
uint256 lpSupply2 = lpSupply.sub(pool.totalBadAreaBalance);
if(lpSupply2 > 0){
creatorAccLightPerShare = creatorAccLightPerShare.add(lightRewardForCreator.mul(1e12).div(lpSupply2));
}
}
return area.amount.mul(creatorAccLightPerShare).div(1e12).sub(area.rewardDebt);
}
// Update reward variables of the given pool to be up-to-date.
function updateSlavePool(uint256 _pid) public {
SlavePoolInfo storage pool = slavePoolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 blockReward = getBlockRewards(pool.lastRewardBlock, block.number, Region.slave);
uint256 lightReward = blockReward.mul(pool.allocPoint).div(slaveTotalAllocPoint);
uint256 lightRewardForMiner = lightReward.mul(95).div(100);
uint256 lightRewardForCreator = lightReward.sub(lightRewardForMiner);
pool.minerAccLightPerShare = pool.minerAccLightPerShare.add(lightRewardForMiner.mul(1e12).div(lpSupply));
uint256 lpSupply2 = lpSupply.sub(pool.totalBadAreaBalance);
if(lpSupply2 > 0){
pool.creatorAccLightPerShare = pool.creatorAccLightPerShare.add(lightRewardForCreator.mul(1e12).div(lpSupply2));
light.mint(address(this), lightReward);
}else{
light.mint(address(this), lightRewardForMiner);
}
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to LightMain for LIGHT allocation.
function slaveDeposit(uint256 _pid, uint256 _aid, uint256 _amount) public {
AreaInfo storage area = areaInfo[_pid][_aid];
require(area.creator != address(0), "invalid area");
SlavePoolInfo storage pool = slavePoolInfo[_pid];
SlaveUserInfo storage user = slaveUserInfo[_pid][msg.sender];
updateSlavePool(_pid);
if (user.amount > 0) {
require(user.aid == _aid, "deposit: invalid aid");
uint256 minerPending = user.amount.mul(pool.minerAccLightPerShare).div(1e12).sub(user.rewardDebt);
if(minerPending > 0) {
safeLightTransfer(msg.sender, minerPending);
user.accReward = user.accReward.add(minerPending);
}
}
if(area.members >= MinMinters){
uint256 creatorPending = area.amount.mul(pool.creatorAccLightPerShare).div(1e12).sub(area.rewardDebt);
if(creatorPending > 0) {
safeLightTransfer(area.creator, creatorPending);
SlaveUserInfo storage creatorInfo = slaveUserInfo[_pid][area.creator];
creatorInfo.accReward = creatorInfo.accReward.add(creatorPending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
// First deposit
if(user.amount == 0){
user.aid = _aid;
area.members = area.members.add(1);
if(area.members == MinMinters){
pool.totalBadAreaBalance = pool.totalBadAreaBalance.sub(area.amount);
}
}
if(area.members < MinMinters){
pool.totalBadAreaBalance = pool.totalBadAreaBalance.add(_amount);
}
user.amount = user.amount.add(_amount);
area.amount = area.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.minerAccLightPerShare).div(1e12);
area.rewardDebt = area.amount.mul(pool.creatorAccLightPerShare).div(1e12);
emit SlaveDeposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from LightMain.
function slaveWithdraw(uint256 _pid, uint256 _amount) public {
SlavePoolInfo storage pool = slavePoolInfo[_pid];
SlaveUserInfo storage user = slaveUserInfo[_pid][msg.sender];
AreaInfo storage area = areaInfo[_pid][user.aid];
require(user.amount >= _amount, "withdraw: not good");
updateSlavePool(_pid);
uint256 minerPending = user.amount.mul(pool.minerAccLightPerShare).div(1e12).sub(user.rewardDebt);
if(minerPending > 0) {
safeLightTransfer(msg.sender, minerPending);
user.accReward = user.accReward.add(minerPending);
}
if(area.members >= MinMinters){
uint256 creatorPending = area.amount.mul(pool.creatorAccLightPerShare).div(1e12).sub(area.rewardDebt);
if(creatorPending > 0) {
safeLightTransfer(area.creator, creatorPending);
SlaveUserInfo storage creatorInfo = slaveUserInfo[_pid][area.creator];
creatorInfo.accReward = creatorInfo.accReward.add(creatorPending);
}
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
if(user.amount == 0){
if(area.members == MinMinters){
pool.totalBadAreaBalance = pool.totalBadAreaBalance.add(area.amount);
}
area.members = area.members.sub(1);
}
if(area.members < MinMinters){
pool.totalBadAreaBalance = pool.totalBadAreaBalance.sub(_amount);
}
area.amount = area.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
area.rewardDebt = area.amount.mul(pool.creatorAccLightPerShare).div(1e12);
user.rewardDebt = user.amount.mul(pool.minerAccLightPerShare).div(1e12);
emit SlaveWithdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function slaveEmergencyWithdraw(uint256 _pid) public {
SlavePoolInfo storage pool = slavePoolInfo[_pid];
SlaveUserInfo storage user = slaveUserInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit SlaveEmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
function setBuyBackContract(address _buyBackContract) public onlyOwner {
buyBackContract = _buyBackContract;
}
// Share LIGHTs for creators;
function shareLightForCreators(uint256 _pid, uint256 _amount) public {
SlavePoolInfo storage pool = slavePoolInfo[_pid];
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 lpSupply2 = lpSupply.sub(pool.totalBadAreaBalance);
if(lpSupply2 > 0){
light.transferFrom(msg.sender, address(this), _amount);
pool.creatorAccLightPerShare = pool.creatorAccLightPerShare.add(_amount.mul(1e12).div(lpSupply2));
}
}
function manualBuyBack(uint256 _pid) public onlyOwner {
SlavePoolInfo storage pool = slavePoolInfo[_pid];
require(buyBackContract != address(0) && pool.ethForBuyBack > 0);
bytes memory callData = abi.encodeWithSignature("buyBackLightForCreators(uint256)", _pid);
(bool success, ) = buyBackContract.call{value: pool.ethForBuyBack}(callData);
if(success){
pool.ethForBuyBack = 0;
}
}
// ---------------------------------------
// Migrate
// ---------------------------------------
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorLight _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, Region region, IMigratorLight.Platform platform) public {
require(address(migrator) != address(0), "migrate: no migrator");
if(region == Region.master){
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, platform);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}else if(region == Region.slave){
SlavePoolInfo storage pool = slavePoolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken, platform);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
}
}
|
Update reward variables of the given pool to be up-to-date.
|
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 blockRewards = getBlockRewards(pool.lastRewardBlock, block.number, Region.master);
uint256 lightReward = blockRewards.mul(pool.allocPoint).div(totalAllocPoint);
light.mint(address(this), lightReward);
pool.accLightPerShare = pool.accLightPerShare.add(lightReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 6,453,512
|
./partial_match/1/0x9Be61833A4a7aFb2c9a0DC90894C5CE82771e396/sources/BallyGang.sol
|
INITIALISE MINT LOGIC AT DEPLOYMENTMINT BALLYG[1-10] -> STATIC 1:1 TOKENSMINT BALLYG[11-388] -> GENERATIVE TOKENSAIRDROPS FOR ARTISTS/INFLUENCERS/GIVEAWAYS/WINNERS
|
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity >=0.7.0 <0.9.0;
constructor() ERC721("Bally Gang", "BALLYG") {
setPayable(address(0x779a516cC09E7Fb12daA2eA4fE961916A4B2e177));
setDeveloper(msg.sender);
_mintLoop(address(0x15023dFD0c33859B5Ace6665eEe7a3d524d65C42),10);
_mintLoop(address(0x15023dFD0c33859B5Ace6665eEe7a3d524d65C42),378);
_mintLoop(address(0x962ca86f2B62a4Df5Bc52B5E694587841a60CCC1),1);
_mintLoop(address(0x51A7fc09428ef488DC175d7c9CAe0dA7903790a7),1);
_mintLoop(address(0xDFE5629Aa0e766F7214E9b970468a56a2bC5441c),8);
_mintLoop(address(0xFF945ade5E911bC29063c88cB64a246D6069fF08),1);
_mintLoop(address(0xCe716c038597c859e3A5a909005C58E7290c2796),1);
_mintLoop(address(0xce50E9aB724a323d8E4753b364338D9056f367Ec),1);
_mintLoop(address(0x0536211ABEB7407B5812060501237C00c56250aC),1);
_mintLoop(address(0x03B8837B2cA7aA8B43Afb6fAb0E2210D729867F6),1);
_mintLoop(address(0xE3f96A5eED631303BC589d766cB5d031197744F7),1);
_mintLoop(address(0xD17348A4aE8Dea65A8B5B0B6CeBAc25DFf511e8f),1);
_mintLoop(address(0xBcf211ba118538E629344644754a51e160349df7),1);
_mintLoop(address(0xef6c1F143Be4259aE8242f4f8489a69Fc4C40786),1);
_mintLoop(address(0x1196Defb47071a0BDf1ba1037FD8ECD1E4b70C42),1);
_mintLoop(address(0xC37621839DF3DE7dFbe5EAED895e526445bE9A32),1);
_mintLoop(address(0x27fB2582BdE984552FAbEA7252b6b96153000DCf),1);
_mintLoop(address(0x31ecAC1A64e90241716E4Da32E988DaB8811a195),1);
_mintLoop(address(0xFF1525Ce1BD6Ec719834964d94Df5324607043c6),1);
_mintLoop(address(0x8B9af980A04c13b8E7F426a87E60f9E166FE36A3),1);
_mintLoop(address(0x875B77c4d368fFC8c634E65EaAE48315B763706F),1);
_mintLoop(address(0x6A70Ce0e14F4aCb32567AF098a66F23E753b2bb2),1);
_mintLoop(address(0x91BBd583B8C16F568B2E11C8C5bEcE75a48aB6d8),1);
_mintLoop(address(0x5073254dCAd429f02D752A649cF1c2041308cA63),1);
_mintLoop(address(0x274276f91BF42E5AE0D4b9C61677F72CE5DaE04a),1);
_mintLoop(address(0x8C9C02511dD1282607D0185bEdEbFa3b90b14B66),1);
_mintLoop(address(0x3cF83c1C8E638A637962B383271EA5ab762aBbEe),1);
_mintLoop(address(0x474958ECD11cE81ce0193228d2Fc7238A53d5FB5),1);
_mintLoop(address(0x85209b80C42f8cc092aaE66f2756B37D95C7ba06),1);
_mintLoop(address(0x7F93FD25a5a8d6d7C1cC5bdB1b03cf57B574ee5C),1);
_mintLoop(address(0x7C062F6377599B31C38D76e193C5F2974CEFC799),1);
_mintLoop(address(0x178473936884F33a11d70f28b6F71758D407A391),1);
_mintLoop(address(0x8a4f1d414b415bBAD8243f52982b1A3d6E736714),1);
_mintLoop(address(0xcc2aDF7D666f49d47a6Ac653E6bEd83447dEDf51),1);
_mintLoop(address(0x1c4ADD21644bf4C47950C22473b09aB0ac604232),1);
_mintLoop(address(0xd0aba2ebb570feF89FE0CB5Fb49c74E944F4D7F3),1);
_mintLoop(address(0xeF311E803235a5993C12341fAD2e8a5650Dc9c71),1);
_mintLoop(address(0xd7f59956E1A850404A4439a68c3c0FC9D376dfB6),1);
_mintLoop(address(0x79cCD5A462A884b479aEe0201ba6c97039cc5C90),1);
_mintLoop(address(0x6aA9393d3085AD378E537Eb29C253F82ba97Cdf4),1);
_mintLoop(address(0xC6d350771bDDA5927052976578C7084AD437A5c3),1);
_mintLoop(address(0xe4f675A59592118ad965c473587DeDcD6080118C),1);
_mintLoop(address(0x57B40a4e2C6CBC234a211D3788eE2338cB71dA4a),1);
_mintLoop(address(0x0c8d78A1a7C7D6eb24bA04e0aA01bAE7E10DeFc8),1);
_mintLoop(address(0x4171F6a8fCAB5787d084bBE648a6ACF2603E39B0),1);
_mintLoop(address(0x8b9f0aB97EF5933Cc1D42F5DBE6B7830D9324b7A),1);
_mintLoop(address(0xEd19EE630B13196650BB65C4b207338d7643b339),1);
_mintLoop(address(0x200b29036f18aA3F804AB523b242598a35E1702F),1);
_mintLoop(address(0x12a7aF59b8768e2692FA55892380D1cBD82F5949),1);
_mintLoop(address(0xB5821e51bd575DbaE78D3a2c52EdB5e00ADebc17),1);
_mintLoop(address(0x7334944be0bC94E09d2067E78Ca7525887695C90),1);
_mintLoop(address(0x58FC45633b8F2761f74d7D1Fc9a5cAE8F0f4ff7A),1);
_mintLoop(address(0xa91f6B4930c7203f8A394F8006035434352aBd44),1);
_mintLoop(address(0xb656db26072656A4d72f74f7242DfB754290f99C),1);
_mintLoop(address(0xadece1b5D0F36437E3CB3faFacc5b795799c924e),1);
_mintLoop(address(0x1be41a9e5c7B0E760009412e94062F63f963DB2f),1);
_mintLoop(address(0x9DBBaf0E936aA06c0318eD3e2DcA11ad996AAB3d),1);
_mintLoop(address(0x5Da13Ca9B468941381321517B9BD32d099e3485b),1);
_mintLoop(address(0x89f902B8068c428F0d11f9CD031BF11723DB88AA),1);
}
| 4,244,002
|
//Address: 0xf08bcfe0e509a293b73f8a41473435845c35eaa5
//Contract name: GameLib
//Balance: 0 Ether
//Verification Date: 2/7/2017
//Transacion Count: 1
// CODE STARTS HERE
library ArrayLib {
// Inserts to keep array sorted (assumes input array is sorted)
function insertInPlace(uint8[] storage self, uint8 n) {
uint8 insertingIndex = 0;
while (self.length > 0 && insertingIndex < self.length && self[insertingIndex] < n) {
insertingIndex += 1;
}
self.length += 1;
for (uint8 i = uint8(self.length) - 1; i > insertingIndex; i--) {
self[i] = self[i - 1];
}
self[insertingIndex] = n;
}
}
library DeckLib {
using ArrayLib for uint8[];
enum Suit { Spades, Hearts, Clubs, Diamonds }
uint8 constant cardsPerSuit = 13;
uint8 constant suits = 4;
uint8 constant totalCards = cardsPerSuit * suits;
struct Deck {
uint8[] usedCards; // always has to be sorted
address player;
uint256 gameID;
}
function init(Deck storage self, uint256 gameID) {
self.usedCards = new uint8[](0);
self.player = msg.sender;
self.gameID = gameID;
}
function getCard(Deck storage self, uint256 blockNumber) returns (uint8) {
uint cardIndex = self.usedCards.length;
if (cardIndex >= totalCards) throw;
uint8 r = uint8(getRandomNumber(blockNumber, self.player, self.gameID, cardIndex, totalCards - cardIndex));
for (uint8 i = 0; i < cardIndex; i++) {
if (self.usedCards[i] <= r) r += 1;
}
self.usedCards.insertInPlace(r);
return r;
}
function cardDescription(uint8 self) constant returns (Suit, uint8) {
return (Suit(self / cardsPerSuit), cardFacevalue(self));
}
function cardEmojified(uint8 self) constant returns (uint8, string) {
string memory emojiSuit;
var (suit, number) = cardDescription(self);
if (suit == Suit.Clubs) emojiSuit = "โฃ๏ธ";
else if (suit == Suit.Diamonds) emojiSuit = "โฆ๏ธ";
else if (suit == Suit.Hearts) emojiSuit = "โฅ๏ธ";
else if (suit == Suit.Spades) emojiSuit = "โ ๏ธ";
return (number, emojiSuit);
}
function cardFacevalue(uint8 self) constant returns (uint8) {
return 1 + self % cardsPerSuit;
}
function blackjackValue(uint8 self) constant returns (uint8) {
uint8 cardValue = cardFacevalue(self);
return cardValue < 10 ? cardValue : 10;
}
function getRandomNumber(uint b, address player, uint256 gameID, uint n, uint m) constant returns (uint) {
// Uses blockhash as randomness source.
// Credits: https://github.com/Bunjin/Rouleth/blob/master/Provably_Fair_No_Cheating.md
bytes32 blockHash = block.blockhash(b);
if (blockHash == 0x0) throw;
return uint(uint256(keccak256(blockHash, player, gameID, n)) % m);
}
}
library GameLib {
using DeckLib for *;
uint8 constant houseLimit = 17;
uint8 constant target = 21;
enum ComparaisonResult { First, Second, Tie }
enum GameState { InitialCards, Waiting, Hit, Stand, Finished }
enum GameResult { Ongoing, House, Tie, Player, PlayerNatural }
struct Game {
address player;
uint256 bet;
uint256 payout;
uint256 gameID;
DeckLib.Deck deck;
uint8[] houseCards;
uint8[] playerCards;
uint256 actionBlock; // Block on which commitment to perform an action happens.
GameState state;
GameResult result;
bool closed;
}
function init(Game storage self, uint256 gameID) {
self.player = msg.sender;
self.bet = msg.value;
self.payout = 0;
self.houseCards = new uint8[](0);
self.playerCards = new uint8[](0);
self.actionBlock = block.number;
self.state = GameState.InitialCards;
self.result = GameResult.Ongoing;
self.closed = false;
self.gameID = gameID;
self.deck.init(gameID);
}
function tick(Game storage self) returns (bool) {
if (block.number <= self.actionBlock) return false; // Can't tick yet
if (self.actionBlock + 255 < block.number) {
endGame(self, GameResult.House);
return true;
}
if (!needsTick(self)) return true; // not needed, everything is fine
if (self.state == GameState.InitialCards) dealInitialCards(self);
if (self.state == GameState.Hit) dealHitCard(self);
if (self.state == GameState.Stand) {
dealHouseCards(self);
checkGameResult(self);
} else {
checkGameContinues(self);
}
return true;
}
function needsTick(Game storage self) constant returns (bool) {
if (self.state == GameState.Waiting) return false;
if (self.state == GameState.Finished) return false;
return true;
}
function checkGameResult(Game storage self) {
uint8 houseHand = countHand(self.houseCards);
if (houseHand == target && self.houseCards.length == 2) return endGame(self, GameResult.House); // House natural
ComparaisonResult result = compareHands(houseHand, countHand(self.playerCards));
if (result == ComparaisonResult.First) return endGame(self, GameResult.House);
if (result == ComparaisonResult.Second) return endGame(self, GameResult.Player);
endGame(self, GameResult.Tie);
}
function checkGameContinues(Game storage self) {
uint8 playerHand = countHand(self.playerCards);
if (playerHand == target && self.playerCards.length == 2) return endGame(self, GameResult.PlayerNatural); // player natural
if (playerHand > target) return endGame(self, GameResult.House); // Player busted
if (playerHand == target) {
// Player is forced to stand with 21
uint256 currentActionBlock = self.actionBlock;
playerDecision(self, GameState.Stand);
self.actionBlock = currentActionBlock;
if (!tick(self)) throw; // Forces tick, commitment to play actually happened past block
}
}
function playerDecision(Game storage self, GameState decision) {
if (self.state != GameState.Waiting) throw;
if (decision != GameState.Hit && decision != GameState.Stand) throw;
self.state = decision;
self.actionBlock = block.number;
}
function dealInitialCards(Game storage self) private {
self.playerCards.push(self.deck.getCard(self.actionBlock));
self.houseCards.push(self.deck.getCard(self.actionBlock));
self.playerCards.push(self.deck.getCard(self.actionBlock));
self.state = GameState.Waiting;
}
function dealHitCard(Game storage self) private {
self.playerCards.push(self.deck.getCard(self.actionBlock));
self.state = GameState.Waiting;
}
function dealHouseCards(Game storage self) private {
self.houseCards.push(self.deck.getCard(self.actionBlock));
if (countHand(self.houseCards) < houseLimit) dealHouseCards(self);
}
function endGame(Game storage self, GameResult result) {
self.result = result;
self.state = GameState.Finished;
self.payout = payoutForResult(self.result, self.bet);
closeGame(self);
}
function closeGame(Game storage self) private {
if (self.closed) throw; // cannot re-close
if (self.state != GameState.Finished) throw; // not closable
self.closed = true;
if (self.payout > 0) {
if (!self.player.send(self.payout)) throw;
}
}
function payoutForResult(GameResult result, uint256 bet) private returns (uint256) {
if (result == GameResult.PlayerNatural) return bet * 5 / 2; // bet + 1.5x bet
if (result == GameResult.Player) return bet * 2; // doubles bet
if (result == GameResult.Tie) return bet; // returns bet
return 0;
}
function countHand(uint8[] memory hand) returns (uint8) {
uint8[] memory possibleSums = new uint8[](1);
for (uint i = 0; i < hand.length; i++) {
uint8 value = hand[i].blackjackValue();
uint l = possibleSums.length;
for (uint j = 0; j < l; j++) {
possibleSums[j] += value;
if (value == 1) { // is Ace
possibleSums = appendArray(possibleSums, possibleSums[j] + 10); // Fork possible sum with 11 as ace value.
}
}
}
return bestSum(possibleSums);
}
function bestSum(uint8[] possibleSums) returns (uint8 bestSum) {
bestSum = 50; // very bad hand
for (uint i = 0; i < possibleSums.length; i++) {
if (compareHands(bestSum, possibleSums[i]) == ComparaisonResult.Second) {
bestSum = possibleSums[i];
}
}
return;
}
function appendArray(uint8[] memory array, uint8 n) returns (uint8[] memory) {
uint8[] memory newArray = new uint8[](array.length + 1);
for (uint8 i = 0; i < array.length; i++) {
newArray[i] = array[i];
}
newArray[array.length] = n;
return newArray;
}
function compareHands(uint8 a, uint8 b) returns (ComparaisonResult) {
if (a <= target && b <= target) {
if (a > b) return ComparaisonResult.First;
if (a < b) return ComparaisonResult.Second;
}
if (a > target && b > target) {
if (a < b) return ComparaisonResult.First;
if (a > b) return ComparaisonResult.Second;
}
if (a > target) return ComparaisonResult.Second;
if (b > target) return ComparaisonResult.First;
return ComparaisonResult.Tie;
}
}
|
Player is forced to stand with 21
|
function checkGameContinues(Game storage self) {
uint8 playerHand = countHand(self.playerCards);
if (playerHand == target) {
uint256 currentActionBlock = self.actionBlock;
playerDecision(self, GameState.Stand);
self.actionBlock = currentActionBlock;
}
}
| 984,709
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "../interfaces/IPair.sol";
import "../interfaces/IEnchant.sol";
import "../interfaces/IERC20.sol";
import "../interfaces/ISummoner.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract SoulAura is Ownable {
ISummoner summoner = ISummoner(0xce6ccbB1EdAD497B4d53d829DF491aF70065AB5B);
ISoulSwapPair pair = ISoulSwapPair(0xa2527Af9DABf3E3B4979d7E0493b5e2C6e63dC57); // SOUL-FTM
IEnchant enchant = IEnchant(0x6a1a8368D607c7a808F7BbA4F7aEd1D9EbDE147a);
IERC20 soul = IERC20(0xe2fb177009FF39F52C0134E8007FA0e4BaAcBd07);
IERC20 seance = IERC20(0x124B06C5ce47De7A6e9EFDA71a946717130079E6);
function name() public pure returns (string memory) { return "SoulAura"; }
function symbol() public pure returns (string memory) { return "AURA"; }
function decimals() public pure returns (uint8) { return 18; }
// transfers ownership to the DAO.
constructor() { transferOwnership(0x1C63C726926197BD3CB75d86bCFB1DaeBcD87250); }
// gets the total voting power = twice the reserves in the LP + enchanted seance.
function totalSupply() public view returns (uint) {
// SOUL reserves in the SOUL-FTM LP contract.
(, uint lp_totalSoul, ) = pair.getReserves();
// total SEANCE staked in ENCHANT.
uint enchant_totalSeance = seance.balanceOf(address(enchant));
return lp_totalSoul * 2 + enchant_totalSeance;
}
function balanceOf(address member) public view returns (uint) {
//////////////////////////
// LP BALANCE //
//////////////////////////
uint lp_total = pair.totalSupply();
uint lp_totalSoul = soul.balanceOf(address(pair));
// wallet balance.
uint lp_walletBalance = pair.balanceOf(member);
// staked balance
(uint lp_stakedBalance, ) = summoner.userInfo(1, member);
// lp balance [user]
uint lp_balance = lp_walletBalance + lp_stakedBalance;
// LP voting power is 2X the members' SOUL share in the pool.
uint lp_power = lp_totalSoul * lp_balance / lp_total * 2;
//////////////////////////
// ENCHANT BALANCE //
//////////////////////////
uint enchant_total = enchant.totalSupply();
uint enchant_balance = enchant.balanceOf(member);
uint enchant_totalSeance = seance.balanceOf(address(enchant));
// enchanted voting power is the members' enchanted SEANCE share.
uint enchanted_power = enchant_totalSeance * enchant_balance / enchant_total;
//////////////////////////
// SOUL POWER //
//////////////////////////
// soul power is the members' SOUL balance.
uint soul_power = soul.balanceOf(member);
return lp_power + enchanted_power + soul_power;
}
// gets: member's pooled power
function pooledPower(address member) public view returns (uint raw, uint formatted) {
uint lp_total = pair.totalSupply();
uint lp_totalSoul = soul.balanceOf(address(pair));
// wallet balance.
uint lp_walletBalance = pair.balanceOf(member);
// staked balance
(uint lp_stakedBalance, ) = summoner.userInfo(1, member);
// lp balance [user]
uint lp_balance = lp_walletBalance + lp_stakedBalance;
// LP voting power is 2X the members' SOUL share in the lp pool.
uint lp_power = lp_totalSoul * lp_balance / lp_total * 2;
return (lp_power, fromWei(lp_power));
}
// gets: member's enchanted power
function enchantedPower(address member) public view returns (uint raw, uint formatted) {
uint enchant_total = enchant.totalSupply();
uint enchant_balance = enchant.balanceOf(member);
uint enchant_totalSeance = seance.balanceOf(address(enchant));
// enchanted voting power is the members' enchanted SEANCE share.
uint enchanted_power = enchant_totalSeance * enchant_balance / enchant_total;
return (enchanted_power, fromWei(enchanted_power));
}
// gets: member's SOUL power
function soulPower(address member) public view returns (uint raw, uint formatted) {
// soul power is the members' SOUL balance.
uint soul_power = soul.balanceOf(member);
return (soul_power, fromWei(soul_power));
}
// gets: sender's pooled power
function pooledPower() public view returns (uint raw, uint formatted) {
uint lp_total = pair.totalSupply();
uint lp_totalSoul = soul.balanceOf(address(pair));
// wallet balance.
uint lp_walletBalance = pair.balanceOf(msg.sender);
// staked balance
(uint lp_stakedBalance, ) = summoner.userInfo(1, msg.sender);
// lp balance [user]
uint lp_balance = lp_walletBalance + lp_stakedBalance;
// LP voting power is 2X the sender's SOUL share in the lp pool.
uint lp_power = lp_totalSoul * lp_balance / lp_total * 2;
return (lp_power, fromWei(lp_power));
}
// gets: sender's enchanted power
function enchantedPower() public view returns (uint raw, uint formatted) {
uint enchant_total = enchant.totalSupply();
uint enchant_balance = enchant.balanceOf(msg.sender);
uint enchant_totalSeance = seance.balanceOf(address(enchant));
// enchanted voting power is the sender's enchanted SEANCE share.
uint enchanted_power = enchant_totalSeance * enchant_balance / enchant_total;
return (enchanted_power, fromWei(enchanted_power));
}
// gets: sender's SOUL power
function soulPower() public view returns (uint raw, uint formatted) {
// soul power is the sender's SOUL balance.
uint soul_power = soul.balanceOf(msg.sender);
return (soul_power, fromWei(soul_power));
}
// disables ERC20 functionality.
function allowance(address, address) public pure returns (uint) { return 0; }
function transfer(address, uint) public pure returns (bool) { return false; }
function approve(address, uint) public pure returns (bool) { return false; }
function transferFrom(address, address, uint) public pure returns (bool) { return false; }
// conversion helper functions
function toWei(uint intNum) public pure returns (uint bigInt) { return intNum * 10**18; }
function fromWei(uint bigInt) public pure returns (uint intNum) { return bigInt / 10**18; }
}
|
gets: sender's SOUL power soul power is the sender's SOUL balance.
|
function soulPower() public view returns (uint raw, uint formatted) {
uint soul_power = soul.balanceOf(msg.sender);
return (soul_power, fromWei(soul_power));
}
| 14,094,050
|
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {IBToken} from "../interfaces/IBToken.sol";
import {IDebtToken} from "../interfaces/IDebtToken.sol";
import {ILendPoolLoan} from "../interfaces/ILendPoolLoan.sol";
import {ILendPool} from "../interfaces/ILendPool.sol";
import {IReserveOracleGetter} from "../interfaces/IReserveOracleGetter.sol";
import {INFTOracleGetter} from "../interfaces/INFTOracleGetter.sol";
import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol";
import {Errors} from "../libraries/helpers/Errors.sol";
import {WadRayMath} from "../libraries/math/WadRayMath.sol";
import {GenericLogic} from "../libraries/logic/GenericLogic.sol";
import {PercentageMath} from "../libraries/math/PercentageMath.sol";
import {ReserveLogic} from "../libraries/logic/ReserveLogic.sol";
import {NftLogic} from "../libraries/logic/NftLogic.sol";
import {ValidationLogic} from "../libraries/logic/ValidationLogic.sol";
import {ReserveConfiguration} from "../libraries/configuration/ReserveConfiguration.sol";
import {NftConfiguration} from "../libraries/configuration/NftConfiguration.sol";
import {DataTypes} from "../libraries/types/DataTypes.sol";
import {LendPoolStorage} from "./LendPoolStorage.sol";
import {AddressUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import {IERC721ReceiverUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {ContextUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
/**
* @title LendPool contract
* @dev Main point of interaction with an Bend protocol's market
* - Users can:
* # Deposit
* # Withdraw
* # Borrow
* # Repay
* # Auction
* # Liquidate
* - To be covered by a proxy contract, owned by the LendPoolAddressesProvider of the specific market
* - All admin functions are callable by the LendPoolConfigurator contract defined also in the
* LendPoolAddressesProvider
* @author Bend
**/
contract LendPool is Initializable, ILendPool, LendPoolStorage, ContextUpgradeable, IERC721ReceiverUpgradeable {
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
using ReserveLogic for DataTypes.ReserveData;
using NftLogic for DataTypes.NftData;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using NftConfiguration for DataTypes.NftConfigurationMap;
modifier whenNotPaused() {
_whenNotPaused();
_;
}
modifier onlyLendPoolConfigurator() {
_onlyLendPoolConfigurator();
_;
}
function _whenNotPaused() internal view {
require(!_paused, Errors.LP_IS_PAUSED);
}
function _onlyLendPoolConfigurator() internal view {
require(_addressesProvider.getLendPoolConfigurator() == _msgSender(), Errors.LP_CALLER_NOT_LEND_POOL_CONFIGURATOR);
}
/**
* @dev Function is invoked by the proxy contract when the LendPool contract is added to the
* LendPoolAddressesProvider of the market.
* - Caching the address of the LendPoolAddressesProvider in order to reduce gas consumption
* on subsequent operations
* @param provider The address of the LendPoolAddressesProvider
**/
function initialize(ILendPoolAddressesProvider provider) public initializer {
_maxNumberOfReserves = 32;
_maxNumberOfNfts = 256;
_addressesProvider = provider;
}
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying bTokens.
* - E.g. User deposits 100 USDC and gets in return 100 bUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the bTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of bTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external override whenNotPaused {
require(onBehalfOf != address(0), Errors.VL_INVALID_ONBEHALFOF_ADDRESS);
DataTypes.ReserveData storage reserve = _reserves[asset];
address bToken = reserve.bTokenAddress;
require(bToken != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
ValidationLogic.validateDeposit(reserve, amount);
reserve.updateState();
reserve.updateInterestRates(asset, bToken, amount, 0);
IERC20Upgradeable(asset).safeTransferFrom(_msgSender(), bToken, amount);
IBToken(bToken).mint(onBehalfOf, amount, reserve.liquidityIndex);
emit Deposit(_msgSender(), asset, amount, onBehalfOf, referralCode);
}
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent bTokens owned
* E.g. User has 100 bUSDC, calls withdraw() and receives 100 USDC, burning the 100 bUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole bToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external override whenNotPaused returns (uint256) {
require(to != address(0), Errors.VL_INVALID_TARGET_ADDRESS);
DataTypes.ReserveData storage reserve = _reserves[asset];
address bToken = reserve.bTokenAddress;
require(bToken != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
uint256 userBalance = IBToken(bToken).balanceOf(_msgSender());
uint256 amountToWithdraw = amount;
if (amount == type(uint256).max) {
amountToWithdraw = userBalance;
}
ValidationLogic.validateWithdraw(reserve, amountToWithdraw, userBalance);
reserve.updateState();
reserve.updateInterestRates(asset, bToken, 0, amountToWithdraw);
IBToken(bToken).burn(_msgSender(), to, amountToWithdraw, reserve.liquidityIndex);
emit Withdraw(_msgSender(), asset, amountToWithdraw, to);
return amountToWithdraw;
}
struct ExecuteBorrowLocalVars {
address initiator;
uint256 ltv;
uint256 liquidationThreshold;
uint256 liquidationBonus;
uint256 loanId;
address reserveOracle;
address nftOracle;
address loanAddress;
}
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset
* - E.g. User borrows 100 USDC, receiving the 100 USDC in his wallet
* and lock collateral asset in contract
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param nftAsset The address of the underlying nft used as collateral
* @param nftTokenId The token ID of the underlying nft used as collateral
* @param onBehalfOf Address of the user who will receive the loan. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function borrow(
address asset,
uint256 amount,
address nftAsset,
uint256 nftTokenId,
address onBehalfOf,
uint16 referralCode
) external override whenNotPaused {
require(onBehalfOf != address(0), Errors.VL_INVALID_ONBEHALFOF_ADDRESS);
ExecuteBorrowLocalVars memory vars;
vars.initiator = _msgSender();
DataTypes.ReserveData storage reserveData = _reserves[asset];
DataTypes.NftData storage nftData = _nfts[nftAsset];
// update state MUST BEFORE get borrow amount which is depent on latest borrow index
reserveData.updateState();
// Convert asset amount to ETH
vars.reserveOracle = _addressesProvider.getReserveOracle();
vars.nftOracle = _addressesProvider.getNFTOracle();
vars.loanAddress = _addressesProvider.getLendPoolLoan();
vars.loanId = ILendPoolLoan(vars.loanAddress).getCollateralLoanId(nftAsset, nftTokenId);
ValidationLogic.validateBorrow(
onBehalfOf,
asset,
amount,
reserveData,
nftAsset,
nftData,
vars.loanAddress,
vars.loanId,
vars.reserveOracle,
vars.nftOracle
);
if (vars.loanId == 0) {
IERC721Upgradeable(nftAsset).safeTransferFrom(_msgSender(), address(this), nftTokenId);
vars.loanId = ILendPoolLoan(vars.loanAddress).createLoan(
vars.initiator,
onBehalfOf,
nftAsset,
nftTokenId,
nftData.bNftAddress,
asset,
amount,
reserveData.variableBorrowIndex
);
} else {
ILendPoolLoan(vars.loanAddress).updateLoan(
vars.initiator,
vars.loanId,
amount,
0,
reserveData.variableBorrowIndex
);
}
IDebtToken(reserveData.debtTokenAddress).mint(vars.initiator, onBehalfOf, amount, reserveData.variableBorrowIndex);
// update interest rate according latest borrow amount (utilizaton)
reserveData.updateInterestRates(asset, reserveData.bTokenAddress, 0, amount);
IBToken(reserveData.bTokenAddress).transferUnderlyingTo(vars.initiator, amount);
emit Borrow(
vars.initiator,
asset,
amount,
nftAsset,
nftTokenId,
onBehalfOf,
reserveData.currentVariableBorrowRate,
vars.loanId,
referralCode
);
}
struct RepayLocalVars {
address initiator;
address poolLoan;
address onBehalfOf;
uint256 loanId;
bool isUpdate;
uint256 borrowAmount;
uint256 repayAmount;
}
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent loan owned
* - E.g. User repays 100 USDC, burning loan and receives collateral asset
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param amount The amount to repay
**/
function repay(
address nftAsset,
uint256 nftTokenId,
uint256 amount
) external override whenNotPaused returns (uint256, bool) {
RepayLocalVars memory vars;
vars.initiator = _msgSender();
vars.poolLoan = _addressesProvider.getLendPoolLoan();
vars.loanId = ILendPoolLoan(vars.poolLoan).getCollateralLoanId(nftAsset, nftTokenId);
require(vars.loanId != 0, Errors.LP_NFT_IS_NOT_USED_AS_COLLATERAL);
DataTypes.LoanData memory loanData = ILendPoolLoan(vars.poolLoan).getLoan(vars.loanId);
DataTypes.ReserveData storage reserveData = _reserves[loanData.reserveAsset];
DataTypes.NftData storage nftData = _nfts[loanData.nftAsset];
// update state MUST BEFORE get borrow amount which is depent on latest borrow index
reserveData.updateState();
(, vars.borrowAmount) = ILendPoolLoan(vars.poolLoan).getLoanReserveBorrowAmount(vars.loanId);
ValidationLogic.validateRepay(reserveData, nftData, loanData, amount, vars.borrowAmount);
vars.repayAmount = vars.borrowAmount;
vars.isUpdate = false;
if (amount < vars.repayAmount) {
vars.isUpdate = true;
vars.repayAmount = amount;
}
if (vars.isUpdate) {
ILendPoolLoan(vars.poolLoan).updateLoan(
vars.initiator,
vars.loanId,
0,
vars.repayAmount,
reserveData.variableBorrowIndex
);
} else {
ILendPoolLoan(vars.poolLoan).repayLoan(
vars.initiator,
vars.loanId,
nftData.bNftAddress,
vars.repayAmount,
reserveData.variableBorrowIndex
);
}
IDebtToken(reserveData.debtTokenAddress).burn(loanData.borrower, vars.repayAmount, reserveData.variableBorrowIndex);
// update interest rate according latest borrow amount (utilizaton)
reserveData.updateInterestRates(loanData.reserveAsset, reserveData.bTokenAddress, vars.repayAmount, 0);
// transfer repay amount to bToken
IERC20Upgradeable(loanData.reserveAsset).safeTransferFrom(
vars.initiator,
reserveData.bTokenAddress,
vars.repayAmount
);
// transfer erc721 to borrower
if (!vars.isUpdate) {
IERC721Upgradeable(loanData.nftAsset).safeTransferFrom(address(this), loanData.borrower, nftTokenId);
}
emit Repay(
vars.initiator,
loanData.reserveAsset,
vars.repayAmount,
loanData.nftAsset,
loanData.nftTokenId,
loanData.borrower,
vars.loanId
);
return (vars.repayAmount, !vars.isUpdate);
}
/**
* @dev Function to auction a non-healthy position collateral-wise
* - The bidder want to buy collateral asset of the user getting liquidated
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param bidPrice The bid price of the bidder want to buy underlying NFT
* @param onBehalfOf Address of the user who will get the underlying NFT, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of NFT
* is a different wallet
**/
function auction(
address nftAsset,
uint256 nftTokenId,
uint256 bidPrice,
address onBehalfOf
) external override whenNotPaused {
address poolLiquidator = _addressesProvider.getLendPoolLiquidator();
//solium-disable-next-line
(bool success, bytes memory result) = poolLiquidator.delegatecall(
abi.encodeWithSignature("auction(address,uint256,uint256,address)", nftAsset, nftTokenId, bidPrice, onBehalfOf)
);
_verifyCallResult(success, result, Errors.LP_DELEGATE_CALL_FAILED);
}
/**
* @notice Redeem a NFT loan which state is in Auction
* - E.g. User repays 100 USDC, burning loan and receives collateral asset
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param amount The amount to repay the debt and bid fine
**/
function redeem(
address nftAsset,
uint256 nftTokenId,
uint256 amount
) external override whenNotPaused returns (uint256) {
address poolLiquidator = _addressesProvider.getLendPoolLiquidator();
//solium-disable-next-line
(bool success, bytes memory result) = poolLiquidator.delegatecall(
abi.encodeWithSignature("redeem(address,uint256,uint256)", nftAsset, nftTokenId, amount)
);
bytes memory resultData = _verifyCallResult(success, result, Errors.LP_DELEGATE_CALL_FAILED);
uint256 repayAmount = abi.decode(resultData, (uint256));
return (repayAmount);
}
/**
* @dev Function to liquidate a non-healthy position collateral-wise
* - The caller (liquidator) buy collateral asset of the user getting liquidated, and receives
* the collateral asset
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
**/
function liquidate(
address nftAsset,
uint256 nftTokenId,
uint256 amount
) external override whenNotPaused returns (uint256) {
address poolLiquidator = _addressesProvider.getLendPoolLiquidator();
//solium-disable-next-line
(bool success, bytes memory result) = poolLiquidator.delegatecall(
abi.encodeWithSignature("liquidate(address,uint256,uint256)", nftAsset, nftTokenId, amount)
);
bytes memory resultData = _verifyCallResult(success, result, Errors.LP_DELEGATE_CALL_FAILED);
uint256 extraAmount = abi.decode(resultData, (uint256));
return (extraAmount);
}
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external pure override returns (bytes4) {
operator;
from;
tokenId;
data;
return IERC721ReceiverUpgradeable.onERC721Received.selector;
}
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getReserveConfiguration(address asset)
external
view
override
returns (DataTypes.ReserveConfigurationMap memory)
{
return _reserves[asset].configuration;
}
/**
* @dev Returns the configuration of the NFT
* @param asset The address of the asset of the NFT
* @return The configuration of the NFT
**/
function getNftConfiguration(address asset) external view override returns (DataTypes.NftConfigurationMap memory) {
return _nfts[asset].configuration;
}
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view override returns (uint256) {
return _reserves[asset].getNormalizedIncome();
}
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view override returns (uint256) {
return _reserves[asset].getNormalizedDebt();
}
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view override returns (DataTypes.ReserveData memory) {
return _reserves[asset];
}
/**
* @dev Returns the state and configuration of the nft
* @param asset The address of the underlying asset of the nft
* @return The state of the nft
**/
function getNftData(address asset) external view override returns (DataTypes.NftData memory) {
return _nfts[asset];
}
/**
* @dev Returns the loan data of the NFT
* @param nftAsset The address of the NFT
* @param reserveAsset The address of the Reserve
* @return totalCollateralInETH the total collateral in ETH of the NFT
* @return totalCollateralInReserve the total collateral in Reserve of the NFT
* @return availableBorrowsInETH the borrowing power in ETH of the NFT
* @return availableBorrowsInReserve the borrowing power in Reserve of the NFT
* @return ltv the loan to value of the user
* @return liquidationThreshold the liquidation threshold of the NFT
* @return liquidationBonus the liquidation bonus of the NFT
**/
function getNftCollateralData(address nftAsset, address reserveAsset)
external
view
override
returns (
uint256 totalCollateralInETH,
uint256 totalCollateralInReserve,
uint256 availableBorrowsInETH,
uint256 availableBorrowsInReserve,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus
)
{
DataTypes.NftData storage nftData = _nfts[nftAsset];
DataTypes.ReserveData storage reserveData = _reserves[reserveAsset];
(ltv, liquidationThreshold, liquidationBonus) = nftData.configuration.getCollateralParams();
(totalCollateralInETH, totalCollateralInReserve) = GenericLogic.calculateNftCollateralData(
reserveAsset,
reserveData,
nftAsset,
nftData,
_addressesProvider.getReserveOracle(),
_addressesProvider.getNFTOracle()
);
availableBorrowsInETH = GenericLogic.calculateAvailableBorrows(totalCollateralInETH, 0, ltv);
availableBorrowsInReserve = GenericLogic.calculateAvailableBorrows(totalCollateralInReserve, 0, ltv);
}
/**
* @dev Returns the debt data of the NFT
* @param nftAsset The address of the NFT
* @param nftTokenId The token id of the NFT
* @return loanId the loan id of the NFT
* @return reserveAsset the address of the Reserve
* @return totalCollateral the total power of the NFT
* @return totalDebt the total debt of the NFT
* @return availableBorrows the borrowing power left of the NFT
* @return healthFactor the current health factor of the NFT
**/
function getNftDebtData(address nftAsset, uint256 nftTokenId)
external
view
override
returns (
uint256 loanId,
address reserveAsset,
uint256 totalCollateral,
uint256 totalDebt,
uint256 availableBorrows,
uint256 healthFactor
)
{
DataTypes.NftData storage nftData = _nfts[nftAsset];
(uint256 ltv, uint256 liquidationThreshold, ) = nftData.configuration.getCollateralParams();
loanId = ILendPoolLoan(_addressesProvider.getLendPoolLoan()).getCollateralLoanId(nftAsset, nftTokenId);
if (loanId == 0) {
return (0, address(0), 0, 0, 0, 0);
}
DataTypes.LoanData memory loan = ILendPoolLoan(_addressesProvider.getLendPoolLoan()).getLoan(loanId);
reserveAsset = loan.reserveAsset;
DataTypes.ReserveData storage reserveData = _reserves[reserveAsset];
(, totalCollateral) = GenericLogic.calculateNftCollateralData(
reserveAsset,
reserveData,
nftAsset,
nftData,
_addressesProvider.getReserveOracle(),
_addressesProvider.getNFTOracle()
);
(, totalDebt) = GenericLogic.calculateNftDebtData(
reserveAsset,
reserveData,
_addressesProvider.getLendPoolLoan(),
loanId,
_addressesProvider.getReserveOracle()
);
availableBorrows = GenericLogic.calculateAvailableBorrows(totalCollateral, totalDebt, ltv);
if (loan.state == DataTypes.LoanState.Active) {
healthFactor = GenericLogic.calculateHealthFactorFromBalances(totalCollateral, totalDebt, liquidationThreshold);
}
}
/**
* @dev Returns the auction data of the NFT
* @param nftAsset The address of the NFT
* @param nftTokenId The token id of the NFT
* @return loanId the loan id of the NFT
* @return bidderAddress the highest bidder address of the loan
* @return bidPrice the highest bid price in Reserve of the loan
* @return bidBorrowAmount the borrow amount in Reserve of the loan
* @return bidFine the penalty fine of the loan
**/
function getNftAuctionData(address nftAsset, uint256 nftTokenId)
external
view
override
returns (
uint256 loanId,
address bidderAddress,
uint256 bidPrice,
uint256 bidBorrowAmount,
uint256 bidFine
)
{
DataTypes.NftData storage nftData = _nfts[nftAsset];
loanId = ILendPoolLoan(_addressesProvider.getLendPoolLoan()).getCollateralLoanId(nftAsset, nftTokenId);
if (loanId != 0) {
DataTypes.LoanData memory loan = ILendPoolLoan(_addressesProvider.getLendPoolLoan()).getLoan(loanId);
bidderAddress = loan.bidderAddress;
bidPrice = loan.bidPrice;
bidBorrowAmount = loan.bidBorrowAmount;
bidFine = loan.bidPrice.percentMul(nftData.configuration.getRedeemFine());
}
}
struct GetLiquidationPriceLocalVars {
address poolLoan;
uint256 loanId;
uint256 thresholdPrice;
uint256 liquidatePrice;
uint256 paybackAmount;
uint256 remainAmount;
}
function getNftLiquidatePrice(address nftAsset, uint256 nftTokenId)
external
view
override
returns (uint256 liquidatePrice, uint256 paybackAmount)
{
GetLiquidationPriceLocalVars memory vars;
vars.poolLoan = _addressesProvider.getLendPoolLoan();
vars.loanId = ILendPoolLoan(vars.poolLoan).getCollateralLoanId(nftAsset, nftTokenId);
if (vars.loanId == 0) {
return (0, 0);
}
DataTypes.LoanData memory loanData = ILendPoolLoan(vars.poolLoan).getLoan(vars.loanId);
DataTypes.ReserveData storage reserveData = _reserves[loanData.reserveAsset];
DataTypes.NftData storage nftData = _nfts[nftAsset];
(vars.paybackAmount, vars.thresholdPrice, vars.liquidatePrice) = GenericLogic.calculateLoanLiquidatePrice(
vars.loanId,
loanData.reserveAsset,
reserveData,
loanData.nftAsset,
nftData,
vars.poolLoan,
_addressesProvider.getReserveOracle(),
_addressesProvider.getNFTOracle()
);
if (vars.liquidatePrice < vars.paybackAmount) {
vars.liquidatePrice = vars.paybackAmount;
}
return (vars.liquidatePrice, vars.paybackAmount);
}
/**
* @dev Validates and finalizes an bToken transfer
* - Only callable by the overlying bToken of the `asset`
* @param asset The address of the underlying asset of the bToken
* @param from The user from which the bToken are transferred
* @param to The user receiving the bTokens
* @param amount The amount being transferred/withdrawn
* @param balanceFromBefore The bToken balance of the `from` user before the transfer
* @param balanceToBefore The bToken balance of the `to` user before the transfer
*/
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromBefore,
uint256 balanceToBefore
) external view override whenNotPaused {
asset;
from;
to;
amount;
balanceFromBefore;
balanceToBefore;
DataTypes.ReserveData storage reserve = _reserves[asset];
require(_msgSender() == reserve.bTokenAddress, Errors.LP_CALLER_MUST_BE_AN_BTOKEN);
ValidationLogic.validateTransfer(from, reserve);
}
/**
* @dev Returns the list of the initialized reserves
**/
function getReservesList() external view override returns (address[] memory) {
address[] memory _activeReserves = new address[](_reservesCount);
for (uint256 i = 0; i < _reservesCount; i++) {
_activeReserves[i] = _reservesList[i];
}
return _activeReserves;
}
/**
* @dev Returns the list of the initialized nfts
**/
function getNftsList() external view override returns (address[] memory) {
address[] memory _activeNfts = new address[](_nftsCount);
for (uint256 i = 0; i < _nftsCount; i++) {
_activeNfts[i] = _nftsList[i];
}
return _activeNfts;
}
/**
* @dev Set the _pause state of the pool
* - Only callable by the LendPoolConfigurator contract
* @param val `true` to pause the pool, `false` to un-pause it
*/
function setPause(bool val) external override onlyLendPoolConfigurator {
_paused = val;
if (_paused) {
emit Paused();
} else {
emit Unpaused();
}
}
/**
* @dev Returns if the LendPool is paused
*/
function paused() external view override returns (bool) {
return _paused;
}
/**
* @dev Returns the cached LendPoolAddressesProvider connected to this contract
**/
function getAddressesProvider() external view override returns (ILendPoolAddressesProvider) {
return _addressesProvider;
}
function setMaxNumberOfReserves(uint256 val) external override onlyLendPoolConfigurator {
_maxNumberOfReserves = val;
}
/**
* @dev Returns the maximum number of reserves supported to be listed in this LendPool
*/
function getMaxNumberOfReserves() public view override returns (uint256) {
return _maxNumberOfReserves;
}
function setMaxNumberOfNfts(uint256 val) external override onlyLendPoolConfigurator {
_maxNumberOfNfts = val;
}
/**
* @dev Returns the maximum number of nfts supported to be listed in this LendPool
*/
function getMaxNumberOfNfts() public view override returns (uint256) {
return _maxNumberOfNfts;
}
/**
* @dev Initializes a reserve, activating it, assigning an bToken and nft loan and an
* interest rate strategy
* - Only callable by the LendPoolConfigurator contract
* @param asset The address of the underlying asset of the reserve
* @param bTokenAddress The address of the bToken that will be assigned to the reserve
* @param debtTokenAddress The address of the debtToken that will be assigned to the reserve
* @param interestRateAddress The address of the interest rate strategy contract
**/
function initReserve(
address asset,
address bTokenAddress,
address debtTokenAddress,
address interestRateAddress
) external override onlyLendPoolConfigurator {
require(AddressUpgradeable.isContract(asset), Errors.LP_NOT_CONTRACT);
_reserves[asset].init(bTokenAddress, debtTokenAddress, interestRateAddress);
_addReserveToList(asset);
}
/**
* @dev Initializes a nft, activating it, assigning nft loan and an
* interest rate strategy
* - Only callable by the LendPoolConfigurator contract
* @param asset The address of the underlying asset of the nft
**/
function initNft(address asset, address bNftAddress) external override onlyLendPoolConfigurator {
require(AddressUpgradeable.isContract(asset), Errors.LP_NOT_CONTRACT);
_nfts[asset].init(bNftAddress);
_addNftToList(asset);
require(_addressesProvider.getLendPoolLoan() != address(0), Errors.LPC_INVALIED_LOAN_ADDRESS);
IERC721Upgradeable(asset).setApprovalForAll(_addressesProvider.getLendPoolLoan(), true);
ILendPoolLoan(_addressesProvider.getLendPoolLoan()).initNft(asset, bNftAddress);
}
/**
* @dev Updates the address of the interest rate strategy contract
* - Only callable by the LendPoolConfigurator contract
* @param asset The address of the underlying asset of the reserve
* @param rateAddress The address of the interest rate strategy contract
**/
function setReserveInterestRateAddress(address asset, address rateAddress)
external
override
onlyLendPoolConfigurator
{
_reserves[asset].interestRateAddress = rateAddress;
}
/**
* @dev Sets the configuration bitmap of the reserve as a whole
* - Only callable by the LendPoolConfigurator contract
* @param asset The address of the underlying asset of the reserve
* @param configuration The new configuration bitmap
**/
function setReserveConfiguration(address asset, uint256 configuration) external override onlyLendPoolConfigurator {
_reserves[asset].configuration.data = configuration;
}
/**
* @dev Sets the configuration bitmap of the NFT as a whole
* - Only callable by the LendPoolConfigurator contract
* @param asset The address of the asset of the NFT
* @param configuration The new configuration bitmap
**/
function setNftConfiguration(address asset, uint256 configuration) external override onlyLendPoolConfigurator {
_nfts[asset].configuration.data = configuration;
}
function _addReserveToList(address asset) internal {
uint256 reservesCount = _reservesCount;
require(reservesCount < _maxNumberOfReserves, Errors.LP_NO_MORE_RESERVES_ALLOWED);
bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset;
if (!reserveAlreadyAdded) {
_reserves[asset].id = uint8(reservesCount);
_reservesList[reservesCount] = asset;
_reservesCount = reservesCount + 1;
}
}
function _addNftToList(address asset) internal {
uint256 nftsCount = _nftsCount;
require(nftsCount < _maxNumberOfNfts, Errors.LP_NO_MORE_NFTS_ALLOWED);
bool nftAlreadyAdded = _nfts[asset].id != 0 || _nftsList[0] == asset;
if (!nftAlreadyAdded) {
_nfts[asset].id = uint8(nftsCount);
_nftsList[nftsCount] = asset;
_nftsCount = nftsCount + 1;
}
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {ILendPoolAddressesProvider} from "./ILendPoolAddressesProvider.sol";
import {IIncentivesController} from "./IIncentivesController.sol";
import {IScaledBalanceToken} from "./IScaledBalanceToken.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IERC20MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
interface IBToken is IScaledBalanceToken, IERC20Upgradeable, IERC20MetadataUpgradeable {
/**
* @dev Emitted when an bToken is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param treasury The address of the treasury
* @param incentivesController The address of the incentives controller for this bToken
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address treasury,
address incentivesController
);
/**
* @dev Initializes the bToken
* @param addressProvider The address of the address provider where this bToken will be used
* @param treasury The address of the Bend treasury, receiving the fees on this bToken
* @param underlyingAsset The address of the underlying asset of this bToken
*/
function initialize(
ILendPoolAddressesProvider addressProvider,
address treasury,
address underlyingAsset,
uint8 bTokenDecimals,
string calldata bTokenName,
string calldata bTokenSymbol
) external;
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param value The amount being
* @param index The new liquidity index of the reserve
**/
event Mint(address indexed from, uint256 value, uint256 index);
/**
* @dev Mints `amount` bTokens to `user`
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted after bTokens are burned
* @param from The owner of the bTokens, getting them burned
* @param target The address that will receive the underlying
* @param value The amount being burned
* @param index The new liquidity index of the reserve
**/
event Burn(address indexed from, address indexed target, uint256 value, uint256 index);
/**
* @dev Emitted during the transfer action
* @param from The user whose tokens are being transferred
* @param to The recipient
* @param value The amount being transferred
* @param index The new liquidity index of the reserve
**/
event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);
/**
* @dev Burns bTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* @param user The owner of the bTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external;
/**
* @dev Mints bTokens to the reserve treasury
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external;
/**
* @dev Transfers the underlying asset to `target`. Used by the LendPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param user The recipient of the underlying
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (IIncentivesController);
/**
* @dev Returns the address of the underlying asset of this bToken
**/
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol";
import {IIncentivesController} from "./IIncentivesController.sol";
import {IScaledBalanceToken} from "./IScaledBalanceToken.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IERC20MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
/**
* @title IDebtToken
* @author Bend
* @notice Defines the basic interface for a debt token.
**/
interface IDebtToken is IScaledBalanceToken, IERC20Upgradeable, IERC20MetadataUpgradeable {
/**
* @dev Emitted when a debt token is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lend pool
* @param incentivesController The address of the incentives controller
* @param debtTokenDecimals the decimals of the debt token
* @param debtTokenName the name of the debt token
* @param debtTokenSymbol the symbol of the debt token
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address incentivesController,
uint8 debtTokenDecimals,
string debtTokenName,
string debtTokenSymbol
);
/**
* @dev Initializes the debt token.
* @param addressProvider The address of the lend pool
* @param underlyingAsset The address of the underlying asset
* @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's
* @param debtTokenName The name of the token
* @param debtTokenSymbol The symbol of the token
*/
function initialize(
ILendPoolAddressesProvider addressProvider,
address underlyingAsset,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol
) external;
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param value The amount to be minted
* @param index The last index of the reserve
**/
event Mint(address indexed from, uint256 value, uint256 index);
/**
* @dev Mints debt token to the `user` address
* @param user The address receiving the borrowed underlying
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted when variable debt is burnt
* @param user The user which debt has been burned
* @param amount The amount of debt being burned
* @param index The index of the user
**/
event Burn(address indexed user, uint256 amount, uint256 index);
/**
* @dev Burns user variable debt
* @param user The user which debt is burnt
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external;
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (IIncentivesController);
/**
* @dev delegates borrowing power to a user on the specific debt token
* @param delegatee the address receiving the delegated borrowing power
* @param amount the maximum amount being delegated. Delegation will still
* respect the liquidation constraints (even if delegated, a delegatee cannot
* force a delegator HF to go below 1)
**/
function approveDelegation(address delegatee, uint256 amount) external;
/**
* @dev returns the borrow allowance of the user
* @param fromUser The user to giving allowance
* @param toUser The user to give allowance to
* @return the current allowance of toUser
**/
function borrowAllowance(address fromUser, address toUser) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {DataTypes} from "../libraries/types/DataTypes.sol";
interface ILendPoolLoan {
/**
* @dev Emitted on initialization to share location of dependent notes
* @param pool The address of the associated lend pool
*/
event Initialized(address indexed pool);
/**
* @dev Emitted when a loan is created
* @param user The address initiating the action
*/
event LoanCreated(
address indexed user,
address indexed onBehalfOf,
uint256 indexed loanId,
address nftAsset,
uint256 nftTokenId,
address reserveAsset,
uint256 amount,
uint256 borrowIndex
);
/**
* @dev Emitted when a loan is updated
* @param user The address initiating the action
*/
event LoanUpdated(
address indexed user,
uint256 indexed loanId,
address nftAsset,
uint256 nftTokenId,
address reserveAsset,
uint256 amountAdded,
uint256 amountTaken,
uint256 borrowIndex
);
/**
* @dev Emitted when a loan is repaid by the borrower
* @param user The address initiating the action
*/
event LoanRepaid(
address indexed user,
uint256 indexed loanId,
address nftAsset,
uint256 nftTokenId,
address reserveAsset,
uint256 amount,
uint256 borrowIndex
);
/**
* @dev Emitted when a loan is auction by the liquidator
* @param user The address initiating the action
*/
event LoanAuctioned(
address indexed user,
uint256 indexed loanId,
address nftAsset,
uint256 nftTokenId,
uint256 amount,
uint256 borrowIndex,
address bidder,
uint256 price,
address previousBidder,
uint256 previousPrice
);
/**
* @dev Emitted when a loan is redeemed
* @param user The address initiating the action
*/
event LoanRedeemed(
address indexed user,
uint256 indexed loanId,
address nftAsset,
uint256 nftTokenId,
address reserveAsset,
uint256 amountTaken,
uint256 borrowIndex
);
/**
* @dev Emitted when a loan is liquidate by the liquidator
* @param user The address initiating the action
*/
event LoanLiquidated(
address indexed user,
uint256 indexed loanId,
address nftAsset,
uint256 nftTokenId,
address reserveAsset,
uint256 amount,
uint256 borrowIndex
);
function initNft(address nftAsset, address bNftAddress) external;
/**
* @dev Create store a loan object with some params
* @param initiator The address of the user initiating the borrow
* @param onBehalfOf The address receiving the loan
*/
function createLoan(
address initiator,
address onBehalfOf,
address nftAsset,
uint256 nftTokenId,
address bNftAddress,
address reserveAsset,
uint256 amount,
uint256 borrowIndex
) external returns (uint256);
/**
* @dev Update the given loan with some params
*
* Requirements:
* - The caller must be a holder of the loan
* - The loan must be in state Active
* @param initiator The address of the user initiating the borrow
*/
function updateLoan(
address initiator,
uint256 loanId,
uint256 amountAdded,
uint256 amountTaken,
uint256 borrowIndex
) external;
/**
* @dev Repay the given loan
*
* Requirements:
* - The caller must be a holder of the loan
* - The caller must send in principal + interest
* - The loan must be in state Active
*
* @param initiator The address of the user initiating the repay
* @param loanId The loan getting burned
* @param bNftAddress The address of bNFT
*/
function repayLoan(
address initiator,
uint256 loanId,
address bNftAddress,
uint256 amount,
uint256 borrowIndex
) external;
/**
* @dev Auction the given loan
*
* Requirements:
* - The price must be greater than current highest price
* - The loan must be in state Active or Auction
*
* @param initiator The address of the user initiating the auction
* @param loanId The loan getting auctioned
* @param bidPrice The bid price of this auction
*/
function auctionLoan(
address initiator,
uint256 loanId,
address onBehalfOf,
uint256 bidPrice,
uint256 borrowAmount,
uint256 borrowIndex
) external;
/**
* @dev Redeem the given loan with some params
*
* Requirements:
* - The caller must be a holder of the loan
* - The loan must be in state Auction
* @param initiator The address of the user initiating the borrow
*/
function redeemLoan(
address initiator,
uint256 loanId,
uint256 amountTaken,
uint256 borrowIndex
) external;
/**
* @dev Liquidate the given loan
*
* Requirements:
* - The caller must send in principal + interest
* - The loan must be in state Active
*
* @param initiator The address of the user initiating the auction
* @param loanId The loan getting burned
* @param bNftAddress The address of bNFT
*/
function liquidateLoan(
address initiator,
uint256 loanId,
address bNftAddress,
uint256 borrowAmount,
uint256 borrowIndex
) external;
function borrowerOf(uint256 loanId) external view returns (address);
function getCollateralLoanId(address nftAsset, uint256 nftTokenId) external view returns (uint256);
function getLoan(uint256 loanId) external view returns (DataTypes.LoanData memory loanData);
function getLoanCollateralAndReserve(uint256 loanId)
external
view
returns (
address nftAsset,
uint256 nftTokenId,
address reserveAsset,
uint256 scaledAmount
);
function getLoanReserveBorrowScaledAmount(uint256 loanId) external view returns (address, uint256);
function getLoanReserveBorrowAmount(uint256 loanId) external view returns (address, uint256);
function getLoanHighestBid(uint256 loanId) external view returns (address, uint256);
function getNftCollateralAmount(address nftAsset) external view returns (uint256);
function getUserNftCollateralAmount(address user, address nftAsset) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {ILendPoolAddressesProvider} from "./ILendPoolAddressesProvider.sol";
import {DataTypes} from "../libraries/types/DataTypes.sol";
interface ILendPool {
/**
* @dev Emitted on deposit()
* @param user The address initiating the deposit
* @param amount The amount deposited
* @param reserve The address of the underlying asset of the reserve
* @param onBehalfOf The beneficiary of the deposit, receiving the bTokens
* @param referral The referral code used
**/
event Deposit(
address user,
address indexed reserve,
uint256 amount,
address indexed onBehalfOf,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param user The address initiating the withdrawal, owner of bTokens
* @param reserve The address of the underlyng asset being withdrawn
* @param amount The amount to be withdrawn
* @param to Address that will receive the underlying
**/
event Withdraw(address indexed user, address indexed reserve, uint256 amount, address indexed to);
/**
* @dev Emitted on borrow() when loan needs to be opened
* @param user The address of the user initiating the borrow(), receiving the funds
* @param reserve The address of the underlying asset being borrowed
* @param amount The amount borrowed out
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token id of the underlying NFT used as collateral
* @param onBehalfOf The address that will be getting the loan
* @param referral The referral code used
**/
event Borrow(
address user,
address indexed reserve,
uint256 amount,
address nftAsset,
uint256 nftTokenId,
address indexed onBehalfOf,
uint256 borrowRate,
uint256 loanId,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param user The address of the user initiating the repay(), providing the funds
* @param reserve The address of the underlying asset of the reserve
* @param amount The amount repaid
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token id of the underlying NFT used as collateral
* @param borrower The beneficiary of the repayment, getting his debt reduced
* @param loanId The loan ID of the NFT loans
**/
event Repay(
address user,
address indexed reserve,
uint256 amount,
address indexed nftAsset,
uint256 nftTokenId,
address indexed borrower,
uint256 loanId
);
/**
* @dev Emitted when a borrower's loan is auctioned.
* @param user The address of the user initiating the auction
* @param reserve The address of the underlying asset of the reserve
* @param bidPrice The price of the underlying reserve given by the bidder
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token id of the underlying NFT used as collateral
* @param onBehalfOf The address that will be getting the NFT
* @param loanId The loan ID of the NFT loans
**/
event Auction(
address user,
address indexed reserve,
uint256 bidPrice,
address indexed nftAsset,
uint256 nftTokenId,
address onBehalfOf,
address indexed borrower,
uint256 loanId
);
/**
* @dev Emitted on redeem()
* @param user The address of the user initiating the redeem(), providing the funds
* @param reserve The address of the underlying asset of the reserve
* @param borrowAmount The borrow amount repaid
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token id of the underlying NFT used as collateral
* @param loanId The loan ID of the NFT loans
**/
event Redeem(
address user,
address indexed reserve,
uint256 borrowAmount,
uint256 fineAmount,
address indexed nftAsset,
uint256 nftTokenId,
address indexed borrower,
uint256 loanId
);
/**
* @dev Emitted when a borrower's loan is liquidated.
* @param user The address of the user initiating the auction
* @param reserve The address of the underlying asset of the reserve
* @param repayAmount The amount of reserve repaid by the liquidator
* @param remainAmount The amount of reserve received by the borrower
* @param loanId The loan ID of the NFT loans
**/
event Liquidate(
address user,
address indexed reserve,
uint256 repayAmount,
uint256 remainAmount,
address indexed nftAsset,
uint256 nftTokenId,
address indexed borrower,
uint256 loanId
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendPool contract. The event is therefore replicated here so it
* gets added to the LendPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying bTokens.
* - E.g. User deposits 100 USDC and gets in return 100 bUSDC
* @param reserve The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the bTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of bTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address reserve,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent bTokens owned
* E.g. User has 100 bUSDC, calls withdraw() and receives 100 USDC, burning the 100 bUSDC
* @param reserve The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole bToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address reserve,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral
* - E.g. User borrows 100 USDC, receiving the 100 USDC in his wallet
* and lock collateral asset in contract
* @param reserveAsset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param onBehalfOf Address of the user who will receive the loan. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function borrow(
address reserveAsset,
uint256 amount,
address nftAsset,
uint256 nftTokenId,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent loan owned
* - E.g. User repays 100 USDC, burning loan and receives collateral asset
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param amount The amount to repay
* @return The final amount repaid, loan is burned or not
**/
function repay(
address nftAsset,
uint256 nftTokenId,
uint256 amount
) external returns (uint256, bool);
/**
* @dev Function to auction a non-healthy position collateral-wise
* - The caller (liquidator) want to buy collateral asset of the user getting liquidated
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param bidPrice The bid price of the liquidator want to buy the underlying NFT
* @param onBehalfOf Address of the user who will get the underlying NFT, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of NFT
* is a different wallet
**/
function auction(
address nftAsset,
uint256 nftTokenId,
uint256 bidPrice,
address onBehalfOf
) external;
/**
* @notice Redeem a NFT loan which state is in Auction
* - E.g. User repays 100 USDC, burning loan and receives collateral asset
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param amount The amount to repay the debt and bid fine
**/
function redeem(
address nftAsset,
uint256 nftTokenId,
uint256 amount
) external returns (uint256);
/**
* @dev Function to liquidate a non-healthy position collateral-wise
* - The caller (liquidator) buy collateral asset of the user getting liquidated, and receives
* the collateral asset
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
**/
function liquidate(
address nftAsset,
uint256 nftTokenId,
uint256 amount
) external returns (uint256);
/**
* @dev Validates and finalizes an bToken transfer
* - Only callable by the overlying bToken of the `asset`
* @param asset The address of the underlying asset of the bToken
* @param from The user from which the bTokens are transferred
* @param to The user receiving the bTokens
* @param amount The amount being transferred/withdrawn
* @param balanceFromBefore The bToken balance of the `from` user before the transfer
* @param balanceToBefore The bToken balance of the `to` user before the transfer
*/
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromBefore,
uint256 balanceToBefore
) external view;
function getReserveConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory);
function getNftConfiguration(address asset) external view returns (DataTypes.NftConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function getReservesList() external view returns (address[] memory);
function getNftData(address asset) external view returns (DataTypes.NftData memory);
/**
* @dev Returns the loan data of the NFT
* @param nftAsset The address of the NFT
* @param reserveAsset The address of the Reserve
* @return totalCollateralInETH the total collateral in ETH of the NFT
* @return totalCollateralInReserve the total collateral in Reserve of the NFT
* @return availableBorrowsInETH the borrowing power in ETH of the NFT
* @return availableBorrowsInReserve the borrowing power in Reserve of the NFT
* @return ltv the loan to value of the user
* @return liquidationThreshold the liquidation threshold of the NFT
* @return liquidationBonus the liquidation bonus of the NFT
**/
function getNftCollateralData(address nftAsset, address reserveAsset)
external
view
returns (
uint256 totalCollateralInETH,
uint256 totalCollateralInReserve,
uint256 availableBorrowsInETH,
uint256 availableBorrowsInReserve,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus
);
/**
* @dev Returns the debt data of the NFT
* @param nftAsset The address of the NFT
* @param nftTokenId The token id of the NFT
* @return loanId the loan id of the NFT
* @return reserveAsset the address of the Reserve
* @return totalCollateral the total power of the NFT
* @return totalDebt the total debt of the NFT
* @return availableBorrows the borrowing power left of the NFT
* @return healthFactor the current health factor of the NFT
**/
function getNftDebtData(address nftAsset, uint256 nftTokenId)
external
view
returns (
uint256 loanId,
address reserveAsset,
uint256 totalCollateral,
uint256 totalDebt,
uint256 availableBorrows,
uint256 healthFactor
);
/**
* @dev Returns the auction data of the NFT
* @param nftAsset The address of the NFT
* @param nftTokenId The token id of the NFT
* @return loanId the loan id of the NFT
* @return bidderAddress the highest bidder address of the loan
* @return bidPrice the highest bid price in Reserve of the loan
* @return bidBorrowAmount the borrow amount in Reserve of the loan
* @return bidFine the penalty fine of the loan
**/
function getNftAuctionData(address nftAsset, uint256 nftTokenId)
external
view
returns (
uint256 loanId,
address bidderAddress,
uint256 bidPrice,
uint256 bidBorrowAmount,
uint256 bidFine
);
function getNftLiquidatePrice(address nftAsset, uint256 nftTokenId)
external
view
returns (uint256 liquidatePrice, uint256 paybackAmount);
function getNftsList() external view returns (address[] memory);
/**
* @dev Set the _pause state of a reserve
* - Only callable by the LendPool contract
* @param val `true` to pause the reserve, `false` to un-pause it
*/
function setPause(bool val) external;
/**
* @dev Returns if the LendPool is paused
*/
function paused() external view returns (bool);
function getAddressesProvider() external view returns (ILendPoolAddressesProvider);
function initReserve(
address asset,
address bTokenAddress,
address debtTokenAddress,
address interestRateAddress
) external;
function initNft(address asset, address bNftAddress) external;
function setReserveInterestRateAddress(address asset, address rateAddress) external;
function setReserveConfiguration(address asset, uint256 configuration) external;
function setNftConfiguration(address asset, uint256 configuration) external;
function setMaxNumberOfReserves(uint256 val) external;
function setMaxNumberOfNfts(uint256 val) external;
function getMaxNumberOfReserves() external view returns (uint256);
function getMaxNumberOfNfts() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
/************
@title IReserveOracleGetter interface
@notice Interface for getting Reserve price oracle.*/
interface IReserveOracleGetter {
/* CAUTION: Price uint is ETH based (WEI, 18 decimals) */
/***********
@dev returns the asset price in ETH
*/
function getAssetPrice(address asset) external view returns (uint256);
// get twap price depending on _period
function getTwapPrice(address _priceFeedKey, uint256 _interval) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
/************
@title INFTOracleGetter interface
@notice Interface for getting NFT price oracle.*/
interface INFTOracleGetter {
/* CAUTION: Price uint is ETH based (WEI, 18 decimals) */
/***********
@dev returns the asset price in ETH
*/
function getAssetPrice(address asset) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
/**
* @title LendPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Bend Governance
* @author Bend
**/
interface ILendPoolAddressesProvider {
event MarketIdSet(string newMarketId);
event LendPoolUpdated(address indexed newAddress, bytes encodedCallData);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendPoolConfiguratorUpdated(address indexed newAddress, bytes encodedCallData);
event ReserveOracleUpdated(address indexed newAddress);
event NftOracleUpdated(address indexed newAddress);
event LendPoolLoanUpdated(address indexed newAddress, bytes encodedCallData);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy, bytes encodedCallData);
event BNFTRegistryUpdated(address indexed newAddress);
event LendPoolLiquidatorUpdated(address indexed newAddress);
event IncentivesControllerUpdated(address indexed newAddress);
event UIDataProviderUpdated(address indexed newAddress);
event BendDataProviderUpdated(address indexed newAddress);
event WalletBalanceProviderUpdated(address indexed newAddress);
function getMarketId() external view returns (string memory);
function setMarketId(string calldata marketId) external;
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(
bytes32 id,
address impl,
bytes memory encodedCallData
) external;
function getAddress(bytes32 id) external view returns (address);
function getLendPool() external view returns (address);
function setLendPoolImpl(address pool, bytes memory encodedCallData) external;
function getLendPoolConfigurator() external view returns (address);
function setLendPoolConfiguratorImpl(address configurator, bytes memory encodedCallData) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getReserveOracle() external view returns (address);
function setReserveOracle(address reserveOracle) external;
function getNFTOracle() external view returns (address);
function setNFTOracle(address nftOracle) external;
function getLendPoolLoan() external view returns (address);
function setLendPoolLoanImpl(address loan, bytes memory encodedCallData) external;
function getBNFTRegistry() external view returns (address);
function setBNFTRegistry(address factory) external;
function getLendPoolLiquidator() external view returns (address);
function setLendPoolLiquidator(address liquidator) external;
function getIncentivesController() external view returns (address);
function setIncentivesController(address controller) external;
function getUIDataProvider() external view returns (address);
function setUIDataProvider(address provider) external;
function getBendDataProvider() external view returns (address);
function setBendDataProvider(address provider) external;
function getWalletBalanceProvider() external view returns (address);
function setWalletBalanceProvider(address provider) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
/**
* @title Errors library
* @author Bend
* @notice Defines the error messages emitted by the different contracts of the Bend protocol
*/
library Errors {
enum ReturnCode {
SUCCESS,
FAILED
}
string public constant SUCCESS = "0";
//common errors
string public constant CALLER_NOT_POOL_ADMIN = "100"; // 'The caller must be the pool admin'
string public constant CALLER_NOT_ADDRESS_PROVIDER = "101";
string public constant INVALID_FROM_BALANCE_AFTER_TRANSFER = "102";
string public constant INVALID_TO_BALANCE_AFTER_TRANSFER = "103";
//math library erros
string public constant MATH_MULTIPLICATION_OVERFLOW = "200";
string public constant MATH_ADDITION_OVERFLOW = "201";
string public constant MATH_DIVISION_BY_ZERO = "202";
//validation & check errors
string public constant VL_INVALID_AMOUNT = "301"; // 'Amount must be greater than 0'
string public constant VL_NO_ACTIVE_RESERVE = "302"; // 'Action requires an active reserve'
string public constant VL_RESERVE_FROZEN = "303"; // 'Action cannot be performed because the reserve is frozen'
string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = "304"; // 'User cannot withdraw more than the available balance'
string public constant VL_BORROWING_NOT_ENABLED = "305"; // 'Borrowing is not enabled'
string public constant VL_COLLATERAL_BALANCE_IS_0 = "306"; // 'The collateral balance is 0'
string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = "307"; // 'Health factor is lesser than the liquidation threshold'
string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = "308"; // 'There is not enough collateral to cover a new borrow'
string public constant VL_NO_DEBT_OF_SELECTED_TYPE = "309"; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt'
string public constant VL_NO_ACTIVE_NFT = "310";
string public constant VL_NFT_FROZEN = "311";
string public constant VL_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = "312"; // 'User did not borrow the specified currency'
string public constant VL_INVALID_HEALTH_FACTOR = "313";
string public constant VL_INVALID_ONBEHALFOF_ADDRESS = "314";
string public constant VL_INVALID_TARGET_ADDRESS = "315";
string public constant VL_INVALID_RESERVE_ADDRESS = "316";
string public constant VL_SPECIFIED_LOAN_NOT_BORROWED_BY_USER = "317";
string public constant VL_SPECIFIED_RESERVE_NOT_BORROWED_BY_USER = "318";
string public constant VL_HEALTH_FACTOR_HIGHER_THAN_LIQUIDATION_THRESHOLD = "319";
//lend pool errors
string public constant LP_CALLER_NOT_LEND_POOL_CONFIGURATOR = "400"; // 'The caller of the function is not the lending pool configurator'
string public constant LP_IS_PAUSED = "401"; // 'Pool is paused'
string public constant LP_NO_MORE_RESERVES_ALLOWED = "402";
string public constant LP_NOT_CONTRACT = "403";
string public constant LP_BORROW_NOT_EXCEED_LIQUIDATION_THRESHOLD = "404";
string public constant LP_BORROW_IS_EXCEED_LIQUIDATION_PRICE = "405";
string public constant LP_NO_MORE_NFTS_ALLOWED = "406";
string public constant LP_INVALIED_USER_NFT_AMOUNT = "407";
string public constant LP_INCONSISTENT_PARAMS = "408";
string public constant LP_NFT_IS_NOT_USED_AS_COLLATERAL = "409";
string public constant LP_CALLER_MUST_BE_AN_BTOKEN = "410";
string public constant LP_INVALIED_NFT_AMOUNT = "411";
string public constant LP_NFT_HAS_USED_AS_COLLATERAL = "412";
string public constant LP_DELEGATE_CALL_FAILED = "413";
string public constant LP_AMOUNT_LESS_THAN_EXTRA_DEBT = "414";
string public constant LP_AMOUNT_LESS_THAN_REDEEM_THRESHOLD = "415";
//lend pool loan errors
string public constant LPL_INVALID_LOAN_STATE = "480";
string public constant LPL_INVALID_LOAN_AMOUNT = "481";
string public constant LPL_INVALID_TAKEN_AMOUNT = "482";
string public constant LPL_AMOUNT_OVERFLOW = "483";
string public constant LPL_BID_PRICE_LESS_THAN_LIQUIDATION_PRICE = "484";
string public constant LPL_BID_PRICE_LESS_THAN_HIGHEST_PRICE = "485";
string public constant LPL_BID_REDEEM_DURATION_HAS_END = "486";
string public constant LPL_BID_USER_NOT_SAME = "487";
string public constant LPL_BID_REPAY_AMOUNT_NOT_ENOUGH = "488";
string public constant LPL_BID_AUCTION_DURATION_HAS_END = "489";
string public constant LPL_BID_AUCTION_DURATION_NOT_END = "490";
string public constant LPL_BID_PRICE_LESS_THAN_BORROW = "491";
string public constant LPL_INVALID_BIDDER_ADDRESS = "492";
string public constant LPL_AMOUNT_LESS_THAN_BID_FINE = "493";
//common token errors
string public constant CT_CALLER_MUST_BE_LEND_POOL = "500"; // 'The caller of this function must be a lending pool'
string public constant CT_INVALID_MINT_AMOUNT = "501"; //invalid amount to mint
string public constant CT_INVALID_BURN_AMOUNT = "502"; //invalid amount to burn
string public constant CT_BORROW_ALLOWANCE_NOT_ENOUGH = "503";
//reserve logic errors
string public constant RL_RESERVE_ALREADY_INITIALIZED = "601"; // 'Reserve has already been initialized'
string public constant RL_LIQUIDITY_INDEX_OVERFLOW = "602"; // Liquidity index overflows uint128
string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = "603"; // Variable borrow index overflows uint128
string public constant RL_LIQUIDITY_RATE_OVERFLOW = "604"; // Liquidity rate overflows uint128
string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = "605"; // Variable borrow rate overflows uint128
//configure errors
string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = "700"; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_CONFIGURATION = "701"; // 'Invalid risk parameters for the reserve'
string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = "702"; // 'The caller must be the emergency admin'
string public constant LPC_INVALIED_BNFT_ADDRESS = "703";
string public constant LPC_INVALIED_LOAN_ADDRESS = "704";
string public constant LPC_NFT_LIQUIDITY_NOT_0 = "705";
//reserve config errors
string public constant RC_INVALID_LTV = "730";
string public constant RC_INVALID_LIQ_THRESHOLD = "731";
string public constant RC_INVALID_LIQ_BONUS = "732";
string public constant RC_INVALID_DECIMALS = "733";
string public constant RC_INVALID_RESERVE_FACTOR = "734";
string public constant RC_INVALID_REDEEM_DURATION = "735";
string public constant RC_INVALID_AUCTION_DURATION = "736";
string public constant RC_INVALID_REDEEM_FINE = "737";
string public constant RC_INVALID_REDEEM_THRESHOLD = "738";
//address provider erros
string public constant LPAPR_PROVIDER_NOT_REGISTERED = "760"; // 'Provider is not registered'
string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = "761";
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {Errors} from "../helpers/Errors.sol";
/**
* @title WadRayMath library
* @author Bend
* @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
**/
library WadRayMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant HALF_WAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant HALF_RAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return HALF_RAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return HALF_WAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + HALF_WAD) / WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + HALF_RAY) / RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {ILendPoolLoan} from "../../interfaces/ILendPoolLoan.sol";
import {IReserveOracleGetter} from "../../interfaces/IReserveOracleGetter.sol";
import {INFTOracleGetter} from "../../interfaces/INFTOracleGetter.sol";
import {WadRayMath} from "../math/WadRayMath.sol";
import {PercentageMath} from "../math/PercentageMath.sol";
import {ReserveConfiguration} from "../configuration/ReserveConfiguration.sol";
import {NftConfiguration} from "../configuration/NftConfiguration.sol";
import {Errors} from "../helpers/Errors.sol";
import {DataTypes} from "../types/DataTypes.sol";
import {ReserveLogic} from "./ReserveLogic.sol";
/**
* @title GenericLogic library
* @author Bend
* @notice Implements protocol-level logic to calculate and validate the state of a user
*/
library GenericLogic {
using ReserveLogic for DataTypes.ReserveData;
using WadRayMath for uint256;
using PercentageMath for uint256;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using NftConfiguration for DataTypes.NftConfigurationMap;
uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether;
struct CalculateLoanDataVars {
uint256 reserveUnitPrice;
uint256 reserveUnit;
uint256 reserveDecimals;
uint256 healthFactor;
uint256 totalCollateralInETH;
uint256 totalCollateralInReserve;
uint256 totalDebtInETH;
uint256 totalDebtInReserve;
uint256 nftLtv;
uint256 nftLiquidationThreshold;
address nftAsset;
uint256 nftTokenId;
uint256 nftUnitPrice;
}
/**
* @dev Calculates the nft loan data.
* this includes the total collateral/borrow balances in Reserve,
* the Loan To Value, the Liquidation Ratio, and the Health factor.
* @param reserveData Data of the reserve
* @param nftData Data of the nft
* @param reserveOracle The price oracle address of reserve
* @param nftOracle The price oracle address of nft
* @return The total collateral and total debt of the loan in Reserve, the ltv, liquidation threshold and the HF
**/
function calculateLoanData(
address reserveAddress,
DataTypes.ReserveData storage reserveData,
address nftAddress,
DataTypes.NftData storage nftData,
address loanAddress,
uint256 loanId,
address reserveOracle,
address nftOracle
)
internal
view
returns (
uint256,
uint256,
uint256
)
{
CalculateLoanDataVars memory vars;
(vars.nftLtv, vars.nftLiquidationThreshold, ) = nftData.configuration.getCollateralParams();
// calculate total borrow balance for the loan
if (loanId != 0) {
(vars.totalDebtInETH, vars.totalDebtInReserve) = calculateNftDebtData(
reserveAddress,
reserveData,
loanAddress,
loanId,
reserveOracle
);
}
// calculate total collateral balance for the nft
(vars.totalCollateralInETH, vars.totalCollateralInReserve) = calculateNftCollateralData(
reserveAddress,
reserveData,
nftAddress,
nftData,
reserveOracle,
nftOracle
);
// calculate health by borrow and collateral
vars.healthFactor = calculateHealthFactorFromBalances(
vars.totalCollateralInReserve,
vars.totalDebtInReserve,
vars.nftLiquidationThreshold
);
return (vars.totalCollateralInReserve, vars.totalDebtInReserve, vars.healthFactor);
}
function calculateNftDebtData(
address reserveAddress,
DataTypes.ReserveData storage reserveData,
address loanAddress,
uint256 loanId,
address reserveOracle
) internal view returns (uint256, uint256) {
CalculateLoanDataVars memory vars;
// all asset price has converted to ETH based, unit is in WEI (18 decimals)
vars.reserveDecimals = reserveData.configuration.getDecimals();
vars.reserveUnit = 10**vars.reserveDecimals;
vars.reserveUnitPrice = IReserveOracleGetter(reserveOracle).getAssetPrice(reserveAddress);
(, vars.totalDebtInReserve) = ILendPoolLoan(loanAddress).getLoanReserveBorrowAmount(loanId);
vars.totalDebtInETH = (vars.totalDebtInReserve * vars.reserveUnitPrice) / vars.reserveUnit;
return (vars.totalDebtInETH, vars.totalDebtInReserve);
}
function calculateNftCollateralData(
address reserveAddress,
DataTypes.ReserveData storage reserveData,
address nftAddress,
DataTypes.NftData storage nftData,
address reserveOracle,
address nftOracle
) internal view returns (uint256, uint256) {
reserveData;
nftData;
CalculateLoanDataVars memory vars;
// calculate total collateral balance for the nft
// all asset price has converted to ETH based, unit is in WEI (18 decimals)
vars.nftUnitPrice = INFTOracleGetter(nftOracle).getAssetPrice(nftAddress);
vars.totalCollateralInETH = vars.nftUnitPrice;
if (reserveAddress != address(0)) {
vars.reserveDecimals = reserveData.configuration.getDecimals();
vars.reserveUnit = 10**vars.reserveDecimals;
vars.reserveUnitPrice = IReserveOracleGetter(reserveOracle).getAssetPrice(reserveAddress);
vars.totalCollateralInReserve = (vars.totalCollateralInETH * vars.reserveUnit) / vars.reserveUnitPrice;
}
return (vars.totalCollateralInETH, vars.totalCollateralInReserve);
}
/**
* @dev Calculates the health factor from the corresponding balances
* @param totalCollateral The total collateral
* @param totalDebt The total debt
* @param liquidationThreshold The avg liquidation threshold
* @return The health factor calculated from the balances provided
**/
function calculateHealthFactorFromBalances(
uint256 totalCollateral,
uint256 totalDebt,
uint256 liquidationThreshold
) internal pure returns (uint256) {
if (totalDebt == 0) return type(uint256).max;
return (totalCollateral.percentMul(liquidationThreshold)).wadDiv(totalDebt);
}
/**
* @dev Calculates the equivalent amount that an user can borrow, depending on the available collateral and the
* average Loan To Value
* @param totalCollateral The total collateral
* @param totalDebt The total borrow balance
* @param ltv The average loan to value
* @return the amount available to borrow for the user
**/
function calculateAvailableBorrows(
uint256 totalCollateral,
uint256 totalDebt,
uint256 ltv
) internal pure returns (uint256) {
uint256 availableBorrows = totalCollateral.percentMul(ltv);
if (availableBorrows < totalDebt) {
return 0;
}
availableBorrows = availableBorrows - totalDebt;
return availableBorrows;
}
struct CalcLiquidatePriceLocalVars {
uint256 ltv;
uint256 liquidationThreshold;
uint256 liquidationBonus;
uint256 nftPriceInETH;
uint256 nftPriceInReserve;
uint256 reserveDecimals;
uint256 reservePriceInETH;
uint256 thresholdPrice;
uint256 liquidatePrice;
uint256 borrowAmount;
}
function calculateLoanLiquidatePrice(
uint256 loanId,
address reserveAsset,
DataTypes.ReserveData storage reserveData,
address nftAsset,
DataTypes.NftData storage nftData,
address poolLoan,
address reserveOracle,
address nftOracle
)
internal
view
returns (
uint256,
uint256,
uint256
)
{
CalcLiquidatePriceLocalVars memory vars;
/*
* 0 CR LH 100
* |___________________|___________________|___________________|
* < Borrowing with Interest <
* CR: Callteral Ratio;
* LH: Liquidate Threshold;
* Liquidate Trigger: Borrowing with Interest > thresholdPrice;
* Liquidate Price: (100% - BonusRatio) * NFT Price;
*/
vars.reserveDecimals = reserveData.configuration.getDecimals();
(, vars.borrowAmount) = ILendPoolLoan(poolLoan).getLoanReserveBorrowAmount(loanId);
(vars.ltv, vars.liquidationThreshold, vars.liquidationBonus) = nftData.configuration.getCollateralParams();
vars.nftPriceInETH = INFTOracleGetter(nftOracle).getAssetPrice(nftAsset);
vars.reservePriceInETH = IReserveOracleGetter(reserveOracle).getAssetPrice(reserveAsset);
vars.nftPriceInReserve = ((10**vars.reserveDecimals) * vars.nftPriceInETH) / vars.reservePriceInETH;
vars.thresholdPrice = vars.nftPriceInReserve.percentMul(vars.liquidationThreshold);
vars.liquidatePrice = vars.nftPriceInReserve.percentMul(PercentageMath.PERCENTAGE_FACTOR - vars.liquidationBonus);
return (vars.borrowAmount, vars.thresholdPrice, vars.liquidatePrice);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {Errors} from "../helpers/Errors.sol";
/**
* @title PercentageMath library
* @author Bend
* @notice Provides functions to perform percentage calculations
* @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR
* @dev Operations are rounded half up
**/
library PercentageMath {
uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals
uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;
uint256 constant ONE_PERCENT = 1e2; //100, 1%
uint256 constant TEN_PERCENT = 1e3; //1000, 10%
uint256 constant ONE_THOUSANDTH_PERCENT = 1e1; //10, 0.1%
uint256 constant ONE_TEN_THOUSANDTH_PERCENT = 1; //1, 0.01%
/**
* @dev Executes a percentage multiplication
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The percentage of value
**/
function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {
if (value == 0 || percentage == 0) {
return 0;
}
require(value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;
}
/**
* @dev Executes a percentage division
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The value divided the percentage
**/
function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) {
require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfPercentage = percentage / 2;
require(value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {IBToken} from "../../interfaces/IBToken.sol";
import {IDebtToken} from "../../interfaces/IDebtToken.sol";
import {IInterestRate} from "../../interfaces/IInterestRate.sol";
import {ReserveConfiguration} from "../configuration/ReserveConfiguration.sol";
import {MathUtils} from "../math/MathUtils.sol";
import {WadRayMath} from "../math/WadRayMath.sol";
import {PercentageMath} from "../math/PercentageMath.sol";
import {Errors} from "../helpers/Errors.sol";
import {DataTypes} from "../types/DataTypes.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
/**
* @title ReserveLogic library
* @author Bend
* @notice Implements the logic to update the reserves state
*/
library ReserveLogic {
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/**
* @dev Emitted when the state of a reserve is updated
* @param asset The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed asset,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
using ReserveLogic for DataTypes.ReserveData;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
/**
* @dev Returns the ongoing normalized income for the reserve
* A value of 1e27 means there is no income. As time passes, the income is accrued
* A value of 2*1e27 means for each unit of asset one unit of income has been accrued
* @param reserve The reserve object
* @return the normalized income. expressed in ray
**/
function getNormalizedIncome(DataTypes.ReserveData storage reserve) internal view returns (uint256) {
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.liquidityIndex;
}
uint256 cumulated = MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(
reserve.liquidityIndex
);
return cumulated;
}
/**
* @dev Returns the ongoing normalized variable debt for the reserve
* A value of 1e27 means there is no debt. As time passes, the income is accrued
* A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated
* @param reserve The reserve object
* @return The normalized variable debt. expressed in ray
**/
function getNormalizedDebt(DataTypes.ReserveData storage reserve) internal view returns (uint256) {
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.variableBorrowIndex;
}
uint256 cumulated = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(
reserve.variableBorrowIndex
);
return cumulated;
}
/**
* @dev Updates the liquidity cumulative index and the variable borrow index.
* @param reserve the reserve object
**/
function updateState(DataTypes.ReserveData storage reserve) internal {
uint256 scaledVariableDebt = IDebtToken(reserve.debtTokenAddress).scaledTotalSupply();
uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;
uint256 previousLiquidityIndex = reserve.liquidityIndex;
uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;
(uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes(
reserve,
scaledVariableDebt,
previousLiquidityIndex,
previousVariableBorrowIndex,
lastUpdatedTimestamp
);
_mintToTreasury(
reserve,
scaledVariableDebt,
previousVariableBorrowIndex,
newLiquidityIndex,
newVariableBorrowIndex,
lastUpdatedTimestamp
);
}
/**
* @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate
* the flashloan fee to the reserve, and spread it between all the depositors
* @param reserve The reserve object
* @param totalLiquidity The total liquidity available in the reserve
* @param amount The amount to accomulate
**/
function cumulateToLiquidityIndex(
DataTypes.ReserveData storage reserve,
uint256 totalLiquidity,
uint256 amount
) internal {
uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay());
uint256 result = amountToLiquidityRatio + (WadRayMath.ray());
result = result.rayMul(reserve.liquidityIndex);
require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);
reserve.liquidityIndex = uint128(result);
}
/**
* @dev Initializes a reserve
* @param reserve The reserve object
* @param bTokenAddress The address of the overlying bToken contract
* @param debtTokenAddress The address of the overlying debtToken contract
* @param interestRateAddress The address of the interest rate strategy contract
**/
function init(
DataTypes.ReserveData storage reserve,
address bTokenAddress,
address debtTokenAddress,
address interestRateAddress
) external {
require(reserve.bTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED);
reserve.liquidityIndex = uint128(WadRayMath.ray());
reserve.variableBorrowIndex = uint128(WadRayMath.ray());
reserve.bTokenAddress = bTokenAddress;
reserve.debtTokenAddress = debtTokenAddress;
reserve.interestRateAddress = interestRateAddress;
}
struct UpdateInterestRatesLocalVars {
uint256 availableLiquidity;
uint256 newLiquidityRate;
uint256 newVariableRate;
uint256 totalVariableDebt;
}
/**
* @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate
* @param reserve The address of the reserve to be updated
* @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action
* @param liquidityTaken The amount of liquidity taken from the protocol (withdraw or borrow)
**/
function updateInterestRates(
DataTypes.ReserveData storage reserve,
address reserveAddress,
address bTokenAddress,
uint256 liquidityAdded,
uint256 liquidityTaken
) internal {
UpdateInterestRatesLocalVars memory vars;
//calculates the total variable debt locally using the scaled borrow amount instead
//of borrow amount(), as it's noticeably cheaper. Also, the index has been
//updated by the previous updateState() call
vars.totalVariableDebt = IDebtToken(reserve.debtTokenAddress).scaledTotalSupply().rayMul(
reserve.variableBorrowIndex
);
(vars.newLiquidityRate, vars.newVariableRate) = IInterestRate(reserve.interestRateAddress).calculateInterestRates(
reserveAddress,
bTokenAddress,
liquidityAdded,
liquidityTaken,
vars.totalVariableDebt,
reserve.configuration.getReserveFactor()
);
require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW);
require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW);
reserve.currentLiquidityRate = uint128(vars.newLiquidityRate);
reserve.currentVariableBorrowRate = uint128(vars.newVariableRate);
emit ReserveDataUpdated(
reserveAddress,
vars.newLiquidityRate,
vars.newVariableRate,
reserve.liquidityIndex,
reserve.variableBorrowIndex
);
}
struct MintToTreasuryLocalVars {
uint256 currentVariableDebt;
uint256 previousVariableDebt;
uint256 totalDebtAccrued;
uint256 amountToMint;
uint256 reserveFactor;
}
/**
* @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the
* specific asset.
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The current scaled total variable debt
* @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest
* @param newLiquidityIndex The new liquidity index
* @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest
**/
function _mintToTreasury(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 previousVariableBorrowIndex,
uint256 newLiquidityIndex,
uint256 newVariableBorrowIndex,
uint40 timestamp
) internal {
timestamp;
MintToTreasuryLocalVars memory vars;
vars.reserveFactor = reserve.configuration.getReserveFactor();
if (vars.reserveFactor == 0) {
return;
}
//calculate the last principal variable debt
vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex);
//calculate the new total supply after accumulation of the index
vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex);
//debt accrued is the sum of the current debt minus the sum of the debt at the last update
vars.totalDebtAccrued = vars.currentVariableDebt - (vars.previousVariableDebt);
vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor);
if (vars.amountToMint != 0) {
IBToken(reserve.bTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex);
}
}
/**
* @dev Updates the reserve indexes and the timestamp of the update
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The scaled variable debt
* @param liquidityIndex The last stored liquidity index
* @param variableBorrowIndex The last stored variable borrow index
**/
function _updateIndexes(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 timestamp
) internal returns (uint256, uint256) {
uint256 currentLiquidityRate = reserve.currentLiquidityRate;
uint256 newLiquidityIndex = liquidityIndex;
uint256 newVariableBorrowIndex = variableBorrowIndex;
//only cumulating if there is any income being produced
if (currentLiquidityRate > 0) {
uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp);
newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex);
require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);
reserve.liquidityIndex = uint128(newLiquidityIndex);
//as the liquidity rate might come only from stable rate loans, we need to ensure
//that there is actual variable debt before accumulating
if (scaledVariableDebt != 0) {
uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(
reserve.currentVariableBorrowRate,
timestamp
);
newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex);
require(newVariableBorrowIndex <= type(uint128).max, Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW);
reserve.variableBorrowIndex = uint128(newVariableBorrowIndex);
}
}
//solium-disable-next-line
reserve.lastUpdateTimestamp = uint40(block.timestamp);
return (newLiquidityIndex, newVariableBorrowIndex);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {Errors} from "../helpers/Errors.sol";
import {DataTypes} from "../types/DataTypes.sol";
/**
* @title NftLogic library
* @author Bend
* @notice Implements the logic to update the nft state
*/
library NftLogic {
/**
* @dev Initializes a nft
* @param nft The nft object
* @param bNftAddress The address of the bNFT contract
**/
function init(DataTypes.NftData storage nft, address bNftAddress) external {
require(nft.bNftAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED);
nft.bNftAddress = bNftAddress;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {ReserveLogic} from "./ReserveLogic.sol";
import {GenericLogic} from "./GenericLogic.sol";
import {WadRayMath} from "../math/WadRayMath.sol";
import {PercentageMath} from "../math/PercentageMath.sol";
import {ReserveConfiguration} from "../configuration/ReserveConfiguration.sol";
import {NftConfiguration} from "../configuration/NftConfiguration.sol";
import {Errors} from "../helpers/Errors.sol";
import {DataTypes} from "../types/DataTypes.sol";
import {IInterestRate} from "../../interfaces/IInterestRate.sol";
import {ILendPoolLoan} from "../../interfaces/ILendPoolLoan.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
/**
* @title ValidationLogic library
* @author Bend
* @notice Implements functions to validate the different actions of the protocol
*/
library ValidationLogic {
using ReserveLogic for DataTypes.ReserveData;
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using NftConfiguration for DataTypes.NftConfigurationMap;
/**
* @dev Validates a deposit action
* @param reserve The reserve object on which the user is depositing
* @param amount The amount to be deposited
*/
function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view {
(bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags();
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!isFrozen, Errors.VL_RESERVE_FROZEN);
}
/**
* @dev Validates a withdraw action
* @param reserveData The reserve state
* @param amount The amount to be withdrawn
* @param userBalance The balance of the user
*/
function validateWithdraw(
DataTypes.ReserveData storage reserveData,
uint256 amount,
uint256 userBalance
) external view {
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE);
(bool isActive, , , ) = reserveData.configuration.getFlags();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
}
struct ValidateBorrowLocalVars {
uint256 currentLtv;
uint256 currentLiquidationThreshold;
uint256 amountOfCollateralNeeded;
uint256 userCollateralBalance;
uint256 userBorrowBalance;
uint256 availableLiquidity;
uint256 healthFactor;
bool isActive;
bool isFrozen;
bool borrowingEnabled;
bool stableRateBorrowingEnabled;
bool nftIsActive;
bool nftIsFrozen;
address loanReserveAsset;
address loanBorrower;
}
/**
* @dev Validates a borrow action
* @param reserveAsset The address of the asset to borrow
* @param amount The amount to be borrowed
* @param reserveData The reserve state from which the user is borrowing
* @param nftData The state of the user for the specific nft
*/
function validateBorrow(
address user,
address reserveAsset,
uint256 amount,
DataTypes.ReserveData storage reserveData,
address nftAsset,
DataTypes.NftData storage nftData,
address loanAddress,
uint256 loanId,
address reserveOracle,
address nftOracle
) external view {
ValidateBorrowLocalVars memory vars;
require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS);
require(amount > 0, Errors.VL_INVALID_AMOUNT);
if (loanId != 0) {
DataTypes.LoanData memory loanData = ILendPoolLoan(loanAddress).getLoan(loanId);
require(loanData.state == DataTypes.LoanState.Active, Errors.LPL_INVALID_LOAN_STATE);
require(reserveAsset == loanData.reserveAsset, Errors.VL_SPECIFIED_RESERVE_NOT_BORROWED_BY_USER);
require(user == loanData.borrower, Errors.VL_SPECIFIED_LOAN_NOT_BORROWED_BY_USER);
}
(vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserveData
.configuration
.getFlags();
require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN);
require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED);
(vars.nftIsActive, vars.nftIsFrozen) = nftData.configuration.getFlags();
require(vars.nftIsActive, Errors.VL_NO_ACTIVE_NFT);
require(!vars.nftIsFrozen, Errors.VL_NFT_FROZEN);
(vars.currentLtv, vars.currentLiquidationThreshold, ) = nftData.configuration.getCollateralParams();
(vars.userCollateralBalance, vars.userBorrowBalance, vars.healthFactor) = GenericLogic.calculateLoanData(
reserveAsset,
reserveData,
nftAsset,
nftData,
loanAddress,
loanId,
reserveOracle,
nftOracle
);
require(vars.userCollateralBalance > 0, Errors.VL_COLLATERAL_BALANCE_IS_0);
require(
vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,
Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD
);
//add the current already borrowed amount to the amount requested to calculate the total collateral needed.
//LTV is calculated in percentage
vars.amountOfCollateralNeeded = (vars.userBorrowBalance + amount).percentDiv(vars.currentLtv);
require(vars.amountOfCollateralNeeded <= vars.userCollateralBalance, Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW);
}
/**
* @dev Validates a repay action
* @param reserveData The reserve state from which the user is repaying
* @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1)
* @param borrowAmount The borrow balance of the user
*/
function validateRepay(
DataTypes.ReserveData storage reserveData,
DataTypes.NftData storage nftData,
DataTypes.LoanData memory loanData,
uint256 amountSent,
uint256 borrowAmount
) external view {
require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS);
require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE);
require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT);
require(amountSent > 0, Errors.VL_INVALID_AMOUNT);
require(borrowAmount > 0, Errors.VL_NO_DEBT_OF_SELECTED_TYPE);
require(loanData.state == DataTypes.LoanState.Active, Errors.LPL_INVALID_LOAN_STATE);
}
/**
* @dev Validates the auction action
* @param reserveData The reserve data of the principal
* @param nftData The nft data of the underlying nft
* @param bidPrice Total variable debt balance of the user
**/
function validateAuction(
DataTypes.ReserveData storage reserveData,
DataTypes.NftData storage nftData,
DataTypes.LoanData memory loanData,
uint256 bidPrice
) internal view {
require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS);
require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE);
require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT);
require(
loanData.state == DataTypes.LoanState.Active || loanData.state == DataTypes.LoanState.Auction,
Errors.LPL_INVALID_LOAN_STATE
);
require(bidPrice > 0, Errors.VL_INVALID_AMOUNT);
}
/**
* @dev Validates a redeem action
* @param reserveData The reserve state
* @param nftData The nft state
*/
function validateRedeem(
DataTypes.ReserveData storage reserveData,
DataTypes.NftData storage nftData,
DataTypes.LoanData memory loanData,
uint256 amount
) external view {
require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS);
require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE);
require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT);
require(loanData.state == DataTypes.LoanState.Auction, Errors.LPL_INVALID_LOAN_STATE);
require(loanData.bidderAddress != address(0), Errors.LPL_INVALID_BIDDER_ADDRESS);
uint256 bidFine = loanData.bidPrice.percentMul(nftData.configuration.getRedeemFine());
require(amount > bidFine, Errors.LPL_AMOUNT_LESS_THAN_BID_FINE);
}
/**
* @dev Validates the liquidation action
* @param reserveData The reserve data of the principal
* @param nftData The data of the underlying NFT
* @param loanData The loan data of the underlying NFT
**/
function validateLiquidate(
DataTypes.ReserveData storage reserveData,
DataTypes.NftData storage nftData,
DataTypes.LoanData memory loanData
) internal view {
require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS);
require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE);
require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT);
require(loanData.state == DataTypes.LoanState.Auction, Errors.LPL_INVALID_LOAN_STATE);
require(loanData.bidderAddress != address(0), Errors.LPL_INVALID_BIDDER_ADDRESS);
}
/**
* @dev Validates an bToken transfer
* @param from The user from which the bTokens are being transferred
* @param reserveData The state of the reserve
*/
function validateTransfer(address from, DataTypes.ReserveData storage reserveData) internal pure {
from;
reserveData;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {Errors} from "../helpers/Errors.sol";
import {DataTypes} from "../types/DataTypes.sol";
/**
* @title ReserveConfiguration library
* @author Bend
* @notice Implements the bitmap logic to handle the reserve configuration
*/
library ReserveConfiguration {
uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore
uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore
uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore
uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore
uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore
uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore
/// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed
uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;
uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;
uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48;
uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;
uint256 constant IS_FROZEN_START_BIT_POSITION = 57;
uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58;
uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;
uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64;
uint256 constant MAX_VALID_LTV = 65535;
uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;
uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535;
uint256 constant MAX_VALID_DECIMALS = 255;
uint256 constant MAX_VALID_RESERVE_FACTOR = 65535;
/**
* @dev Sets the Loan to Value of the reserve
* @param self The reserve configuration
* @param ltv the new ltv
**/
function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure {
require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV);
self.data = (self.data & LTV_MASK) | ltv;
}
/**
* @dev Gets the Loan to Value of the reserve
* @param self The reserve configuration
* @return The loan to value
**/
function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return self.data & ~LTV_MASK;
}
/**
* @dev Sets the liquidation threshold of the reserve
* @param self The reserve configuration
* @param threshold The new liquidation threshold
**/
function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure {
require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD);
self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);
}
/**
* @dev Gets the liquidation threshold of the reserve
* @param self The reserve configuration
* @return The liquidation threshold
**/
function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;
}
/**
* @dev Sets the liquidation bonus of the reserve
* @param self The reserve configuration
* @param bonus The new liquidation bonus
**/
function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure {
require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS);
self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);
}
/**
* @dev Gets the liquidation bonus of the reserve
* @param self The reserve configuration
* @return The liquidation bonus
**/
function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;
}
/**
* @dev Sets the decimals of the underlying asset of the reserve
* @param self The reserve configuration
* @param decimals The decimals
**/
function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure {
require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS);
self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION);
}
/**
* @dev Gets the decimals of the underlying asset of the reserve
* @param self The reserve configuration
* @return The decimals of the asset
**/
function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;
}
/**
* @dev Sets the active state of the reserve
* @param self The reserve configuration
* @param active The active state
**/
function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure {
self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);
}
/**
* @dev Gets the active state of the reserve
* @param self The reserve configuration
* @return The active state
**/
function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~ACTIVE_MASK) != 0;
}
/**
* @dev Sets the frozen state of the reserve
* @param self The reserve configuration
* @param frozen The frozen state
**/
function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure {
self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);
}
/**
* @dev Gets the frozen state of the reserve
* @param self The reserve configuration
* @return The frozen state
**/
function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~FROZEN_MASK) != 0;
}
/**
* @dev Enables or disables borrowing on the reserve
* @param self The reserve configuration
* @param enabled True if the borrowing needs to be enabled, false otherwise
**/
function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure {
self.data = (self.data & BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION);
}
/**
* @dev Gets the borrowing state of the reserve
* @param self The reserve configuration
* @return The borrowing state
**/
function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~BORROWING_MASK) != 0;
}
/**
* @dev Enables or disables stable rate borrowing on the reserve
* @param self The reserve configuration
* @param enabled True if the stable rate borrowing needs to be enabled, false otherwise
**/
function setStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure {
self.data =
(self.data & STABLE_BORROWING_MASK) |
(uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION);
}
/**
* @dev Gets the stable rate borrowing state of the reserve
* @param self The reserve configuration
* @return The stable rate borrowing state
**/
function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~STABLE_BORROWING_MASK) != 0;
}
/**
* @dev Sets the reserve factor of the reserve
* @param self The reserve configuration
* @param reserveFactor The reserve factor
**/
function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure {
require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR);
self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);
}
/**
* @dev Gets the reserve factor of the reserve
* @param self The reserve configuration
* @return The reserve factor
**/
function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION;
}
/**
* @dev Gets the configuration flags of the reserve
* @param self The reserve configuration
* @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled
**/
function getFlags(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (
bool,
bool,
bool,
bool
)
{
uint256 dataLocal = self.data;
return (
(dataLocal & ~ACTIVE_MASK) != 0,
(dataLocal & ~FROZEN_MASK) != 0,
(dataLocal & ~BORROWING_MASK) != 0,
(dataLocal & ~STABLE_BORROWING_MASK) != 0
);
}
/**
* @dev Gets the configuration paramters of the reserve
* @param self The reserve configuration
* @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals
**/
function getParams(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
uint256 dataLocal = self.data;
return (
dataLocal & ~LTV_MASK,
(dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
(dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,
(dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,
(dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION
);
}
/**
* @dev Gets the configuration paramters of the reserve from a memory object
* @param self The reserve configuration
* @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals
**/
function getParamsMemory(DataTypes.ReserveConfigurationMap memory self)
internal
pure
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
return (
self.data & ~LTV_MASK,
(self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
(self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,
(self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,
(self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION
);
}
/**
* @dev Gets the configuration flags of the reserve from a memory object
* @param self The reserve configuration
* @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled
**/
function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self)
internal
pure
returns (
bool,
bool,
bool,
bool
)
{
return (
(self.data & ~ACTIVE_MASK) != 0,
(self.data & ~FROZEN_MASK) != 0,
(self.data & ~BORROWING_MASK) != 0,
(self.data & ~STABLE_BORROWING_MASK) != 0
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {Errors} from "../helpers/Errors.sol";
import {DataTypes} from "../types/DataTypes.sol";
/**
* @title NftConfiguration library
* @author Bend
* @notice Implements the bitmap logic to handle the NFT configuration
*/
library NftConfiguration {
uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore
uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore
uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore
uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant REDEEM_DURATION_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant AUCTION_DURATION_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant REDEEM_FINE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant REDEEM_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore
/// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed
uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;
uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;
uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;
uint256 constant IS_FROZEN_START_BIT_POSITION = 57;
uint256 constant REDEEM_DURATION_START_BIT_POSITION = 64;
uint256 constant AUCTION_DURATION_START_BIT_POSITION = 72;
uint256 constant REDEEM_FINE_START_BIT_POSITION = 80;
uint256 constant REDEEM_THRESHOLD_START_BIT_POSITION = 96;
uint256 constant MAX_VALID_LTV = 65535;
uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;
uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535;
uint256 constant MAX_VALID_REDEEM_DURATION = 255;
uint256 constant MAX_VALID_AUCTION_DURATION = 255;
uint256 constant MAX_VALID_REDEEM_FINE = 65535;
uint256 constant MAX_VALID_REDEEM_THRESHOLD = 65535;
/**
* @dev Sets the Loan to Value of the NFT
* @param self The NFT configuration
* @param ltv the new ltv
**/
function setLtv(DataTypes.NftConfigurationMap memory self, uint256 ltv) internal pure {
require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV);
self.data = (self.data & LTV_MASK) | ltv;
}
/**
* @dev Gets the Loan to Value of the NFT
* @param self The NFT configuration
* @return The loan to value
**/
function getLtv(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return self.data & ~LTV_MASK;
}
/**
* @dev Sets the liquidation threshold of the NFT
* @param self The NFT configuration
* @param threshold The new liquidation threshold
**/
function setLiquidationThreshold(DataTypes.NftConfigurationMap memory self, uint256 threshold) internal pure {
require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD);
self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);
}
/**
* @dev Gets the liquidation threshold of the NFT
* @param self The NFT configuration
* @return The liquidation threshold
**/
function getLiquidationThreshold(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;
}
/**
* @dev Sets the liquidation bonus of the NFT
* @param self The NFT configuration
* @param bonus The new liquidation bonus
**/
function setLiquidationBonus(DataTypes.NftConfigurationMap memory self, uint256 bonus) internal pure {
require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS);
self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);
}
/**
* @dev Gets the liquidation bonus of the NFT
* @param self The NFT configuration
* @return The liquidation bonus
**/
function getLiquidationBonus(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;
}
/**
* @dev Sets the active state of the NFT
* @param self The NFT configuration
* @param active The active state
**/
function setActive(DataTypes.NftConfigurationMap memory self, bool active) internal pure {
self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);
}
/**
* @dev Gets the active state of the NFT
* @param self The NFT configuration
* @return The active state
**/
function getActive(DataTypes.NftConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~ACTIVE_MASK) != 0;
}
/**
* @dev Sets the frozen state of the NFT
* @param self The NFT configuration
* @param frozen The frozen state
**/
function setFrozen(DataTypes.NftConfigurationMap memory self, bool frozen) internal pure {
self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);
}
/**
* @dev Gets the frozen state of the NFT
* @param self The NFT configuration
* @return The frozen state
**/
function getFrozen(DataTypes.NftConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~FROZEN_MASK) != 0;
}
/**
* @dev Sets the redeem duration of the NFT
* @param self The NFT configuration
* @param redeemDuration The redeem duration
**/
function setRedeemDuration(DataTypes.NftConfigurationMap memory self, uint256 redeemDuration) internal pure {
require(redeemDuration <= MAX_VALID_REDEEM_DURATION, Errors.RC_INVALID_REDEEM_DURATION);
self.data = (self.data & REDEEM_DURATION_MASK) | (redeemDuration << REDEEM_DURATION_START_BIT_POSITION);
}
/**
* @dev Gets the redeem duration of the NFT
* @param self The NFT configuration
* @return The redeem duration
**/
function getRedeemDuration(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION;
}
/**
* @dev Sets the auction duration of the NFT
* @param self The NFT configuration
* @param auctionDuration The auction duration
**/
function setAuctionDuration(DataTypes.NftConfigurationMap memory self, uint256 auctionDuration) internal pure {
require(auctionDuration <= MAX_VALID_AUCTION_DURATION, Errors.RC_INVALID_AUCTION_DURATION);
self.data = (self.data & AUCTION_DURATION_MASK) | (auctionDuration << AUCTION_DURATION_START_BIT_POSITION);
}
/**
* @dev Gets the auction duration of the NFT
* @param self The NFT configuration
* @return The auction duration
**/
function getAuctionDuration(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~AUCTION_DURATION_MASK) >> AUCTION_DURATION_START_BIT_POSITION;
}
/**
* @dev Sets the redeem fine of the NFT
* @param self The NFT configuration
* @param redeemFine The redeem duration
**/
function setRedeemFine(DataTypes.NftConfigurationMap memory self, uint256 redeemFine) internal pure {
require(redeemFine <= MAX_VALID_REDEEM_FINE, Errors.RC_INVALID_REDEEM_FINE);
self.data = (self.data & REDEEM_FINE_MASK) | (redeemFine << REDEEM_FINE_START_BIT_POSITION);
}
/**
* @dev Gets the redeem fine of the NFT
* @param self The NFT configuration
* @return The redeem fine
**/
function getRedeemFine(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~REDEEM_FINE_MASK) >> REDEEM_FINE_START_BIT_POSITION;
}
/**
* @dev Sets the redeem threshold of the NFT
* @param self The NFT configuration
* @param redeemThreshold The redeem duration
**/
function setRedeemThreshold(DataTypes.NftConfigurationMap memory self, uint256 redeemThreshold) internal pure {
require(redeemThreshold <= MAX_VALID_REDEEM_THRESHOLD, Errors.RC_INVALID_REDEEM_THRESHOLD);
self.data = (self.data & REDEEM_THRESHOLD_MASK) | (redeemThreshold << REDEEM_THRESHOLD_START_BIT_POSITION);
}
/**
* @dev Gets the redeem threshold of the NFT
* @param self The NFT configuration
* @return The redeem threshold
**/
function getRedeemThreshold(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION;
}
/**
* @dev Gets the configuration flags of the NFT
* @param self The NFT configuration
* @return The state flags representing active, frozen
**/
function getFlags(DataTypes.NftConfigurationMap storage self) internal view returns (bool, bool) {
uint256 dataLocal = self.data;
return ((dataLocal & ~ACTIVE_MASK) != 0, (dataLocal & ~FROZEN_MASK) != 0);
}
/**
* @dev Gets the configuration flags of the NFT from a memory object
* @param self The NFT configuration
* @return The state flags representing active, frozen
**/
function getFlagsMemory(DataTypes.NftConfigurationMap memory self) internal pure returns (bool, bool) {
return ((self.data & ~ACTIVE_MASK) != 0, (self.data & ~FROZEN_MASK) != 0);
}
/**
* @dev Gets the collateral configuration paramters of the NFT
* @param self The NFT configuration
* @return The state params representing ltv, liquidation threshold, liquidation bonus
**/
function getCollateralParams(DataTypes.NftConfigurationMap storage self)
internal
view
returns (
uint256,
uint256,
uint256
)
{
uint256 dataLocal = self.data;
return (
dataLocal & ~LTV_MASK,
(dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
(dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION
);
}
/**
* @dev Gets the auction configuration paramters of the NFT
* @param self The NFT configuration
* @return The state params representing redeem duration, auction duration, redeem fine
**/
function getAuctionParams(DataTypes.NftConfigurationMap storage self)
internal
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
uint256 dataLocal = self.data;
return (
(dataLocal & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION,
(dataLocal & ~AUCTION_DURATION_MASK) >> AUCTION_DURATION_START_BIT_POSITION,
(dataLocal & ~REDEEM_FINE_MASK) >> REDEEM_FINE_START_BIT_POSITION,
(dataLocal & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION
);
}
/**
* @dev Gets the collateral configuration paramters of the NFT from a memory object
* @param self The NFT configuration
* @return The state params representing ltv, liquidation threshold, liquidation bonus
**/
function getCollateralParamsMemory(DataTypes.NftConfigurationMap memory self)
internal
pure
returns (
uint256,
uint256,
uint256
)
{
return (
self.data & ~LTV_MASK,
(self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
(self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION
);
}
/**
* @dev Gets the auction configuration paramters of the NFT from a memory object
* @param self The NFT configuration
* @return The state params representing redeem duration, auction duration, redeem fine
**/
function getAuctionParamsMemory(DataTypes.NftConfigurationMap memory self)
internal
pure
returns (
uint256,
uint256,
uint256,
uint256
)
{
return (
(self.data & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION,
(self.data & ~AUCTION_DURATION_MASK) >> AUCTION_DURATION_START_BIT_POSITION,
(self.data & ~REDEEM_FINE_MASK) >> REDEEM_FINE_START_BIT_POSITION,
(self.data & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
library DataTypes {
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address bTokenAddress;
address debtTokenAddress;
//address of the interest rate strategy
address interestRateAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct NftData {
//stores the nft configuration
NftConfigurationMap configuration;
//address of the bNFT contract
address bNftAddress;
//the id of the nft. Represents the position in the list of the active nfts
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct NftConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 56: NFT is active
//bit 57: NFT is frozen
uint256 data;
}
/**
* @dev Enum describing the current state of a loan
* State change flow:
* Created -> Active -> Repaid
* -> Auction -> Defaulted
*/
enum LoanState {
// We need a default that is not 'Created' - this is the zero value
None,
// The loan data is stored, but not initiated yet.
Created,
// The loan has been initialized, funds have been delivered to the borrower and the collateral is held.
Active,
// The loan is in auction, higest price liquidator will got chance to claim it.
Auction,
// The loan has been repaid, and the collateral has been returned to the borrower. This is a terminal state.
Repaid,
// The loan was delinquent and collateral claimed by the liquidator. This is a terminal state.
Defaulted
}
struct LoanData {
//the id of the nft loan
uint256 loanId;
//the current state of the loan
LoanState state;
//address of borrower
address borrower;
//address of nft asset token
address nftAsset;
//the id of nft token
uint256 nftTokenId;
//address of reserve asset token
address reserveAsset;
//scaled borrow amount. Expressed in ray
uint256 scaledAmount;
//start time of first bid time
uint256 bidStartTimestamp;
//bidder address of higest bid
address bidderAddress;
//price of higest bid
uint256 bidPrice;
//borrow amount of loan
uint256 bidBorrowAmount;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {DataTypes} from "../libraries/types/DataTypes.sol";
import {ReserveLogic} from "../libraries/logic/ReserveLogic.sol";
import {NftLogic} from "../libraries/logic/NftLogic.sol";
import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol";
contract LendPoolStorage {
using ReserveLogic for DataTypes.ReserveData;
using NftLogic for DataTypes.NftData;
ILendPoolAddressesProvider internal _addressesProvider;
mapping(address => DataTypes.ReserveData) internal _reserves;
mapping(address => DataTypes.NftData) internal _nfts;
mapping(uint256 => address) internal _reservesList;
uint256 internal _reservesCount;
mapping(uint256 => address) internal _nftsList;
uint256 internal _nftsCount;
bool internal _paused;
uint256 internal _maxNumberOfReserves;
uint256 internal _maxNumberOfNfts;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
interface IIncentivesController {
/**
* @dev Called by the corresponding asset on any update that affects the rewards distribution
* @param asset The address of the user
* @param totalSupply The total supply of the asset in the lending pool
* @param userBalance The balance of the user of the asset in the lending pool
**/
function handleAction(
address asset,
uint256 totalSupply,
uint256 userBalance
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
/**
* @title IInterestRate interface
* @dev Interface for the calculation of the interest rates
* @author Bend
*/
interface IInterestRate {
function baseVariableBorrowRate() external view returns (uint256);
function getMaxVariableBorrowRate() external view returns (uint256);
function calculateInterestRates(
address reserve,
uint256 availableLiquidity,
uint256 totalVariableDebt,
uint256 reserveFactor
) external view returns (uint256, uint256);
function calculateInterestRates(
address reserve,
address bToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
uint256 totalVariableDebt,
uint256 reserveFactor
) external view returns (uint256 liquidityRate, uint256 variableBorrowRate);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {WadRayMath} from "./WadRayMath.sol";
library MathUtils {
using WadRayMath for uint256;
/// @dev Ignoring leap years
uint256 internal constant SECONDS_PER_YEAR = 365 days;
/**
* @dev Function to calculate the interest accumulated using a linear interest rate formula
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) {
//solium-disable-next-line
uint256 timeDifference = block.timestamp - (uint256(lastUpdateTimestamp));
return ((rate * (timeDifference)) / SECONDS_PER_YEAR) + (WadRayMath.ray());
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(
uint256 rate,
uint40 lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solium-disable-next-line
uint256 exp = currentTimestamp - (uint256(lastUpdateTimestamp));
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = rate / SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = (exp * (expMinusOne) * (basePowerTwo)) / 2;
uint256 thirdTerm = (exp * (expMinusOne) * (expMinusTwo) * (basePowerThree)) / 6;
return WadRayMath.ray() + (ratePerSecond * (exp)) + (secondTerm) + (thirdTerm);
}
/**
* @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp
* @param rate The interest rate (in ray)
* @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated
**/
function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) {
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// 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 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);
}
|
Updates the liquidity cumulative index and the variable borrow index. reserve the reserve object/
|
function updateState(DataTypes.ReserveData storage reserve) internal {
uint256 scaledVariableDebt = IDebtToken(reserve.debtTokenAddress).scaledTotalSupply();
uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;
uint256 previousLiquidityIndex = reserve.liquidityIndex;
uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;
(uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes(
reserve,
scaledVariableDebt,
previousLiquidityIndex,
previousVariableBorrowIndex,
lastUpdatedTimestamp
);
_mintToTreasury(
reserve,
scaledVariableDebt,
previousVariableBorrowIndex,
newLiquidityIndex,
newVariableBorrowIndex,
lastUpdatedTimestamp
);
}
| 503,175
|
./full_match/1/0x8F8745BD5f9b1464a49F90b95c2F3Aa4d24A1180/sources/contracts/GarbageFriends.sol
|
Update royalty information receiver address numerator uint96/
|
function setDefaultRoyalty(
address payable receiver,
uint96 numerator
) external onlyOwner {
_setDefaultRoyalty(receiver, numerator);
}
| 2,984,335
|
./full_match/137/0x1bDC43dE7DDFC667Eaf6B1fd337BB3CF18C477F0/sources/masterchef.sol
|
Deposit LP tokens to MasterChef for DogeMatic allocation.
|
function deposit(uint256 _pid, uint256 _amount, address _referrer) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (_amount > 0 && address(DogeMaticReferral) != address(0) && _referrer != address(0) && _referrer != msg.sender) {
DogeMaticReferral.recordReferral(msg.sender, _referrer);
}
payOrLockupPendingDogeMatic(_pid);
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if (address(pool.lpToken) == address(DogeMatic)) {
uint256 transferTax = _amount.mul(DogeMatic.transferTaxRate()).div(10000);
_amount = _amount.sub(transferTax);
}
if (pool.depositFeeBP > 0) {
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accDogeMaticPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| 3,740,686
|
pragma solidity ^0.4.24;
// ----------------------------------------------------------------------------
// Sample token contract
//
// Symbol : KDC
// Name : KudetaToken
// Total supply : 2000000000000
// Decimals : 4
// Owner Account : 0x6Ecd9f344F9e94EC5f81237bc44EfF018D489701
// (c) The Kudeta
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Lib: Safe Math
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
/**
Contract function to receive approval and execute function in one call
*/
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
/**
ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers
*/
contract KudetaToken is ERC20Interface, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// Constructor
constructor() public {
symbol = "KDC";
name = "KudetaToken";
decimals = 4;
_totalSupply = 2000000000000;
balances[0x6Ecd9f344F9e94EC5f81237bc44EfF018D489701] = _totalSupply;
emit Transfer(address(0), 0x6Ecd9f344F9e94EC5f81237bc44EfF018D489701, _totalSupply);
}
// Total supply
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// Get the token balance for account tokenOwner
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// Don't accept ETH
function () public payable {
revert();
}
}
|
Returns the amount of tokens approved by the owner that can be transferred to the spender's account
|
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
| 10,206,270
|
./full_match/4/0x158ed9615893f82398CB29298Aa534AEA3a1F1AF/sources/browser/nft.sol
|
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./ Clear approvals from the previous owner
|
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "k025");
require(to != address(0), "k026");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
| 731,219
|
./full_match/5/0x81c7a9d494c74F113cCa32d174925352bD3875f1/sources/_connext/nxtp-contracts/contracts/core/connext/libraries/SwapUtils.sol
|
Externally calculates a swap between two tokens. self Swap struct to read from tokenIndexFrom the token to sell tokenIndexTo the token to buy dy the number of tokens to buy. return dx the number of tokens the user have to transfer + fee/
|
function calculateSwapInv(
Swap storage self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dy
) internal view returns (uint256 dx) {
(dx, ) = _calculateSwapInv(self, tokenIndexFrom, tokenIndexTo, dy, self.balances);
}
| 1,910,778
|
./partial_match/1/0xC62b8c58984a7f9E15933bC9E20159D240Ab0D8D/sources/contracts/protocol/libraries/configuration/ReserveConfiguration.sol
|
Gets the siloed borrowing flag for the reserve. When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset. self The reserve configuration return The siloed borrowing flag/
|
function getSiloedBorrowing(
DataTypes.ReserveConfigurationMap memory self
) internal pure returns (bool) {
return (self.data & ~SILOED_BORROWING_MASK) != 0;
}
| 2,784,108
|
pragma solidity ^0.4.23;
interface RegistryInterface {
function getLatestVersion(address stor_addr, bytes32 exec_id, address provider, bytes32 app_name)
external view returns (bytes32 latest_name);
function getVersionImplementation(address stor_addr, bytes32 exec_id, address provider, bytes32 app_name, bytes32 version_name)
external view returns (address index, bytes4[] selectors, address[] implementations);
}
contract AbstractStorage {
// Special storage locations - applications can read from 0x0 to get the execution id, and 0x20
// to get the sender from which the call originated
bytes32 private exec_id;
address private sender;
// Keeps track of the number of applicaions initialized, so that each application has a unique execution id
uint private nonce;
/// EVENTS ///
event ApplicationInitialized(bytes32 indexed execution_id, address indexed index, address script_exec);
event ApplicationExecution(bytes32 indexed execution_id, address indexed script_target);
event DeliveredPayment(bytes32 indexed execution_id, address indexed destination, uint amount);
/// CONSTANTS ///
// STORAGE LOCATIONS //
bytes32 internal constant EXEC_PERMISSIONS = keccak256('script_exec_permissions');
bytes32 internal constant APP_IDX_ADDR = keccak256('index');
// ACTION REQUESTORS //
bytes4 internal constant EMITS = bytes4(keccak256('Emit((bytes32[],bytes)[])'));
bytes4 internal constant STORES = bytes4(keccak256('Store(bytes32[])'));
bytes4 internal constant PAYS = bytes4(keccak256('Pay(bytes32[])'));
bytes4 internal constant THROWS = bytes4(keccak256('Error(string)'));
// SELECTORS //
bytes4 internal constant REG_APP
= bytes4(keccak256('registerApp(bytes32,address,bytes4[],address[])'));
bytes4 internal constant REG_APP_VER
= bytes4(keccak256('registerAppVersion(bytes32,bytes32,address,bytes4[],address[])'));
bytes4 internal constant UPDATE_EXEC_SEL
= bytes4(keccak256('updateExec(address)'));
bytes4 internal constant UPDATE_INST_SEL
= bytes4(keccak256('updateInstance(bytes32,bytes32,bytes32)'));
// Creates an instance of a registry application and returns the execution id
function createRegistry(address _registry_idx, address _implementation) external returns (bytes32) {
bytes32 new_exec_id = keccak256(++nonce);
put(new_exec_id, keccak256(msg.sender, EXEC_PERMISSIONS), bytes32(1));
put(new_exec_id, APP_IDX_ADDR, bytes32(_registry_idx));
put(new_exec_id, keccak256(REG_APP, 'implementation'), bytes32(_implementation));
put(new_exec_id, keccak256(REG_APP_VER, 'implementation'), bytes32(_implementation));
put(new_exec_id, keccak256(UPDATE_INST_SEL, 'implementation'), bytes32(_implementation));
put(new_exec_id, keccak256(UPDATE_EXEC_SEL, 'implementation'), bytes32(_implementation));
emit ApplicationInitialized(new_exec_id, _registry_idx, msg.sender);
return new_exec_id;
}
/// APPLICATION INSTANCE INITIALIZATION ///
/*
Executes an initialization function of an application, generating a new exec id that will be associated with that address
@param _sender: The sender of the transaction, as reported by the script exec contract
@param _app_name: The name of the application which will be instantiated
@param _provider: The provider under which the application is registered
@param _registry_id: The execution id of the registry app
@param _calldata: The calldata to forward to the application
@return new_exec_id: A new, unique execution id paired with the created instance of the application
@return version: The name of the version of the instance
*/
function createInstance(address _sender, bytes32 _app_name, address _provider, bytes32 _registry_id, bytes _calldata) external payable returns (bytes32 new_exec_id, bytes32 version) {
// Ensure valid input -
require(_sender != 0 && _app_name != 0 && _provider != 0 && _registry_id != 0 && _calldata.length >= 4, 'invalid input');
// Create new exec id by incrementing the nonce -
new_exec_id = keccak256(++nonce);
// Sanity check - verify that this exec id is not linked to an existing application -
assert(getIndex(new_exec_id) == address(0));
// Set the allowed addresses and selectors for the new instance, from the script registry -
address index;
(index, version) = setImplementation(new_exec_id, _app_name, _provider, _registry_id);
// Set the exec id and sender addresses for the target application -
setContext(new_exec_id, _sender);
// Execute application, create a new exec id, and commit the returned data to storage -
require(address(index).delegatecall(_calldata) == false, 'Unsafe execution');
// Get data returned from call revert and perform requested actions -
executeAppReturn(new_exec_id);
// Emit event
emit ApplicationInitialized(new_exec_id, index, msg.sender);
// If execution reaches this point, newly generated exec id should be valid -
assert(new_exec_id != bytes32(0));
// Ensure that any additional balance is transferred back to the sender -
if (address(this).balance > 0)
address(msg.sender).transfer(address(this).balance);
}
/*
Executes an initialized application associated with the given exec id, under the sender's address and with
the given calldata
@param _sender: The address reported as the call sender by the script exec contract
@param _exec_id: The execution id corresponding to an instance of the application
@param _calldata: The calldata to forward to the application
@return n_emitted: The number of events emitted on behalf of the application
@return n_paid: The number of destinations ETH was forwarded to on behalf of the application
@return n_stored: The number of storage slots written to on behalf of the application
*/
function exec(address _sender, bytes32 _exec_id, bytes _calldata) external payable returns (uint n_emitted, uint n_paid, uint n_stored) {
// Ensure valid input and input size - minimum 4 bytes
require(_calldata.length >= 4 && _sender != address(0) && _exec_id != bytes32(0));
// Get the target address associated with the given exec id
address target = getTarget(_exec_id, getSelector(_calldata));
require(target != address(0), 'Uninitialized application');
// Set the exec id and sender addresses for the target application -
setContext(_exec_id, _sender);
// Execute application and commit returned data to storage -
require(address(target).delegatecall(_calldata) == false, 'Unsafe execution');
(n_emitted, n_paid, n_stored) = executeAppReturn(_exec_id);
// If no events were emitted, no wei was forwarded, and no storage was changed, revert -
if (n_emitted == 0 && n_paid == 0 && n_stored == 0)
revert('No state change occured');
// Emit event -
emit ApplicationExecution(_exec_id, target);
// Ensure that any additional balance is transferred back to the sender -
if (address(this).balance > 0)
address(msg.sender).transfer(address(this).balance);
}
/// APPLICATION RETURNDATA HANDLING ///
/*
This function parses data returned by an application and executes requested actions. Because applications
are assumed to be stateless, they cannot emit events, store data, or forward payment. Therefore, these
steps to execution are handled in the storage contract by this function.
Returned data can execute several actions requested by the application through the use of an 'action requestor':
Some actions mirror nested dynamic return types, which are manually encoded and decoded as they are not supported
1. THROWS - App requests storage revert with a given message
--Format: bytes
--Payload is simply an array of bytes that will be reverted back to the caller
2. EMITS - App requests that events be emitted. Can provide topics to index, as well as arbitrary length data
--Format: Event[]
--Event format: [uint n_topics][bytes32 topic_0]...[bytes32 topic_n][uint data.length][bytes data]
3. STORES - App requests that data be stored to its storage. App storage locations are hashed with the app's exec id
--Format: bytes32[]
--bytes32[] consists of a data location followed by a value to place at that location
--as such, its length must be even
--Ex: [value_0][location_0]...[value_n][location_n]
4. PAYS - App requests that ETH sent to the contract be forwarded to other addresses.
--Format: bytes32[]
--bytes32[] consists of an address to send ETH to, followed by an amount to send to that address
--As such, its length must be even
--Ex: [amt_0][bytes32(destination_0)]...[amt_n][bytes32(destination_n)]
Returndata is structured as an array of bytes, beginning with an action requestor ('THROWS', 'PAYS', etc)
followed by that action's appropriately-formatted data (see above). Up to 3 actions with formatted data can be placed
into returndata, and each must be unique (i.e. no two 'EMITS' actions).
If the THROWS action is requested, it must be the first event requested. The event will be parsed
and logged, and no other actions will be executed. If the THROWS requestor is not the first action
requested, this function will throw
@param _exec_id: The execution id which references this application's storage
@return n_emitted: The number of events emitted on behalf of the application
@return n_paid: The number of destinations ETH was forwarded to on behalf of the application
@return n_stored: The number of storage slots written to on behalf of the application
*/
function executeAppReturn(bytes32 _exec_id) internal returns (uint n_emitted, uint n_paid, uint n_stored) {
uint _ptr; // Will be a pointer to the data returned by the application call
uint ptr_bound; // Will be the maximum value of the pointer possible (end of the memory stored in the pointer)
(ptr_bound, _ptr) = getReturnedData();
// If the application reverted with an error, we can check directly for its selector -
if (getAction(_ptr) == THROWS) {
// Execute THROWS request
doThrow(_ptr);
// doThrow should revert, so we should never reach this point
assert(false);
}
// Ensure there are at least 64 bytes stored at the pointer
require(ptr_bound >= _ptr + 64, 'Malformed returndata - invalid size');
_ptr += 64;
// Iterate over returned data and execute actions
bytes4 action;
while (_ptr <= ptr_bound && (action = getAction(_ptr)) != 0x0) {
if (action == EMITS) {
// If the action is EMITS, and this action has already been executed, throw
require(n_emitted == 0, 'Duplicate action: EMITS');
// Otherwise, emit events and get amount of events emitted
// doEmit returns the pointer incremented to the end of the data portion of the action executed
(_ptr, n_emitted) = doEmit(_ptr, ptr_bound);
// If 0 events were emitted, returndata is malformed: throw
require(n_emitted != 0, 'Unfulfilled action: EMITS');
} else if (action == STORES) {
// If the action is STORES, and this action has already been executed, throw
require(n_stored == 0, 'Duplicate action: STORES');
// Otherwise, store data and get amount of slots written to
// doStore increments the pointer to the end of the data portion of the action executed
(_ptr, n_stored) = doStore(_ptr, ptr_bound, _exec_id);
// If no storage was performed, returndata is malformed: throw
require(n_stored != 0, 'Unfulfilled action: STORES');
} else if (action == PAYS) {
// If the action is PAYS, and this action has already been executed, throw
require(n_paid == 0, 'Duplicate action: PAYS');
// Otherwise, forward ETH and get amount of addresses forwarded to
// doPay increments the pointer to the end of the data portion of the action executed
(_ptr, n_paid) = doPay(_exec_id, _ptr, ptr_bound);
// If no destinations recieved ETH, returndata is malformed: throw
require(n_paid != 0, 'Unfulfilled action: PAYS');
} else {
// Unrecognized action requested. returndata is malformed: throw
revert('Malformed returndata - unknown action');
}
}
assert(n_emitted != 0 || n_paid != 0 || n_stored != 0);
}
/// HELPERS ///
/*
Reads application information from the script registry, and sets up permissions for the new instance's various functions
@param _new_exec_id: The execution id being created, for which permissions will be registered
@param _app_name: The name of the new application instance - corresponds to an application registered by the provider under that name
@param _provider: The address of the account that registered an application under the given name
@param _registry_id: The exec id of the registry from which the information will be read
*/
function setImplementation(bytes32 _new_exec_id, bytes32 _app_name, address _provider, bytes32 _registry_id) internal returns (address index, bytes32 version) {
// Get the index address for the registry app associated with the passed-in exec id
index = getIndex(_registry_id);
require(index != address(0) && index != address(this), 'Registry application not found');
// Get the name of the latest version from the registry app at the given address
version = RegistryInterface(index).getLatestVersion(
address(this), _registry_id, _provider, _app_name
);
// Ensure the version name is valid -
require(version != bytes32(0), 'Invalid version name');
// Get the allowed selectors and addresses for the new instance from the registry app
bytes4[] memory selectors;
address[] memory implementations;
(index, selectors, implementations) = RegistryInterface(index).getVersionImplementation(
address(this), _registry_id, _provider, _app_name, version
);
// Ensure a valid index address for the new instance -
require(index != address(0), 'Invalid index address');
// Ensure a nonzero number of allowed selectors and implementing addresses -
require(selectors.length == implementations.length && selectors.length != 0, 'Invalid implementation length');
// Set the index address for the new instance -
bytes32 seed = APP_IDX_ADDR;
put(_new_exec_id, seed, bytes32(index));
// Loop over implementing addresses, and map each function selector to its corresponding address for the new instance
for (uint i = 0; i < selectors.length; i++) {
require(selectors[i] != 0 && implementations[i] != 0, 'invalid input - expected nonzero implementation');
seed = keccak256(selectors[i], 'implementation');
put(_new_exec_id, seed, bytes32(implementations[i]));
}
return (index, version);
}
// Returns the index address of an application using a given exec id, or 0x0
// if the instance does not exist
function getIndex(bytes32 _exec_id) public view returns (address) {
bytes32 seed = APP_IDX_ADDR;
function (bytes32, bytes32) view returns (address) getter;
assembly { getter := readMap }
return getter(_exec_id, seed);
}
// Returns the address to which calldata with the given selector will be routed
function getTarget(bytes32 _exec_id, bytes4 _selector) public view returns (address) {
bytes32 seed = keccak256(_selector, 'implementation');
function (bytes32, bytes32) view returns (address) getter;
assembly { getter := readMap }
return getter(_exec_id, seed);
}
struct Map { mapping(bytes32 => bytes32) inner; }
// Receives a storage pointer and returns the value mapped to the seed at that pointer
function readMap(Map storage _map, bytes32 _seed) internal view returns (bytes32) {
return _map.inner[_seed];
}
// Maps the seed to the value within the execution id's storage
function put(bytes32 _exec_id, bytes32 _seed, bytes32 _val) internal {
function (bytes32, bytes32, bytes32) puts;
assembly { puts := putMap }
puts(_exec_id, _seed, _val);
}
// Receives a storage pointer and maps the seed to the value at that pointer
function putMap(Map storage _map, bytes32 _seed, bytes32 _val) internal {
_map.inner[_seed] = _val;
}
/// APPLICATION EXECUTION ///
function getSelector(bytes memory _calldata) internal pure returns (bytes4 sel) {
assembly {
sel := and(
mload(add(0x20, _calldata)),
0xffffffff00000000000000000000000000000000000000000000000000000000
)
}
}
/*
After validating that returned data is larger than 32 bytes, returns a pointer to the returned data
in memory, as well as a pointer to the end of returndata in memory
@return ptr_bounds: The pointer cannot be this value and be reading from returndata
@return _returndata_ptr: A pointer to the returned data in memory
*/
function getReturnedData() internal pure returns (uint ptr_bounds, uint _returndata_ptr) {
assembly {
// returndatasize must be minimum 96 bytes (offset, length, and requestor)
if lt(returndatasize, 0x60) {
mstore(0, 0x20)
mstore(0x20, 24)
mstore(0x40, 'Insufficient return size')
revert(0, 0x60)
}
// Get memory location to which returndata will be copied
_returndata_ptr := msize
// Copy returned data to pointer location
returndatacopy(_returndata_ptr, 0, returndatasize)
// Get maximum memory location value for returndata
ptr_bounds := add(_returndata_ptr, returndatasize)
// Set new free-memory pointer to point after the returndata in memory
// Returndata is automatically 32-bytes padded
mstore(0x40, add(0x20, ptr_bounds))
}
}
/*
Returns the value stored in memory at the pointer. Used to determine the size of fields in returned data
@param _ptr: A pointer to some location in memory containing returndata
@return length: The value stored at that pointer
*/
function getLength(uint _ptr) internal pure returns (uint length) {
assembly { length := mload(_ptr) }
}
// Executes the THROWS action, reverting any returned data back to the caller
function doThrow(uint _ptr) internal pure {
assert(getAction(_ptr) == THROWS);
assembly { revert(_ptr, returndatasize) }
}
/*
Parses and executes a PAYS action copied from returndata and located at the pointer
A PAYS action provides a set of addresses and corresponding amounts of ETH to send to those
addresses. The sender must ensure the call has sufficient funds, or the call will fail
PAYS actions follow a format of: [amt_0][address_0]...[amt_n][address_n]
@param _ptr: A pointer in memory to an application's returned payment request
@param _ptr_bound: The upper bound on the value for _ptr before it is reading invalid data
@return ptr: An updated pointer, pointing to the end of the PAYS action request in memory
@return n_paid: The number of destinations paid out to from the returned PAYS request
*/
function doPay(bytes32 _exec_id, uint _ptr, uint _ptr_bound) internal returns (uint ptr, uint n_paid) {
// Ensure ETH was sent with the call
require(msg.value > 0);
assert(getAction(_ptr) == PAYS);
_ptr += 4;
// Get number of destinations
uint num_destinations = getLength(_ptr);
_ptr += 32;
address pay_to;
uint amt;
// Loop over PAYS actions and process each one
while (_ptr <= _ptr_bound && n_paid < num_destinations) {
// Get the payment destination and amount from the pointer
assembly {
amt := mload(_ptr)
pay_to := mload(add(0x20, _ptr))
}
// Invalid address was passed as a payment destination - throw
if (pay_to == address(0) || pay_to == address(this))
revert('PAYS: invalid destination');
// Forward ETH and increment n_paid
address(pay_to).transfer(amt);
n_paid++;
// Increment pointer
_ptr += 64;
// Emit event
emit DeliveredPayment(_exec_id, pay_to, amt);
}
ptr = _ptr;
assert(n_paid == num_destinations);
}
/*
Parses and executes a STORES action copied from returndata and located at the pointer
A STORES action provides a set of storage locations and corresponding values to store at those locations
true storage locations within this contract are first hashed with the application's execution id to prevent
storage overlaps between applications sharing the contract
STORES actions follow a format of: [location_0][val_0]...[location_n][val_n]
@param _ptr: A pointer in memory to an application's returned storage request
@param _ptr_bound: The upper bound on the value for _ptr before it is reading invalid data
@param _exec_id: The execution id under which storage is located
@return ptr: An updated pointer, pointing to the end of the STORES action request in memory
@return n_stored: The number of storage locations written to from the returned STORES request
*/
function doStore(uint _ptr, uint _ptr_bound, bytes32 _exec_id) internal returns (uint ptr, uint n_stored) {
assert(getAction(_ptr) == STORES && _exec_id != bytes32(0));
_ptr += 4;
// Get number of locations to which data will be stored
uint num_locations = getLength(_ptr);
_ptr += 32;
bytes32 location;
bytes32 value;
// Loop over STORES actions and process each one
while (_ptr <= _ptr_bound && n_stored < num_locations) {
// Get storage location and value to store from the pointer
assembly {
location := mload(_ptr)
value := mload(add(0x20, _ptr))
}
// Store the data to the location hashed with the exec id
store(_exec_id, location, value);
// Increment n_stored and pointer
n_stored++;
_ptr += 64;
}
ptr = _ptr;
require(n_stored == num_locations);
}
/*
Parses and executes an EMITS action copied from returndata and located at the pointer
An EMITS action is a list of bytes that are able to be processed and passed into logging functions (log0, log1, etc)
EMITS actions follow a format of: [Event_0][Event_1]...[Event_n]
where each Event_i follows the format: [topic_0]...[topic_4][data.length]<data>
-The topics array is a bytes32 array of maximum length 4 and minimum 0
-The final data parameter is a simple bytes array, and is emitted as a non-indexed parameter
@param _ptr: A pointer in memory to an application's returned emit request
@param _ptr_bound: The upper bound on the value for _ptr before it is reading invalid data
@return ptr: An updated pointer, pointing to the end of the EMITS action request in memory
@return n_emitted: The number of events logged from the returned EMITS request
*/
function doEmit(uint _ptr, uint _ptr_bound) internal returns (uint ptr, uint n_emitted) {
assert(getAction(_ptr) == EMITS);
_ptr += 4;
// Converts number of events that will be emitted
uint num_events = getLength(_ptr);
_ptr += 32;
bytes32[] memory topics;
bytes memory data;
// Loop over EMITS actions and process each one
while (_ptr <= _ptr_bound && n_emitted < num_events) {
// Get array of topics and additional data from the pointer
assembly {
topics := _ptr
data := add(add(_ptr, 0x20), mul(0x20, mload(topics)))
}
// Get size of the Event's data in memory
uint log_size = 32 + (32 * (1 + topics.length)) + data.length;
assembly {
switch mload(topics) // topics.length
case 0 {
// Log Event.data array with no topics
log0(
add(0x20, data), // data(ptr)
mload(data) // data.length
)
}
case 1 {
// Log Event.data array with 1 topic
log1(
add(0x20, data), // data(ptr)
mload(data), // data.length
mload(add(0x20, topics)) // topics[0]
)
}
case 2 {
// Log Event.data array with 2 topics
log2(
add(0x20, data), // data(ptr)
mload(data), // data.length
mload(add(0x20, topics)), // topics[0]
mload(add(0x40, topics)) // topics[1]
)
}
case 3 {
// Log Event.data array with 3 topics
log3(
add(0x20, data), // data(ptr)
mload(data), // data.length
mload(add(0x20, topics)), // topics[0]
mload(add(0x40, topics)), // topics[1]
mload(add(0x60, topics)) // topics[2]
)
}
case 4 {
// Log Event.data array with 4 topics
log4(
add(0x20, data), // data(ptr)
mload(data), // data.length
mload(add(0x20, topics)), // topics[0]
mload(add(0x40, topics)), // topics[1]
mload(add(0x60, topics)), // topics[2]
mload(add(0x80, topics)) // topics[3]
)
}
default {
// Events must have 4 or fewer topics
mstore(0, 'EMITS: invalid topic count')
revert(0, 0x20)
}
}
// Event emitted - increment n_emitted and pointer
n_emitted++;
_ptr += log_size;
}
ptr = _ptr;
require(n_emitted == num_events);
}
// Return the bytes4 action requestor stored at the pointer, and cleans the remaining bytes
function getAction(uint _ptr) internal pure returns (bytes4 action) {
assembly {
// Get the first 4 bytes stored at the pointer, and clean the rest of the bytes remaining
action := and(mload(_ptr), 0xffffffff00000000000000000000000000000000000000000000000000000000)
}
}
// Sets the execution id and sender address in special storage locations, so that
// they are able to be read by the target application
function setContext(bytes32 _exec_id, address _sender) internal {
// Ensure the exec id and sender are nonzero
assert(_exec_id != bytes32(0) && _sender != address(0));
exec_id = _exec_id;
sender = _sender;
}
// Stores data to a given location, with a key (exec id)
function store(bytes32 _exec_id, bytes32 _location, bytes32 _data) internal {
// Get true location to store data to - hash of location hashed with exec id
_location = keccak256(_location, _exec_id);
// Store data at location
assembly { sstore(_location, _data) }
}
// STORAGE READS //
/*
Returns data stored at a given location
@param _location: The address to get data from
@return data: The data stored at the location after hashing
*/
function read(bytes32 _exec_id, bytes32 _location) public view returns (bytes32 data_read) {
_location = keccak256(_location, _exec_id);
assembly { data_read := sload(_location) }
}
/*
Returns data stored in several nonconsecutive locations
@param _locations: A dynamic array of storage locations to read from
@return data_read: The corresponding data stored in the requested locations
*/
function readMulti(bytes32 _exec_id, bytes32[] _locations) public view returns (bytes32[] data_read) {
data_read = new bytes32[](_locations.length);
for (uint i = 0; i < _locations.length; i++) {
data_read[i] = read(_exec_id, _locations[i]);
}
}
}
|
Stores data to a given location, with a key (exec id) Get true location to store data to - hash of location hashed with exec id Store data at location
|
function store(bytes32 _exec_id, bytes32 _location, bytes32 _data) internal {
_location = keccak256(_location, _exec_id);
}
@param _location: The address to get data from
@return data: The data stored at the location after hashing
| 329,309
|
./partial_match/1/0xB10daee1FCF62243aE27776D7a92D39dC8740f95/sources/lib/prb-math/src/sd59x18/Casting.sol
|
Casts an SD59x18 number into UD2x18. Requirements: - x must be positive. - x must be less than or equal to `uMAX_UD2x18`.
|
function intoUD2x18(SD59x18 x) pure returns (UD2x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Underflow(x);
}
if (xInt > int256(uint256(uMAX_UD2x18))) {
revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Overflow(x);
}
result = UD2x18.wrap(uint64(uint256(xInt)));
}
| 9,308,768
|
pragma solidity ^0.4.24;
// File: contracts/external/Controlled.sol
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
// File: contracts/external/TokenController.sol
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) public payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
// File: contracts/external/MiniMeToken.sol
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.2'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount) return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
uint previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
uint previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () public payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
// File: contracts/DTXToken.sol
contract DTXToken is MiniMeToken {
function DTXToken(address _tokenFactory) public MiniMeToken (
_tokenFactory,
0x0, // no parent token
0, // no snapshot block number from parent
"DaTa eXchange Token", // Token name
18, // Decimals
"DTX", // Symbol
true // Enable transfers
)
{}
}
// File: contracts/external/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/external/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/BountyVault.sol
contract BountyVault is Ownable {
using SafeMath for uint256;
// the tokencontract for the DataBrokerDAO
DTXToken public tokenContract;
uint256 public allocatedTotal;
// the list of addresses and how much they have earned.
mapping(address => uint256) public balances;
/// @dev the constructor
constructor(
address _tokenAddress
) public {
tokenContract = DTXToken(_tokenAddress);
}
/// @dev Withdraws the tokens
function withdrawTokens() public {
uint256 amount = balances[msg.sender];
require(amount > 0, "You have no tokens left");
balances[msg.sender] = 0;
require(tokenContract.transfer(msg.sender, amount), "Token transfer failed");
}
/// @dev utility function to allow the owner to allocate tokens
function allocateTokens(address[] _recipients, uint256[] _amounts) public onlyOwner {
for (uint256 i = 0; i < _recipients.length; i++) {
balances[_recipients[i]] = balances[_recipients[i]].add(_amounts[i]);
allocatedTotal = allocatedTotal.add(_amounts[i]);
}
}
}
|
Withdraws the tokens
|
function withdrawTokens() public {
uint256 amount = balances[msg.sender];
require(amount > 0, "You have no tokens left");
balances[msg.sender] = 0;
require(tokenContract.transfer(msg.sender, amount), "Token transfer failed");
}
| 13,569,252
|
./partial_match/1/0x3C6452d5a217Cc65b98F0803c6D1BD7Fe588389A/sources/SmartChefInitializable.sol
|
It allows the admin to update profile and thresholdPoints' requirement. This function is only callable by owner. _isRequested: the profile is requested _thresholdPoints: the threshold points/
|
function updateProfileAndThresholdPointsRequirement(bool _isRequested, uint256 _thresholdPoints)
external
onlyOwner
{
require(pancakeProfile != address(0), "Pancake profile address is null");
require(_thresholdPoints >= 0, "Threshold points need to exceed 0");
pancakeProfileIsRequested = _isRequested;
pancakeProfileThresholdPoints = _thresholdPoints;
emit UpdateProfileAndThresholdPointsRequirement(_isRequested, _thresholdPoints);
}
| 3,552,900
|
./full_match/1/0xbB9fB89d8aef7fE563b944540CC1fAc1aD4f9DEb/sources/TokenTorrent.sol
|
Moves distribution tokens from the locked pool to the unlocked pool, according to the previously defined unlock schedules. Publicly callable. return Number of newly unlocked distribution tokens./
|
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
'TokenTorrent: transfer out of locked pool failed');
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
| 4,953,399
|
./partial_match/1/0xCA8586d15187D31eeF8B006Fc298e0F4fB2519fA/sources/CannathaiNFTShop.sol
|
set private sale cost/
|
function setPrivateSaleCost(
uint256 _value
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_value > 0, "cannot be zero");
emit PrivateSaleCostSet(privateSaleCost, _value);
privateSaleCost = _value;
}
| 2,763,448
|
/*
website: huoguo.finance
This project was forked from SUSHI and YUNO projects.
Unless those projects have severe vulnerabilities, this contract will be fine
โโโ โโโโโโ โโโ โโโโโโโ โโโโโโโ โโโ โโโ โโโโโโโ
โโโ โโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโ
โโโโโโโโโโโ โโโโโโ โโโโโโ โโโโโโโ โโโโโโ โโโ
โโโโโโโโโโโ โโโโโโ โโโโโโ โโโโโโ โโโโโโ โโโ
โโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโ โโโ โโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโ
*/
pragma solidity ^0.6.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev 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 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 { }
}
// HuoguoToken with Governance.
contract HuoguoToken is ERC20("HUOGUO.finance", "HUOGUO"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
contract HuoguoChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of HUOGUOs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accHuoguoPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accHuoguoPerShare` (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. HUOGUOs to distribute per block.
uint256 lastRewardBlock; // Last block number that HUOGUOs distribution occurs.
uint256 accHuoguoPerShare; // Accumulated HUOGUOs per share, times 1e12. See below.
}
// The HUOGUO TOKEN!
HuoguoToken public huoguo;
// Dev address.
address public devaddr;
// Block number when bonus HUOGUO period ends.
uint256 public bonusEndBlock;
// HUOGUO tokens created per block.
uint256 public huoguoPerBlock;
// Bonus muliplier for early huoguo makers.
uint256 public constant BONUS_MULTIPLIER = 1; // no bonus
// 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 HUOGUO mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
HuoguoToken _huoguo,
address _devaddr,
uint256 _huoguoPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
huoguo = _huoguo;
devaddr = _devaddr;
huoguoPerBlock = _huoguoPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accHuoguoPerShare: 0
}));
}
// Update the given pool's HUOGUO allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// 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 HUOGUOs on frontend.
function pendingHuoguo(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accHuoguoPerShare = pool.accHuoguoPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 huoguoReward = multiplier.mul(huoguoPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accHuoguoPerShare = accHuoguoPerShare.add(huoguoReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accHuoguoPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function mint(uint256 amount) public onlyOwner{
huoguo.mint(devaddr, amount);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 huoguoReward = multiplier.mul(huoguoPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
huoguo.mint(devaddr, huoguoReward.div(20)); // 5%
huoguo.mint(address(this), huoguoReward);
pool.accHuoguoPerShare = pool.accHuoguoPerShare.add(huoguoReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for HUOGUO allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accHuoguoPerShare).div(1e12).sub(user.rewardDebt);
safeHuoguoTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accHuoguoPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// 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.accHuoguoPerShare).div(1e12).sub(user.rewardDebt);
safeHuoguoTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accHuoguoPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe huoguo transfer function, just in case if rounding error causes pool to not have enough HUOGUOs.
function safeHuoguoTransfer(address _to, uint256 _amount) internal {
uint256 huoguoBal = huoguo.balanceOf(address(this));
if (_amount > huoguoBal) {
huoguo.transfer(_to, huoguoBal);
} else {
huoguo.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
|
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.accHuoguoPerShare).div(1e12).sub(user.rewardDebt);
safeHuoguoTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accHuoguoPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| 436,811
|
/**
*Submitted for verification at Etherscan.io on 2021-06-30
*/
// SPDX-License-Identifier: Unlicense
pragma solidity^0.8.4;
// Part: IVault
interface IVault {
function deposit(
uint256,
uint256,
uint256,
uint256,
address
)
external
returns (
uint256,
uint256,
uint256
);
function withdraw(
uint256,
uint256,
uint256,
address
) external returns (uint256, uint256);
function getTotalAmounts() external view returns (uint256, uint256);
}
// Part: OpenZeppelin/openzeppelin-contracts@3.4.0/Address
/**
* @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);
}
}
}
}
// Part: OpenZeppelin/openzeppelin-contracts@3.4.0/Context
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Part: OpenZeppelin/openzeppelin-contracts@3.4.0/IERC20
/**
* @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);
}
// Part: OpenZeppelin/openzeppelin-contracts@3.4.0/Math
/**
* @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);
}
}
// Part: OpenZeppelin/openzeppelin-contracts@3.4.0/ReentrancyGuard
/**
* @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;
}
}
// Part: OpenZeppelin/openzeppelin-contracts@3.4.0/SafeMath
/**
* @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;
}
}
// Part: PositionKey
library PositionKey {
/// @dev Returns the key of the position in the core library
function compute(
address owner,
int24 tickLower,
int24 tickUpper
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
}
}
// Part: Uniswap/uniswap-v3-core@1.0.0/FixedPoint96
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// Part: Uniswap/uniswap-v3-core@1.0.0/FullMath
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(aรbรทdenominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = denominator & (~denominator + 1);
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(aรbรทdenominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3MintCallback
/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
// Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3PoolActions
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3PoolDerivedState
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3PoolEvents
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3PoolImmutables
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3PoolOwnerActions
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3PoolState
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3SwapCallback
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// Part: Uniswap/uniswap-v3-core@1.0.0/TickMath
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(uint24(MAX_TICK)), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// Part: LiquidityAmounts
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// Part: OpenZeppelin/openzeppelin-contracts@3.4.0/ERC20
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// Part: OpenZeppelin/openzeppelin-contracts@3.4.0/SafeERC20
/**
* @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");
}
}
}
// Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3Pool
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// Part: ExistVault
/**
* @title Exist Vault
* @notice A vault that provides liquidity on Uniswap V3.
*/
contract ExistVault is
IVault,
IUniswapV3MintCallback,
IUniswapV3SwapCallback,
ERC20,
ReentrancyGuard
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
event Deposit(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event Withdraw(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event CollectFees(
uint256 feesToVault0,
uint256 feesToVault1,
uint256 feesToProtocol0,
uint256 feesToProtocol1
);
event Snapshot(int24 tick, uint256 totalAmount0, uint256 totalAmount1, uint256 totalSupply);
IUniswapV3Pool public immutable pool;
IERC20 public immutable token0;
IERC20 public immutable token1;
int24 public immutable tickSpacing;
uint256 public protocolFee;
uint256 public maxTotalSupply;
address public strategy;
address public governance;
address public pendingGovernance;
int24 public baseLower;
int24 public baseUpper;
int24 public limitLower;
int24 public limitUpper;
uint256 public accruedProtocolFees0;
uint256 public accruedProtocolFees1;
/**
* @dev After deploying, strategy needs to be set via `setStrategy()`
* @param _pool Underlying Uniswap V3 pool
* @param _protocolFee Protocol fee expressed as multiple of 1e-6
* @param _maxTotalSupply Cap on total supply
*/
constructor(
address _pool,
uint256 _protocolFee,
uint256 _maxTotalSupply
) ERC20("Exist Vault", "AV") {
pool = IUniswapV3Pool(_pool);
token0 = IERC20(IUniswapV3Pool(_pool).token0());
token1 = IERC20(IUniswapV3Pool(_pool).token1());
tickSpacing = IUniswapV3Pool(_pool).tickSpacing();
protocolFee = _protocolFee;
maxTotalSupply = _maxTotalSupply;
governance = msg.sender;
require(_protocolFee < 1e6, "protocolFee");
}
/**
* @notice Deposits tokens in proportion to the vault's current holdings.
* @dev These tokens sit in the vault and are not used for liquidity on
* Uniswap until the next rebalance. Also note it's not necessary to check
* if user manipulated price to deposit cheaper, as the value of range
* orders can only by manipulated higher.
* @param amount0Desired Max amount of token0 to deposit
* @param amount1Desired Max amount of token1 to deposit
* @param amount0Min Revert if resulting `amount0` is less than this
* @param amount1Min Revert if resulting `amount1` is less than this
* @param to Recipient of shares
* @return shares Number of shares minted
* @return amount0 Amount of token0 deposited
* @return amount1 Amount of token1 deposited
*/
function deposit(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
address to
)
external
override
nonReentrant
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
require(amount0Desired > 0 || amount1Desired > 0, "amount0Desired or amount1Desired");
require(to != address(0) && to != address(this), "to");
// Poke positions so vault's current holdings are up-to-date
_poke(baseLower, baseUpper);
_poke(limitLower, limitUpper);
// Calculate amounts proportional to vault's holdings
(shares, amount0, amount1) = _calcSharesAndAmounts(amount0Desired, amount1Desired);
require(shares > 0, "shares");
require(amount0 >= amount0Min, "amount0Min");
require(amount1 >= amount1Min, "amount1Min");
// Pull in tokens from sender
if (amount0 > 0) token0.safeTransferFrom(msg.sender, address(this), amount0);
if (amount1 > 0) token1.safeTransferFrom(msg.sender, address(this), amount1);
// Mint shares to recipient
_mint(to, shares);
emit Deposit(msg.sender, to, shares, amount0, amount1);
require(totalSupply() <= maxTotalSupply, "maxTotalSupply");
}
/// @dev Do zero-burns to poke a position on Uniswap so earned fees are
/// updated. Should be called if total amounts needs to include up-to-date
/// fees.
function _poke(int24 tickLower, int24 tickUpper) internal {
(uint128 liquidity, , , , ) = _position(tickLower, tickUpper);
if (liquidity > 0) {
pool.burn(tickLower, tickUpper, 0);
}
}
/// @dev Calculates the largest possible `amount0` and `amount1` such that
/// they're in the same proportion as total amounts, but not greater than
/// `amount0Desired` and `amount1Desired` respectively.
function _calcSharesAndAmounts(uint256 amount0Desired, uint256 amount1Desired)
internal
view
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
uint256 totalSupply = totalSupply();
(uint256 total0, uint256 total1) = getTotalAmounts();
// If total supply > 0, vault can't be empty
assert(totalSupply == 0 || total0 > 0 || total1 > 0);
if (totalSupply == 0) {
// For first deposit, just use the amounts desired
amount0 = amount0Desired;
amount1 = amount1Desired;
shares = Math.max(amount0, amount1);
} else if (total0 == 0) {
amount1 = amount1Desired;
shares = amount1.mul(totalSupply).div(total1);
} else if (total1 == 0) {
amount0 = amount0Desired;
shares = amount0.mul(totalSupply).div(total0);
} else {
uint256 cross = Math.min(amount0Desired.mul(total1), amount1Desired.mul(total0));
require(cross > 0, "cross");
// Round up amounts
amount0 = cross.sub(1).div(total1).add(1);
amount1 = cross.sub(1).div(total0).add(1);
shares = cross.mul(totalSupply).div(total0).div(total1);
}
}
/**
* @notice Withdraws tokens in proportion to the vault's holdings.
* @param shares Shares burned by sender
* @param amount0Min Revert if resulting `amount0` is smaller than this
* @param amount1Min Revert if resulting `amount1` is smaller than this
* @param to Recipient of tokens
* @return amount0 Amount of token0 sent to recipient
* @return amount1 Amount of token1 sent to recipient
*/
function withdraw(
uint256 shares,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override nonReentrant returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0) && to != address(this), "to");
uint256 totalSupply = totalSupply();
// Burn shares
_burn(msg.sender, shares);
// Calculate token amounts proportional to unused balances
uint256 unusedAmount0 = getBalance0().mul(shares).div(totalSupply);
uint256 unusedAmount1 = getBalance1().mul(shares).div(totalSupply);
// Withdraw proportion of liquidity from Uniswap pool
(uint256 baseAmount0, uint256 baseAmount1) =
_burnLiquidityShare(baseLower, baseUpper, shares, totalSupply);
(uint256 limitAmount0, uint256 limitAmount1) =
_burnLiquidityShare(limitLower, limitUpper, shares, totalSupply);
// Sum up total amounts owed to recipient
amount0 = unusedAmount0.add(baseAmount0).add(limitAmount0);
amount1 = unusedAmount1.add(baseAmount1).add(limitAmount1);
require(amount0 >= amount0Min, "amount0Min");
require(amount1 >= amount1Min, "amount1Min");
// Push tokens to recipient
if (amount0 > 0) token0.safeTransfer(to, amount0);
if (amount1 > 0) token1.safeTransfer(to, amount1);
emit Withdraw(msg.sender, to, shares, amount0, amount1);
}
/// @dev Withdraws share of liquidity in a range from Uniswap pool.
function _burnLiquidityShare(
int24 tickLower,
int24 tickUpper,
uint256 shares,
uint256 totalSupply
) internal returns (uint256 amount0, uint256 amount1) {
(uint128 totalLiquidity, , , , ) = _position(tickLower, tickUpper);
uint256 liquidity = uint256(totalLiquidity).mul(shares).div(totalSupply);
if (liquidity > 0) {
(uint256 burned0, uint256 burned1, uint256 fees0, uint256 fees1) =
_burnAndCollect(tickLower, tickUpper, _toUint128(liquidity));
// Add share of fees
amount0 = burned0.add(fees0.mul(shares).div(totalSupply));
amount1 = burned1.add(fees1.mul(shares).div(totalSupply));
}
}
/**
* @notice Updates vault's positions. Can only be called by the strategy.
* @dev Two orders are placed - a base order and a limit order. The base
* order is placed first with as much liquidity as possible. This order
* should use up all of one token, leaving only the other one. This excess
* amount is then placed as a single-sided bid or ask order.
*/
function rebalance(
int256 swapAmount,
uint160 sqrtPriceLimitX96,
int24 _baseLower,
int24 _baseUpper,
int24 _bidLower,
int24 _bidUpper,
int24 _askLower,
int24 _askUpper
) external nonReentrant {
require(msg.sender == strategy, "strategy");
_checkRange(_baseLower, _baseUpper);
_checkRange(_bidLower, _bidUpper);
_checkRange(_askLower, _askUpper);
(, int24 tick, , , , , ) = pool.slot0();
require(_bidUpper <= tick, "bidUpper");
require(_askLower > tick, "askLower"); // inequality is strict as tick is rounded down
// Withdraw all current liquidity from Uniswap pool
{
(uint128 baseLiquidity, , , , ) = _position(baseLower, baseUpper);
(uint128 limitLiquidity, , , , ) = _position(limitLower, limitUpper);
_burnAndCollect(baseLower, baseUpper, baseLiquidity);
_burnAndCollect(limitLower, limitUpper, limitLiquidity);
}
// Emit snapshot to record balances and supply
uint256 balance0 = getBalance0();
uint256 balance1 = getBalance1();
emit Snapshot(tick, balance0, balance1, totalSupply());
if (swapAmount != 0) {
pool.swap(
address(this),
swapAmount > 0,
swapAmount > 0 ? swapAmount : -swapAmount,
sqrtPriceLimitX96,
""
);
balance0 = getBalance0();
balance1 = getBalance1();
}
// Place base order on Uniswap
uint128 liquidity = _liquidityForAmounts(_baseLower, _baseUpper, balance0, balance1);
_mintLiquidity(_baseLower, _baseUpper, liquidity);
(baseLower, baseUpper) = (_baseLower, _baseUpper);
balance0 = getBalance0();
balance1 = getBalance1();
// Place bid or ask order on Uniswap depending on which token is left
uint128 bidLiquidity = _liquidityForAmounts(_bidLower, _bidUpper, balance0, balance1);
uint128 askLiquidity = _liquidityForAmounts(_askLower, _askUpper, balance0, balance1);
if (bidLiquidity > askLiquidity) {
_mintLiquidity(_bidLower, _bidUpper, bidLiquidity);
(limitLower, limitUpper) = (_bidLower, _bidUpper);
} else {
_mintLiquidity(_askLower, _askUpper, askLiquidity);
(limitLower, limitUpper) = (_askLower, _askUpper);
}
}
function _checkRange(int24 tickLower, int24 tickUpper) internal view {
int24 _tickSpacing = tickSpacing;
require(tickLower < tickUpper, "tickLower < tickUpper");
require(tickLower >= TickMath.MIN_TICK, "tickLower too low");
require(tickUpper <= TickMath.MAX_TICK, "tickUpper too high");
require(tickLower % _tickSpacing == 0, "tickLower % tickSpacing");
require(tickUpper % _tickSpacing == 0, "tickUpper % tickSpacing");
}
/// @dev Withdraws liquidity from a range and collects all fees in the
/// process.
function _burnAndCollect(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
)
internal
returns (
uint256 burned0,
uint256 burned1,
uint256 feesToVault0,
uint256 feesToVault1
)
{
if (liquidity > 0) {
(burned0, burned1) = pool.burn(tickLower, tickUpper, liquidity);
}
// Collect all owed tokens including earned fees
(uint256 collect0, uint256 collect1) =
pool.collect(
address(this),
tickLower,
tickUpper,
type(uint128).max,
type(uint128).max
);
feesToVault0 = collect0.sub(burned0);
feesToVault1 = collect1.sub(burned1);
uint256 feesToProtocol0;
uint256 feesToProtocol1;
// Update accrued protocol fees
uint256 _protocolFee = protocolFee;
if (_protocolFee > 0) {
feesToProtocol0 = feesToVault0.mul(_protocolFee).div(1e6);
feesToProtocol1 = feesToVault1.mul(_protocolFee).div(1e6);
feesToVault0 = feesToVault0.sub(feesToProtocol0);
feesToVault1 = feesToVault1.sub(feesToProtocol1);
accruedProtocolFees0 = accruedProtocolFees0.add(feesToProtocol0);
accruedProtocolFees1 = accruedProtocolFees1.add(feesToProtocol1);
}
emit CollectFees(feesToVault0, feesToVault1, feesToProtocol0, feesToProtocol1);
}
/// @dev Deposits liquidity in a range on the Uniswap pool.
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal {
if (liquidity > 0) {
pool.mint(address(this), tickLower, tickUpper, liquidity, "");
}
}
/**
* @notice Calculates the vault's total holdings of token0 and token1 - in
* other words, how much of each token the vault would hold if it withdrew
* all its liquidity from Uniswap.
*/
function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) {
(uint256 baseAmount0, uint256 baseAmount1) = getPositionAmounts(baseLower, baseUpper);
(uint256 limitAmount0, uint256 limitAmount1) = getPositionAmounts(limitLower, limitUpper);
total0 = getBalance0().add(baseAmount0).add(limitAmount0);
total1 = getBalance1().add(baseAmount1).add(limitAmount1);
}
/**
* @notice Amounts of token0 and token1 held in vault's position. Includes
* owed fees but excludes the proportion of fees that will be paid to the
* protocol. Doesn't include fees accrued since last poke.
*/
function getPositionAmounts(int24 tickLower, int24 tickUpper)
public
view
returns (uint256 amount0, uint256 amount1)
{
(uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) = _position(tickLower, tickUpper);
(amount0, amount1) = _amountsForLiquidity(tickLower, tickUpper, liquidity);
// Subtract protocol fees
uint256 oneMinusFee = uint256(1e6).sub(protocolFee);
amount0 = amount0.add(uint256(tokensOwed0).mul(oneMinusFee).div(1e6));
amount1 = amount1.add(uint256(tokensOwed1).mul(oneMinusFee).div(1e6));
}
/**
* @notice Balance of token0 in vault not used in any position.
*/
function getBalance0() public view returns (uint256) {
return token0.balanceOf(address(this)).sub(accruedProtocolFees0);
}
/**
* @notice Balance of token1 in vault not used in any position.
*/
function getBalance1() public view returns (uint256) {
return token1.balanceOf(address(this)).sub(accruedProtocolFees1);
}
/// @dev Wrapper around `IUniswapV3Pool.positions()`.
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (
uint128,
uint256,
uint256,
uint128,
uint128
)
{
bytes32 positionKey = PositionKey.compute(address(this), tickLower, tickUpper);
return pool.positions(positionKey);
}
/// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`.
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`.
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
) internal view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
/// @dev Casts uint256 to uint128 with overflow check.
function _toUint128(uint256 x) internal pure returns (uint128) {
assert(x <= type(uint128).max);
return uint128(x);
}
/// @dev Callback for Uniswap V3 pool.
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata
) external override {
require(msg.sender == address(pool));
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
}
/// @dev Callback for Uniswap V3 pool.
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata
) external override {
require(msg.sender == address(pool));
if (amount0Delta > 0) token0.safeTransfer(msg.sender, uint256(amount0Delta));
if (amount1Delta > 0) token1.safeTransfer(msg.sender, uint256(amount1Delta));
}
/**
* @notice Used to collect accumulated protocol fees.
*/
function collectProtocol(
uint256 amount0,
uint256 amount1,
address to
) external onlyGovernance {
accruedProtocolFees0 = accruedProtocolFees0.sub(amount0);
accruedProtocolFees1 = accruedProtocolFees1.sub(amount1);
if (amount0 > 0) token0.safeTransfer(to, amount0);
if (amount1 > 0) token1.safeTransfer(to, amount1);
}
/**
* @notice Removes tokens accidentally sent to this vault.
*/
function sweep(
IERC20 token,
uint256 amount,
address to
) external onlyGovernance {
require(token != token0 && token != token1, "token");
token.safeTransfer(to, amount);
}
/**
* @notice Used to set the strategy contract that determines the position
* ranges and calls rebalance(). Must be called after this vault is
* deployed.
*/
function setStrategy(address _strategy) external onlyGovernance {
strategy = _strategy;
}
/**
* @notice Used to change the protocol fee charged on pool fees earned from
* Uniswap, expressed as multiple of 1e-6.
*/
function setProtocolFee(uint256 _protocolFee) external onlyGovernance {
require(_protocolFee < 1e6, "protocolFee");
protocolFee = _protocolFee;
}
/**
* @notice Used to change deposit cap for a guarded launch or to ensure
* vault doesn't grow too large relative to the pool. Cap is on total
* supply rather than amounts of token0 and token1 as those amounts
* fluctuate naturally over time.
*/
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyGovernance {
maxTotalSupply = _maxTotalSupply;
}
/**
* @notice Removes liquidity in case of emergency.
*/
function emergencyBurn(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) external onlyGovernance {
pool.burn(tickLower, tickUpper, liquidity);
pool.collect(address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max);
}
/**
* @notice Governance address is not updated until the new governance
* address has called `acceptGovernance()` to accept this responsibility.
*/
function setGovernance(address _governance) external onlyGovernance {
pendingGovernance = _governance;
}
/**
* @notice `setGovernance()` should be called by the existing governance
* address prior to calling this function.
*/
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "pendingGovernance");
governance = msg.sender;
}
modifier onlyGovernance {
require(msg.sender == governance, "governance");
_;
}
}
// File: PassiveStrategy.sol
/**
* @title Passive Strategy
* @notice Rebalancing strategy for Exist Vault that maintains the two
* following range orders:
*
* 1. Base order is placed between X - B and X + B + TS.
* 2. Limit order is placed between X - L and X, or between X + TS
* and X + L + TS, depending on which token it holds more of.
*
* where:
*
* X = current tick rounded down to multiple of tick spacing
* TS = tick spacing
* B = base threshold
* L = limit threshold
*
* Note that after these two orders, the vault should have deposited
* all its tokens and should only have a few wei left.
*
* Because the limit order tries to sell whichever token the vault
* holds more of, the vault's holdings will have a tendency to get
* closer to a 1:1 balance. This enables it to continue providing
* liquidity without running out of inventory of either token, and
* achieves this without the need to swap directly on Uniswap and pay
* fees.
*/
contract PassiveStrategy {
using SafeMath for uint256;
ExistVault public vault;
IUniswapV3Pool public pool;
bool setup = false;
int24 public tickSpacing;
int24 public baseThreshold;
int24 public limitThreshold;
uint256 public period;
int24 public minTickMove;
int24 public maxTwapDeviation;
uint32 public twapDuration;
address public keeper;
address public governance;
uint256 public lastTimestamp;
int24 public lastTick;
/**
*/
constructor(
) {
keeper = msg.sender;
governance = msg.sender;
}
function setupContract(
//launch vault first set to address of new contract
address _vault,
uint256 _period,
uint32 _twapDuration
) public onlyGovernance returns(bool success){
if(setup != true){
setup = true;
IUniswapV3Pool _pool = ExistVault(_vault).pool();
int24 _tickSpacing = _pool.tickSpacing();
vault = ExistVault(_vault);
pool = _pool;
tickSpacing = _tickSpacing;
period = _period;
twapDuration = _twapDuration;
(, lastTick, , , , , ) = _pool.slot0();
success = true;
} else {
success = false;
}
}
/**
* @notice Calculates new ranges for orders and calls `vault.rebalance()`
* so that vault can update its positions. Can only be called by keeper.
*/
function rebalance() external {
require(msg.sender == keeper, "can only be called by keeper");
require(block.timestamp >= lastTimestamp.add(period), "not enough time has passed");
(, int24 tick, , , , , ) = pool.slot0();
int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick;
require(tickMove >= minTickMove, "price has not moved enough");
int24 twap = getTwap();
int24 twapDeviation = tick > twap ? tick - twap : twap - tick;
require(twapDeviation <= maxTwapDeviation, "price deviates from twap too much");
int24 _baseThreshold = baseThreshold;
int24 _limitThreshold = limitThreshold;
int24 maxThreshold =
_baseThreshold > _limitThreshold ? _baseThreshold : _limitThreshold;
require(tick >= TickMath.MIN_TICK + maxThreshold + tickSpacing, "price too low");
require(tick <= TickMath.MAX_TICK - maxThreshold - tickSpacing, "price too high");
int24 tickFloor = _floor(tick);
int24 tickCeil = tickFloor + tickSpacing;
vault.rebalance(
0,
0,
tickFloor - _baseThreshold,
tickCeil + _baseThreshold,
tickFloor - _limitThreshold,
tickFloor,
tickCeil,
tickCeil + _limitThreshold
);
lastTimestamp = block.timestamp;
lastTick = tick;
}
/// @dev Fetches time-weighted average price in ticks from Uniswap pool.
function getTwap() public view returns (int24) {
uint32 _twapDuration = twapDuration;
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = _twapDuration;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);
return int24((tickCumulatives[1] - tickCumulatives[0]) / int56(int32(_twapDuration)));
}
/// @dev Rounds tick down towards negative infinity so that it's a multiple
/// of `tickSpacing`.
function _floor(int24 tick) internal view returns (int24) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--;
return compressed * tickSpacing;
}
function _checkThreshold(int24 threshold, int24 _tickSpacing) internal pure {
require(threshold > 0, "threshold must be > 0");
require(threshold <= TickMath.MAX_TICK, "threshold too high");
require(threshold % _tickSpacing == 0, "threshold must be multiple of tickSpacing");
}
function setKeeper(address _keeper) external onlyGovernance {
keeper = _keeper;
}
function setBaseThreshold() external onlyGovernance returns(int24 baseThreshold_){
uint32[] memory secondsAgo;
secondsAgo[0] = 360;
secondsAgo[1] = 0;
(int56[] memory wap,) = pool.observe(secondsAgo);
if(wap[0] >= wap[1]){
int24 thresh = int24((wap[0] - wap[1]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//10% stop loss orders
baseThreshold = thresh - (thresh / 10);
} else if(wap[1] >= wap[0]){
int24 thresh = int24((wap[1] - wap[0]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//10% stop loss orders
baseThreshold = thresh - (thresh / 10);
}
_checkThreshold(baseThreshold, tickSpacing);
baseThreshold_ = baseThreshold;
}
function setLimitThreshold() external onlyGovernance returns(int24 limitThreshold_){
uint32[] memory secondsAgo;
secondsAgo[0] = 360;
secondsAgo[1] = 0;
(int56[] memory wap,) = pool.observe(secondsAgo);
if(wap[0] >= wap[1]){
int24 thresh = int24((wap[0] - wap[1]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//25% take profit order
limitThreshold = thresh + (thresh / 5);
} else if(wap[1] >= wap[0]){
int24 thresh = int24((wap[1] - wap[0]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//25% take profit order
limitThreshold = thresh + (thresh / 5);
}
_checkThreshold(limitThreshold, tickSpacing);
limitThreshold_ = limitThreshold;
}
function setPeriod(uint256 _period) external onlyGovernance {
//set to 360
period = _period;
}
function setMinTickMove() external onlyGovernance returns(int24 minTickMove_){
uint32[] memory secondsAgo;
secondsAgo[0] = 360;
secondsAgo[1] = 0;
(int56[] memory wap,) = pool.observe(secondsAgo);
if(wap[0] >= wap[1]){
int24 thresh = int24((wap[0] - wap[1]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//1% rebalance move
minTickMove = thresh / 100;
} else if(wap[1] >= wap[0]){
int24 thresh = int24((wap[1] - wap[0]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//1% rebalance move
minTickMove = thresh / 100;
}
require(minTickMove >= 0, "minTickMove must be >= 0");
minTickMove_ = minTickMove;
}
function setMaxTwapDeviation() external onlyGovernance returns(int24 maxTwapDeviation_){
uint32[] memory secondsAgo;
secondsAgo[0] = 360;
secondsAgo[1] = 0;
(int56[] memory wap,) = pool.observe(secondsAgo);
if(wap[0] >= wap[1]){
int24 thresh = int24((wap[0] - wap[1]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//.5% twap deviation aloud
maxTwapDeviation = thresh + (thresh / 5);
} else if(wap[1] >= wap[0]){
int24 thresh = int24((wap[1] - wap[0]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//.5% twap deviation aloud
maxTwapDeviation = thresh / 100;
}
require(maxTwapDeviation >= 0, "maxTwapDeviation must be >= 0");
maxTwapDeviation_ = maxTwapDeviation;
}
function setTwapDuration(uint32 _twapDuration) external onlyGovernance {
//set it to 360
require(_twapDuration > 0, "twapDuration must be > 0");
twapDuration = _twapDuration;
}
/// @dev Uses same governance as underlying vault.
modifier onlyGovernance {
require(msg.sender == governance, "governance");
_;
}
}
|
Callback for Uniswap V3 pool.
|
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata
) external override {
require(msg.sender == address(pool));
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
}
| 310,251
|
./full_match/40/0xec9F819e92Af91Fd21a1b0242E240F09D06c4938/sources/contracts/protocol/lendingpool/LendingPool.sol
|
Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. - Users can be rebalanced if the following conditions are satisfied: 1. Usage ratio is above 95% 2. the current deposit APY is below REBALANCE_UP_THRESHOLD maxVariableBorrowRate, which means that too much has been borrowed at a stable rate and depositors are not earning enough asset The address of the underlying asset borrowed user The address of the user to be rebalanced/
|
function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused {
DataTypes.ReserveData storage reserve = _reserves[asset];
IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress);
IERC20 variableDebtToken = IERC20(reserve.variableDebtTokenAddress);
address oTokenAddress = reserve.oTokenAddress;
uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user);
ValidationLogic.validateRebalanceStableBorrowRate(
reserve,
asset,
stableDebtToken,
variableDebtToken,
oTokenAddress
);
reserve.updateState();
IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt);
IStableDebtToken(address(stableDebtToken)).mint(
user,
user,
stableDebt,
reserve.currentStableBorrowRate
);
reserve.updateInterestRates(asset, oTokenAddress, 0, 0);
emit RebalanceStableBorrowRate(asset, user);
}
| 9,552,804
|
./full_match/1/0x8E422E9964881746A68fFa0f6A6163C0100F3037/sources/contracts/global-extensions/GlobalStreamingFeeSplitExtension.sol
|
ONLY OWNER: Initializes StreamingFeeSplitExtension to the DelegatedManager and StreamingFeeModule to the SetToken _delegatedManager Instance of the DelegatedManager to initialize _settings FeeState struct defining fee parameters for StreamingFeeModule initialization/
|
function initializeModuleAndExtension(
IDelegatedManager _delegatedManager,
IStreamingFeeModule.FeeState memory _settings
)
external
onlyOwnerAndValidManager(_delegatedManager)
{
require(_delegatedManager.isPendingExtension(address(this)), "Extension must be pending");
ISetToken setToken = _delegatedManager.setToken();
_initializeExtension(setToken, _delegatedManager);
_initializeModule(setToken, _delegatedManager, _settings);
emit StreamingFeeSplitExtensionInitialized(address(setToken), address(_delegatedManager));
}
| 3,033,723
|
./partial_match/1/0xdDff98044bdf3eCEa5C0eC3e25FD19A72F0D1DD1/sources/pool.sol
|
Users claim their rewards to see if they've won or lost. require(block.timestamp >= staker.time + 1 hours, "You need to stake your tokens for a minimum of 1 hour(s), try again soon.");
|
function claimReward() public {
Staker memory staker = stakers[msg.sender];
require(staker.amount > 0, "No tokens staked");
uint256 elapsedTime = (block.timestamp - staker.time);
uint256 reward = staker.amount + (staker.amount * elapsedTime * rewardPercentage) / (1000 * 3600);
uint256 currentRiskChance = getCurrentRiskChance(msg.sender);
if (random() <= currentRiskChance) {
uint256 burnAmount = staker.amount / 5;
uint256 trueBurnAmount = burnAmount / 2;
uint256 treasuryAmount = burnAmount / 2;
IERC20(tokenAddress).transfer(splitAddress, trueBurnAmount);
IERC20(tokenAddress).transfer(treasuryAddress, treasuryAmount);
stakers[msg.sender].amount = 0;
stakers[msg.sender].time = 0;
stakers[msg.sender].losses += 1;
emit Loss(msg.sender, reward, currentRiskChance, burnAmount);
uint256 splitAmount = reward / 20;
uint256 stakerAmount = reward - splitAmount;
IERC20(tokenAddress).transfer(treasuryAddress, splitAmount);
IERC20(tokenAddress).transfer(msg.sender, stakerAmount);
stakers[msg.sender].amount = 0;
stakers[msg.sender].time = 0;
stakers[msg.sender].wins += 1;
emit Win(msg.sender, reward, currentRiskChance);
}
}
| 2,669,249
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "./DVinMembership.sol";
import "./EIP712Whitelisting.sol";
error RoundDisabled(uint256 round);
error InvalidTier(uint256 tier);
error FailedToMint();
error LengthMismatch();
error PurchaseLimitExceeded();
error InsufficientValue();
error RoundLimitExceeded();
error FailedToSendETH();
/// @title DVin Membership Sale
/// @notice Sale contract with authorization to mint tokens on the DVin NFT contract
contract DVinMint is EIP712Whitelisting {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /*Role used to permission admin minting*/
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); /*Role used to permission contract configuration changes*/
address payable public ethSink; /*recipient for ETH*/
mapping(uint256 => address) public tierContracts; /*Contracts for different tier options*/
uint256 public limitPerPurchase; /*Max amount of tokens someone can buy in one transaction*/
/* Track when presales and public sales are allowed */
enum ContractState {
Presale,
Public
}
mapping(ContractState => bool) public contractState; /*Track which state is enabled*/
/* Track prices and limits for sales*/
struct SaleConfig {
uint256 price;
uint256 limit;
}
mapping(uint256 => SaleConfig) public presaleConfig; /*Configuration for presale*/
mapping(uint256 => SaleConfig) public publicConfig; /*Configuration for public sale*/
/// @notice Constructor configures sale parameters
/// @dev Sets external contract addresses, sets up roles
/// @param _tiers Token types
/// @param _addresses Token addresses
/// @param _sink Address to send sale ETH to
constructor(
uint256[] memory _tiers,
address[] memory _addresses,
address payable _sink
) EIP712Whitelisting("DVin") {
_setupRole(MINTER_ROLE, msg.sender); /*Grant role to deployer for admin minting*/
_setupRole(OWNER_ROLE, msg.sender); /*Grant role to deployer for config changes*/
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender); /*Grant role to deployer for access control changes*/
ethSink = _sink; /*Set address to send ETH to*/
setTierContracts(_tiers, _addresses); /*Set contracts to use for types*/
}
/*****************
EXTERNAL MINTING FUNCTIONS
*****************/
/// @notice Mint tokens by authorized address - useful for people buying with CC
/// @param _tier Which token type to purchase
/// @param _dst Where to send tokens
/// @param _qty Quantity to send
function mintTierAdmin(
uint256 _tier,
address _dst,
uint256 _qty
) public onlyRole(MINTER_ROLE) {
if (tierContracts[_tier] == address(0)) revert InvalidTier(_tier); /*Ensure tier contract is populated*/
if (!DVin(tierContracts[_tier]).mint(_dst, _qty)) revert FailedToMint(); /*Mint token by admin to specified address*/
}
function mintTierAdminBatch(
uint256[] calldata _tiers,
address[] calldata _dsts,
uint256[] calldata _qtys
) public onlyRole(MINTER_ROLE) {
if (_tiers.length != _dsts.length || _dsts.length != _qtys.length)
revert LengthMismatch();
for (uint256 index = 0; index < _tiers.length; index++) {
mintTierAdmin(_tiers[index], _dsts[index], _qtys[index]);
}
}
/// @notice Mint presale by qualified address.
/// @dev Presale state must be enabled
/// @param _tier Which token type to purchase
/// @param _qty How many tokens to buy
/// @param _nonce Whitelist signature nonce
/// @param _signature Whitelist signature
function purchaseTokenPresale(
uint256 _tier,
uint256 _qty,
uint256 _nonce,
bytes calldata _signature
) external payable requiresWhitelist(_signature, _nonce) {
if (!contractState[ContractState.Presale])
revert RoundDisabled(uint256(ContractState.Presale)); /*Presale must be enabled*/
if (presaleConfig[_tier].price == 0) revert InvalidTier(_tier); /*Do not allow 0 value purchase. If desired use separate function for free claim*/
SaleConfig memory _config = presaleConfig[_tier]; /*Fetch sale config*/
_purchase(_tier, _qty, _config.price, _config.limit); /*Purchase token if all values & limits are valid*/
}
/// @notice Mint presale by anyone
/// @dev Public sale must be enabled
/// @param _tier Which token type to purchase
/// @param _qty How many tokens to buy
function purchaseTokenOpensale(uint256 _tier, uint256 _qty)
external
payable
{
if (!contractState[ContractState.Public])
revert RoundDisabled(uint256(ContractState.Public)); /*Public must be enabled*/
if (publicConfig[_tier].price == 0) revert InvalidTier(_tier); /*Do not allow 0 value purchase. If desired use separate function for free claim*/
_purchase(
_tier,
_qty,
publicConfig[_tier].price,
publicConfig[_tier].limit
); /*Purchase token if all values & limits are valid*/
}
/*****************
INTERNAL MINTING FUNCTIONS AND HELPERS
*****************/
/// @notice Mint tokens and transfer eth to sink
/// @dev Validations:
/// - Msg value is checked in comparison to price and quantity
/// @param _tier Token type to mint
/// @param _qty How many tokens to mint
/// @param _price Price per token
/// @param _limit Max token ID
function _purchase(
uint256 _tier,
uint256 _qty,
uint256 _price,
uint256 _limit
) internal {
if (_qty > limitPerPurchase) revert PurchaseLimitExceeded();
if (msg.value < (_price * _qty)) revert InsufficientValue();
if ((DVin(tierContracts[_tier]).totalSupply() + _qty) > _limit)
revert RoundLimitExceeded();
(bool _success, ) = ethSink.call{value: msg.value}(""); /*Send ETH to sink first*/
if (!_success) revert FailedToSendETH();
if (!DVin(tierContracts[_tier]).mint(msg.sender, _qty))
revert FailedToMint(); /*Mint token by admin to specified address*/
}
/*****************
CONFIG FUNCTIONS
*****************/
/// @notice Set states enabled or disabled as owner
/// @param _state 0: presale, 1: public sale
/// @param _enabled specified state on or off
function setContractState(ContractState _state, bool _enabled)
external
onlyRole(OWNER_ROLE)
{
contractState[_state] = _enabled;
}
/// @notice Set sale proceeds address
/// @param _sink new sink
function setSink(address payable _sink) external onlyRole(OWNER_ROLE) {
ethSink = _sink;
}
/// @notice Set new contracts for types
/// @param _tiers Token types like 1,2
/// @param _addresses Addresses of token contracts
function setTierContracts(
uint256[] memory _tiers,
address[] memory _addresses
) public onlyRole(OWNER_ROLE) {
if (_tiers.length != _addresses.length) revert LengthMismatch();
for (uint256 index = 0; index < _tiers.length; index++) {
tierContracts[_tiers[index]] = _addresses[index];
}
}
/// @notice Set token limits for this sale
/// @param _tier Token type to set
/// @param _presaleLimit Max tokens of this type to sell during presale
/// @param _publicLimit Max tokens of this type to sell during public
function setLimit(
uint256 _tier,
uint256 _presaleLimit,
uint256 _publicLimit
) external onlyRole(OWNER_ROLE) {
presaleConfig[_tier].limit = _presaleLimit;
publicConfig[_tier].limit = _publicLimit;
}
/// @notice Set token limits for this sale
/// @param _tier Token type to set
/// @param _presalePrice Price at which to sell this type during presale
/// @param _opensalePrice Price at which to sell this type during public sale
function setPrice(
uint256 _tier,
uint256 _presalePrice,
uint256 _opensalePrice
) external onlyRole(OWNER_ROLE) {
presaleConfig[_tier].price = _presalePrice;
publicConfig[_tier].price = _opensalePrice;
}
/// @notice Set token limits per purchase
/// @param _limit Max tokens someone can buy at once
function setLimitPerPurchase(uint256 _limit) external onlyRole(OWNER_ROLE) {
limitPerPurchase = _limit;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./EIP712Base.sol";
import "./erc721a/extensions/ERC721ABurnable.sol";
contract CloneFactory {
// implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone, 0x14), targetBytes)
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
result := create(0, clone, 0x37)
}
}
}
error CallerIsNotMinter();
error MaxSupplyExceeded();
error NonceTooLow();
error RecoveredUnauthorizedAddress();
error DeadlineExpired();
error TransfersDisabled();
/// @title DVin Membership NFT
/// @notice NFT contract with upgradeable sale contract and signature based transfers
contract DVin is ERC721ABurnable, Ownable, EIP712Base, Initializable {
using Strings for uint256; /*String library allows for token URI concatenation*/
using ECDSA for bytes32; /*ECDSA library allows for signature recovery*/
bool public tradingEnabled; /*Trading can be disabled by owner*/
string public contractURI; /*contractURI contract metadata json*/
string public baseURI; /*baseURI_ String to prepend to token IDs*/
string private _name; /*Token name override*/
string private _symbol; /*Token symbol override*/
uint256 public maxSupply;
address public minter; /*Contract that can mint tokens, changeable by owner*/
mapping(address => uint256) public nonces; /*maps record of states for signing & validating signatures
Nonces increment each time a permit is used.
Users can invalidate a previously signed permit by changing their account nonce
*/
/*EIP712 typehash for permit to allow spender to send a specific token ID*/
bytes32 constant PERMIT_TYPEHASH =
keccak256(
"Permit(address owner,address spender,uint256 tokenId,uint256 nonce,uint256 deadline)"
);
/*EIP712 typehash for permit to allow spender to send a specific token ID*/
bytes32 constant UNIVERSAL_PERMIT_TYPEHASH =
keccak256(
"Permit(address owner,address spender,uint256 nonce,uint256 deadline)"
);
/// @notice constructor configures template contract metadata
constructor() ERC721A("TEMPLATE", "DEAD") initializer {
_transferOwnership(address(0xdead)); /*Disable template*/
}
/// @notice setup configures interfaces and production metadata
/// @param name_ Token name
/// @param symbol_ Token symbol
/// @param _contractURI Metadata location for contract
/// @param baseURI_ Metadata location for tokens
/// @param _minter Authorized address to mint
/// @param _maxSupply Max supply for this token
function setUp(
string memory name_,
string memory symbol_,
string memory _contractURI,
string memory baseURI_,
address _minter,
address _owner,
uint256 _maxSupply
) public initializer {
_name = name_;
_symbol = symbol_;
_setBaseURI(baseURI_); /*Base URI for token ID resolution*/
contractURI = _contractURI; /*Contract URI for marketplace metadata*/
minter = _minter; /*Address authorized to mint */
_currentIndex = _startTokenId();
maxSupply = _maxSupply;
_transferOwnership(_owner);
setUpDomain(name_);
}
function _startTokenId() internal view override(ERC721A) returns (uint256) {
return 1;
}
/*****************
Permissioned Minting
*****************/
/// @dev Mint the token for specified tier by authorized minter contract or EOA
/// @param _dst Recipient
/// @param _qty Number of tokens to send
function mint(address _dst, uint256 _qty) external returns (bool) {
if (msg.sender != minter) revert CallerIsNotMinter(); /*Minting can only be done by minter address*/
if ((totalSupply() + _qty) > maxSupply) revert MaxSupplyExceeded(); /*Cannot exceed max supply*/
_safeMint(_dst, _qty); /*Send token to new recipient*/
return true; /*Return success to external caller*/
}
/*****************
Permit & Guardian tools
*****************/
/// @notice Manually update nonce to invalidate previously signed permits
/// @dev New nonce must be higher than current to prevent replay
/// @param _nonce New nonce
function setNonce(uint256 _nonce) external {
if (_nonce <= nonces[msg.sender]) revert NonceTooLow(); /*New nonce must be higher to prevent replay*/
nonces[msg.sender] = _nonce; /*Set new nonce for sender*/
}
/// @notice Transfer token on behalf of owner using signed authorization
/// Useful to help people authorize a guardian to rescue tokens if access is lost
/// @dev Signature can be either per token ID or universal
/// @param _owner Current owner of token
/// @param _tokenId Token ID to transfer
/// @param _dst New recipient
/// @param _deadline Date the permit must be used by
/// @param _signature Concatenated RSV of sig
function transferWithUniversalPermit(
address _owner,
uint256 _tokenId,
address _dst,
uint256 _deadline,
bytes calldata _signature
) external {
bytes32 structHash = keccak256(
abi.encode(
UNIVERSAL_PERMIT_TYPEHASH,
_owner,
msg.sender,
nonces[_owner]++, /*Increment nonce to prevent replay*/
_deadline
)
); /*calculate EIP-712 struct hash*/
bytes32 digest = toTypedMessageHash(structHash); /*Calculate EIP712 digest*/
address recoveredAddress = digest.recover(_signature); /*Attempt to recover signer*/
if (recoveredAddress != _owner) revert RecoveredUnauthorizedAddress(); /*check signer is `owner`*/
if (block.timestamp > _deadline) revert DeadlineExpired(); /*check signature is not expired*/
_approve(msg.sender, _tokenId, _owner);
safeTransferFrom(_owner, _dst, _tokenId); /*Move token to new wallet*/
}
/// @notice Transfer token on behalf of owner using signed authorization
/// Useful to help people authorize a guardian to rescue tokens if access is lost
/// @dev Signature can be either per token ID or universal
/// @param _owner Current owner of token
/// @param _tokenId Token ID to transfer
/// @param _dst New recipient
/// @param _deadline Date the permit must be used by
/// @param _signature Concatenated RSV of sig
function transferWithPermit(
address _owner,
uint256 _tokenId,
address _dst,
uint256 _deadline,
bytes calldata _signature
) external {
bytes32 structHash = keccak256(
abi.encode(
PERMIT_TYPEHASH,
_owner,
msg.sender,
_tokenId,
nonces[_owner]++, /*Increment nonce to prevent replay*/
_deadline
)
); /*calculate EIP-712 struct hash*/
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash)
); /*calculate EIP-712 digest for signature*/
address recoveredAddress = digest.recover(_signature); /*Attempt to recover signer*/
if (recoveredAddress != _owner) revert RecoveredUnauthorizedAddress(); /*check signer is `owner`*/
if (block.timestamp > _deadline) revert DeadlineExpired(); /*check signature is not expired*/
_approve(msg.sender, _tokenId, _owner);
safeTransferFrom(_owner, _dst, _tokenId); /*Move token to new wallet*/
}
/*****************
CONFIG FUNCTIONS
*****************/
/// @notice Set new base URI for token IDs
/// @param baseURI_ String to prepend to token IDs
function setBaseURI(string memory baseURI_) external onlyOwner {
_setBaseURI(baseURI_);
}
/// @notice Enable or disable trading
/// @param _enabled bool to set state on or off
function setTradingState(bool _enabled) external onlyOwner {
tradingEnabled = _enabled;
}
/// @notice Set minting contract
/// @param _minter new minting contract
function setMinter(address _minter) external onlyOwner {
minter = _minter;
}
/// @notice internal helper to update token URI
/// @param baseURI_ String to prepend to token IDs
function _setBaseURI(string memory baseURI_) internal {
baseURI = baseURI_;
}
/// @notice Set new contract URI
/// @param _contractURI Contract metadata json
function setContractURI(string memory _contractURI) external onlyOwner {
contractURI = _contractURI;
}
/*****************
Public interfaces
*****************/
function name() public view override returns (string memory) {
return _name;
}
function symbol() public view override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString(), ".json"))
: "";
}
///@dev Support interfaces for Access Control and ERC721
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721A)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @dev Hook for disabling trading
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal override(ERC721A) {
super._beforeTokenTransfers(from, to, startTokenId, quantity);
if (from != address(0) && to != address(0) && !tradingEnabled)
revert TransfersDisabled();
}
}
/// @title DVin Membership NFT Summoner
/// @notice Clone factory for new membership tiers
contract DVinSummoner is CloneFactory, Ownable {
address public template; /*Template contract to clone*/
constructor(address _template) public {
template = _template;
}
event SummonComplete(
address indexed newContract,
string name,
string symbol,
address summoner
);
/// @notice Public interface for owner to create new membership tiers
/// @param name_ Token name
/// @param symbol_ Token symbol
/// @param _contractURI Metadata for contract
/// @param baseURI_ Metadata for tokens
/// @param _minter Authorized minting address
/// @param _maxSupply Max amount of this token that can be minted
/// @param _owner Owner address of new contract
function summonDvin(
string memory name_,
string memory symbol_,
string memory _contractURI,
string memory baseURI_,
address _minter,
uint256 _maxSupply,
address _owner
) external onlyOwner returns (address) {
DVin dvin = DVin(createClone(template)); /*Create a new clone of the template*/
/*Set up the external interfaces*/
dvin.setUp(
name_,
symbol_,
_contractURI,
baseURI_,
_minter,
_owner,
_maxSupply
);
emit SummonComplete(address(dvin), name_, symbol_, msg.sender);
return address(dvin);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./EIP712Base.sol";
contract EIP712Whitelisting is AccessControl, EIP712Base {
using ECDSA for bytes32;
bytes32 public constant WHITELISTING_ROLE = keccak256("WHITELISTING_ROLE");
mapping(bytes32 => bool) public signatureUsed;
// The typehash for the data type specified in the structured data
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#rationale-for-typehash
// This should match whats in the client side whitelist signing code
// https://github.com/msfeldstein/EIP712-whitelisting/blob/main/test/signWhitelist.ts#L22
bytes32 public constant MINTER_TYPEHASH =
keccak256("Minter(address wallet,uint256 nonce)");
constructor(string memory name) {
setUpDomain(name);
_setupRole(WHITELISTING_ROLE, msg.sender);
}
modifier requiresWhitelist(
bytes calldata signature,
uint256 nonce
) {
// Verify EIP-712 signature by recreating the data structure
// that we signed on the client side, and then using that to recover
// the address that signed the signature for this data.
bytes32 structHash = keccak256(
abi.encode(MINTER_TYPEHASH, msg.sender, nonce)
);
bytes32 digest = toTypedMessageHash(structHash); /*Calculate EIP712 digest*/
require(!signatureUsed[digest], "signature used");
signatureUsed[digest] = true;
// Use the recover method to see what address was used to create
// the signature on this data.
// Note that if the digest doesn't exactly match what was signed we'll
// get a random recovered address.
address recoveredAddress = digest.recover(signature);
require(
hasRole(WHITELISTING_ROLE, recoveredAddress),
"Invalid Signature"
);
_;
}
}
// 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 (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !Address.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n รท 2 + 1, and for v in (302): v โ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
pragma solidity 0.8.10;
contract EIP712Base {
bytes32 internal DOMAIN_SEPARATOR;
function setUpDomain(string memory name) internal {
// This should match whats in the client side whitelist signing code
// https://github.com/msfeldstein/EIP712-whitelisting/blob/main/test/signWhitelist.ts#L12
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
// This should match the domain you set in your client side signing.
keccak256(bytes(name)),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, messageHash)
);
}
}
// SPDX-License-Identifier: MIT
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import "../ERC721A.sol";
/**
* @title ERC721A Burnable Token
* @dev ERC721A Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721ABurnable is ERC721A {
/**
* @dev Burns `tokenId`. See {ERC721A-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
_burn(tokenId, true);
}
}
// SPDX-License-Identifier: MIT
// 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
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerQueryForNonexistentToken();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function _ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return
bytes(baseURI).length != 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (
to.isContract() &&
!_checkContractOnERC721Received(from, to, tokenId, _data)
) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return
_startTokenId() <= tokenId &&
tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (
!_checkContractOnERC721Received(
address(0),
to,
updatedIndex++,
_data
)
) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
currSlot.startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev This is equivalent to _burn(tokenId, false)
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
address from = prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
AddressData storage addressData = _addressData[from];
addressData.balance -= 1;
addressData.numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = from;
currSlot.startTimestamp = uint64(block.timestamp);
currSlot.burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) internal {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
|
Transfer token on behalf of owner using signed authorization Useful to help people authorize a guardian to rescue tokens if access is lost Signature can be either per token ID or universal _owner Current owner of token _tokenId Token ID to transfer _dst New recipient _deadline Date the permit must be used by _signature Concatenated RSV of sig
|
function transferWithPermit(
address _owner,
uint256 _tokenId,
address _dst,
uint256 _deadline,
bytes calldata _signature
) external {
bytes32 structHash = keccak256(
abi.encode(
PERMIT_TYPEHASH,
_owner,
msg.sender,
_tokenId,
nonces[_owner]++, /*Increment nonce to prevent replay*/
_deadline
)
); /*calculate EIP-712 struct hash*/
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash)
); /*calculate EIP-712 digest for signature*/
address recoveredAddress = digest.recover(_signature); /*Attempt to recover signer*/
if (recoveredAddress != _owner) revert RecoveredUnauthorizedAddress(); /*check signer is `owner`*/
if (block.timestamp > _deadline) revert DeadlineExpired(); /*check signature is not expired*/
_approve(msg.sender, _tokenId, _owner);
safeTransferFrom(_owner, _dst, _tokenId); /*Move token to new wallet*/
}
| 10,009,024
|
pragma solidity ^0.4.25;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./FlightSuretyData.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
FlightSuretyData private flightSuretyData;
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor
(
address dataContract
)
public
{
contractOwner = msg.sender;
require(dataContract != address(0), 'dataContract is empty');
flightSuretyData = FlightSuretyData(dataContract);
fundFeePerAirline = flightSuretyData.FUND_FEE_AIRLINE();
require(fundFeePerAirline >= (1 ether), 'please increase the airline fund');
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// region modifier
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(isOperational(), "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "registered airline" account to be the function caller
*/
modifier requireRegisteredAirline()
{
require(flightSuretyData.isRegisteredAirline(msg.sender), "Caller is not registered airline");
_;
}
/**
* @dev Modifier that requires the "registered and funded airline" account to be the function caller
*/
modifier requireFundedAirline()
{
require(flightSuretyData.isFundedAirline(msg.sender), "Caller airline is not registered or not funded");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational()
public
view
returns(bool)
{
bool dataContractIsOperational = flightSuretyData.isOperational();
return dataContractIsOperational; // Modify to call data contract's status
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
// endregion
// region AIRLINE MANAGEMENT
/*****************************************************************
* the following variales are airline related
****************************************************************/
uint8 public constant MP_AIRLINE_COUNT = 4; // the 5th airline need to be approved by 50+ existing airline
uint8 public constant MP_AIRLINE_APPROVE_PERCENT = 50; // need 50% of the existing airlines to approve
// 0: unknown, 1: agree, 2: disagree, (others we don't care for now.)
uint8 public constant MP_AIRLINE_APPROVE_CODE_AGREE = 1;
uint256 public fundFeePerAirline; // Fee to be paid to make one airline effective/funded
// struct to store the multi-party consensus request info
struct ApproveResponse {
address stakeholder; // the airline who send the approval response
uint8 code; // the code that the approval airline send out
}
struct AirlineRequest {
bool isOpen; // the request is still valid
address airline; // the airline to be approved
string name; // name of the airline
uint256 time; // blockhash time of the new airline request
ApproveResponse[] approvalResult; // the result of the approvals, use uint8 for future reasonCode extension
}
AirlineRequest private airlineRequest; // the need-approval airline (to simply the case, only 1 airline is allowed to wait here)
event AirlineApproveRequest(address airline, address registrant, string name); // the event to request other airlines to approve a new airline
event AirlineApproveResponse(address airline, address approval, uint code); // the event to tell one airlines has approved a new airline
event AirlineRegistered(address airline, address registrant, string name); // the event to tell a new airline has been registered
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline
(
address airline,
string name
)
external
requireIsOperational
requireFundedAirline
returns(bool success, uint256 votes)
{
require(airline != address(0), 'bad airline address');
require(bytes(name).length > 0, 'airline name is empty');
require(!flightSuretyData.isRegisteredAirline(airline), 'the airline is already registered');
uint count = flightSuretyData.countOfAirlines();
if (count < MP_AIRLINE_COUNT) {
success = flightSuretyData.registerAirline(airline, name);
votes = 1;
if (success) {
emit AirlineRegistered(airline, msg.sender, name);
}
} else {
require(!airlineRequest.isOpen, 'Another airline is waiting for approval, please wait');
// add it into the request list
airlineRequest.isOpen = true;
airlineRequest.airline = airline;
airlineRequest.name = name;
airlineRequest.time = now;
airlineRequest.approvalResult.length = 0; // clear existing votes, if any
airlineRequest.approvalResult.push(ApproveResponse({
stakeholder: msg.sender,
code: MP_AIRLINE_APPROVE_CODE_AGREE
}));
votes = 1;
success = false;
// notify the other existing airlines to approve
emit AirlineApproveRequest(airline, msg.sender, name);
}
return (success, votes);
}
/**
* @dev Add an airline to the registration queue
*
* param(code): 0: unknown, 1: agree, 2: disagree, (others we don't care for now.)
*/
function approveAirline
(
address airline,
uint8 code
)
external
requireIsOperational
requireFundedAirline
returns(bool success, uint256 votes)
{
require(!flightSuretyData.isRegisteredAirline(airline), 'the airline is already registered');
require(airlineRequest.isOpen && (airlineRequest.airline == airline), 'the airline is not in the waiting list');
// 1. check status
uint voteSameCode = 1; // the caller itself counts
ApproveResponse[] storage responses = airlineRequest.approvalResult;
for (uint i=0; i<responses.length; i++) {
// check if the msg.sender has alread voted before
require(responses[i].stakeholder != msg.sender, "Caller has already approved.");
// check current response list for its status
if (responses[i].code == code) {
voteSameCode ++;
}
}
success = false;
votes = responses.length + 1;
// 2. add the vote response of the approval airline
// store the response data, as the approval history
airlineRequest.approvalResult.push(ApproveResponse({
stakeholder: msg.sender,
code: code
}));
emit AirlineApproveResponse(airline, msg.sender, code);
// 3. check if we already have a consensus
uint countOfAirlines = flightSuretyData.countOfAirlines();
uint percent = voteSameCode.mul(100).div(countOfAirlines);
if (percent >= MP_AIRLINE_APPROVE_PERCENT) {
// if the consensus is "agree", add it to the registered airline list
if (code == MP_AIRLINE_APPROVE_CODE_AGREE) {
success = flightSuretyData.registerAirline(airline, airlineRequest.name);
if (success) {
// for multi-party consensus, we use the first element first and fall back to use msg.sender if not present
address registrant = airlineRequest.approvalResult[0].stakeholder;
emit AirlineRegistered(airline, registrant, airlineRequest.name);
}
}
// close the vote, as we already have a consensus
airlineRequest.isOpen = false;
airlineRequest.airline = address(0);
airlineRequest.name = '';
airlineRequest.time = 0;
airlineRequest.approvalResult.length = 0; // clear existing votes, if any
}
return (success, votes);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
* Can only be called from FlightSuretyApp contract
*/
function fundAirline
(
address airline
)
external
payable
requireIsOperational
requireRegisteredAirline
{
require(airline != address(0), 'invalid airline');
require(msg.value >= fundFeePerAirline, 'Not paied enough to fund the airline');
flightSuretyData.fundAirline.value(msg.value)(airline);
}
/**
* @dev Get the Information of one particular airline
*/
function getAirlinePendingRequest
(
)
external
view
requireIsOperational
returns(uint8 count, address airline, string name, uint256 votes, uint256 agree)
{
if (airlineRequest.isOpen) {
votes = airlineRequest.approvalResult.length;
agree = 0;
for (uint i=0; i<votes; i++) {
if (airlineRequest.approvalResult[i].code == MP_AIRLINE_APPROVE_CODE_AGREE) {
agree ++;
}
}
return (1, airlineRequest.airline, airlineRequest.name, votes, agree);
} else {
return (0, address(0), '', 0, 0);
}
}
/**
* @dev Get the Information of one particular airline
*/
function getAirlineInfoByIndex
(
uint32 index
)
external
view
requireIsOperational
returns(address airline, string name, bool isFunded)
{
return flightSuretyData.getAirlineInfoByIndex(index);
}
/**
* @dev Retrieve the count of all airline
*/
function countOfAirlines
(
)
external
view
requireIsOperational
returns(uint32)
{
return flightSuretyData.countOfAirlines();
}
// endregion
// region FLIGHT MANAGEMENT
/*****************************************************************
* the following variales are flight related
****************************************************************/
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; // NOTE: only 20 is interesting in this lesson
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
struct Flight {
bool isOpen;
address airline;
string flight;
uint256 flightTimestamp; // the flight timestamp, specified as the number of seconds since the Unix epoch
uint8 statusCode;
}
mapping(bytes32 => Flight) private flights;
bytes32[] private flightIdArray;
/**
* Utils function to caculate flight key
*/
function _getFlightKey
(
address airline,
string flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight
(
address airline,
string flight,
uint256 flightTimestamp
)
external
requireIsOperational
requireFundedAirline
{
require(flightSuretyData.isRegisteredAirline(airline), 'the airline does not exist');
require(bytes(flight).length > 0, 'no flight info ');
bytes32 flightId = _getFlightKey(airline, flight, flightTimestamp);
require(!flights[flightId].isOpen, 'the flight already exists');
flights[flightId] = Flight({
isOpen: true,
airline: airline,
flight: flight,
flightTimestamp: flightTimestamp,
statusCode: STATUS_CODE_UNKNOWN
});
flightIdArray.push(flightId);
}
/**
* the total count of the active flight
*/
function getFlightCount()
external
view
returns(uint256)
{
return flightIdArray.length;
}
/**
* retrieve info of the index-th active flight
*/
function getFlightInfoByIndex(uint256 index)
external
view
returns(
address airline, string flight, uint256 flightTimestamp, uint8 statusCode)
{
require(index < flightIdArray.length, 'no more flight');
bytes32 flightId = flightIdArray[index];
Flight storage flightInfo = flights[flightId];
require(flightInfo.isOpen, 'the flight is not open to insure');
Flight storage result = flights[flightId];
return (result.airline, result.flight, result.flightTimestamp, result.statusCode);
}
/**
* @dev Called after oracle has updated flight status
*
*/
function _processFlightStatus
(
address airline,
string memory flight,
uint256 timestamp,
uint8 statusCode
)
internal
{
bytes32 flightId = _getFlightKey(airline, flight, timestamp);
require(flights[flightId].isOpen, 'the flight does not exists');
flights[flightId].statusCode = statusCode;
// NOTE: we don't proactively refund the insuree, since the count of insuree probably be very large
// and we will exhaust our gas limit to handle it
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus
(
address airline,
string flight,
uint256 timestamp
)
external
requireIsOperational
{
bytes32 flightId = _getFlightKey(airline, flight, timestamp);
require(flights[flightId].isOpen, 'the flight does not exists');
require(flights[flightId].statusCode == STATUS_CODE_UNKNOWN, 'the flight already has a status');
uint8 index = _getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit OracleRequest(index, airline, flight, timestamp);
}
// endregion
// region Insurance MANAGEMENT
uint256 public constant INSURANCE_FEE_MAX = 1 ether; // Max fee to be paid for one single insurance
event PassengerBuyInsurance(address passenger, address airline, string flight, uint256 timestamp);
event InsurancePaidbackCredit(address passenger, address airline, string flight, uint256 timestamp);
event PassengerWithdraw(address passenger);
// Generate a request for oracles to fetch flight information
function buyInsurance
(
address passenger,
address airline,
string flight,
uint256 timestamp
)
external
payable
requireIsOperational
{
require(passenger != address(0), 'invalid passenger');
require((msg.value > 0) && (msg.value <= INSURANCE_FEE_MAX), 'invalid payment for the flight insurance');
// validate it is a valid flight
bytes32 flightId = _getFlightKey(airline, flight, timestamp);
require(flights[flightId].isOpen, 'the flight does not exists');
// calculate payback money and finish buying the insurance
uint256 insurancePayback = msg.value;
insurancePayback = insurancePayback.mul(3).div(2);
flightSuretyData.buyInsurance.value(msg.value)(passenger, airline, flight, timestamp, insurancePayback);
emit PassengerBuyInsurance(passenger, airline, flight, timestamp);
}
// Generate a request for oracles to fetch flight information
function claimInsurancePayback
(
address passenger,
address airline,
string flight,
uint256 timestamp
)
external
requireIsOperational
{
require(passenger != address(0), 'invalid passenger');
// validate it is a valid flight
bytes32 flightId = _getFlightKey(airline, flight, timestamp);
require(flights[flightId].isOpen, 'the flight does not exists');
// check flight status
require(flights[flightId].statusCode == STATUS_CODE_LATE_AIRLINE, 'flight is not delayed, no pay back');
flightSuretyData.creditInsurees(passenger, airline, flight, timestamp);
emit InsurancePaidbackCredit(passenger, airline, flight, timestamp);
}
/**
* get the passender's current balance
*/
function getPassengerInsurances
(
)
external
view
requireIsOperational
returns (uint8 count, uint256 balance)
{
return flightSuretyData.getPassengerInsurances(msg.sender);
}
/**
* get the passender's insurance info
*/
function getPassengerInsuranceByIndex
(
uint8 index
)
external
view
requireIsOperational
returns (
address airline, string flight, uint256 flightTimestamp,
uint256 insuranceFund, uint256 insurancePayback
)
{
return flightSuretyData.getPassengerInsuranceByIndex(msg.sender, index);
}
// passenger withdraw
function passengerWithdraw
(
uint256 amount
)
external
requireIsOperational
{
require(amount > 0, 'please specify the amount to withdraw');
flightSuretyData.payWithdraw(msg.sender, amount);
emit PassengerWithdraw(msg.sender);
}
// endregion
// region ORACLE MANAGEMENT
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant ORACLE_REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant ORACLE_MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
mapping(address => bool) oracles; // Remember the oracles which has responsed
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
/**
* @dev Modifier that requires the caller is a valid registered oracle
*/
modifier requireIsOracleRegistered()
{
require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
_;
}
// Register an oracle with the contract
function registerOracle
(
)
external
payable
requireIsOperational
{
// Require registration fee
require(msg.value >= ORACLE_REGISTRATION_FEE, 'Registration fee is required');
if (!oracles[msg.sender].isRegistered) {
uint8[3] memory indexes = _generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
}
}
function getMyIndexes
(
)
view
external
requireIsOracleRegistered
returns(uint8[3])
{
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse
(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
)
external
requireIsOperational
requireIsOracleRegistered
{
require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request");
require(!oracleResponses[key].oracles[msg.sender], 'the oracle already responsed before');
// remember the vote result
oracleResponses[key].responses[statusCode].push(msg.sender);
oracleResponses[key].oracles[msg.sender] = true;
// Information isn't considered verified until at least ORACLE_MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
// check the vote result
if (oracleResponses[key].responses[statusCode].length >= ORACLE_MIN_RESPONSES) {
// Handle flight status as appropriate
_processFlightStatus(airline, flight, timestamp, statusCode);
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
}
}
// Returns array of three non-duplicating integers from 0-9
function _generateIndexes
(
address account
)
internal
returns(uint8[3])
{
uint8[3] memory indexes;
indexes[0] = _getRandomIndex(account);
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = _getRandomIndex(account);
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = _getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function _getRandomIndex
(
address account
)
internal
returns (uint8)
{
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// endregion
}
|
Retrieve the count of all airline/
|
function countOfAirlines
(
)
external
view
requireIsOperational
returns(uint32)
{
return flightSuretyData.countOfAirlines();
}
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
| 7,318,166
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.7.6;
contract Planets {
/**
* @dev Returns the orbital elements for the specified planet
* @param _planet Id of the planet
*/
function getElements(uint _planet) public pure returns (uint16[6] memory elements) {
require(_planet >= 1 && _planet <= 5);
if (_planet == 1) {
elements = [ 258, 178, 639, 27693, 4955, 9342 ];
} else if (_planet == 2) {
elements = [ 781, 29, 182, 31965, 7588, 24762 ];
} else if (_planet == 3) {
elements = [ 3912, 13, 28, 33765, 6312, 26301 ];
} else if (_planet == 4) {
elements = [ 7249, 42, 48, 35649, 32961, 17878 ];
} else if (_planet == 5) {
elements = [ 9206, 37, 71, 9248, 25823, 22124 ];
}
return elements;
}
/**
* @dev Returns whether the planet is rocky or a gas giant
* @param _planet The Id of the planet
*/
function getType(uint _planet) public pure returns (uint8) {
require(_planet >= 1 && _planet <= 5);
uint8[5] memory planetTypes = [ 1, 1, 2, 2, 2 ];
return planetTypes[_planet - 1];
}
/**
* @dev Gets the radius of the planet
* @param _planet The Id of the planet
*/
function getRadius(uint _planet) public pure returns (uint32) {
require(_planet >= 1 && _planet <= 5);
uint32[5] memory radii = [ 1937420, 2910672, 69120870, 41059721, 19559342 ];
return radii[_planet - 1];
}
/**
* @dev Returns the elements for the planet that has trojan asteroids
*/
function getPlanetWithTrojanAsteroids() public pure returns (uint16[6] memory) {
return getElements(3);
}
}
|
Returns whether the planet is rocky or a gas giant _planet The Id of the planet/
|
function getType(uint _planet) public pure returns (uint8) {
require(_planet >= 1 && _planet <= 5);
uint8[5] memory planetTypes = [ 1, 1, 2, 2, 2 ];
return planetTypes[_planet - 1];
}
| 1,490,141
|
./partial_match/1/0x5edD52A6B444aa32cca82e697bE6493Ba58beD66/sources/CompliantCrowdsale.sol
|
approve buy tokens request nonce request recorded at this particular nonce/ update stateNo need to use mint-approval on token side, since the minting is already approved in the crowdsale side
|
function approveMint(uint256 nonce)
external
onlyValidator
checkIsInvestorApproved(pendingMints[nonce].to)
returns (bool)
{
weiRaised = weiRaised.add(pendingMints[nonce].weiAmount);
totalSupply = totalSupply.add(pendingMints[nonce].tokens);
token.mint(pendingMints[nonce].to, pendingMints[nonce].tokens);
emit TokenPurchase(
msg.sender,
pendingMints[nonce].to,
pendingMints[nonce].weiAmount,
pendingMints[nonce].tokens
);
forwardFunds(pendingMints[nonce].weiAmount);
delete pendingMints[nonce];
return true;
}
| 3,969,825
|
./full_match/11155111/0xFb73a1AFf31022491208C3155880bd61Df2aF0CD/sources/AllTypes.sol
|
Store & retrieve a bytes1 val Value to return/
|
function getBytes1(bytes1 val) public pure returns (bytes1) {
return val;
}
| 3,796,048
|
./full_match/1/0x69c53679EC1C06f3275b64C428e8Cd069a2d3966/sources/contracts/fund/FundV4.sol
|
Return the fund's relative income in a trading day. Note that denominators of the returned ratios are the latest value instead of that at the last settlement. If the amount of underlying token increases from 100 to 110 and assume that there's no creation/redemption or underlying price change, return value `incomeOverQ` will be 1/11 rather than 1/10. day End timestamp of a trading day return incomeOverQ The ratio of income to the fund's total value return incomeOverB The ratio of income to equivalent BISHOP total value if all QUEEN are split
|
function getRelativeIncome(uint256 day)
external
view
override
returns (uint256 incomeOverQ, uint256 incomeOverB)
{
uint256 navB = _historicalNavB[day];
if (navB == 0) {
return (0, 0);
}
uint256 navR = _historicalNavR[day];
if (navB == UNIT && navR == UNIT) {
}
uint256 lastUnderlying = historicalUnderlying[day - 1 days];
uint256 lastEquivalentTotalB = historicalEquivalentTotalB[day - 1 days];
if (lastUnderlying == 0 || lastEquivalentTotalB == 0) {
return (0, 0);
}
uint256 currentUnderlying = historicalUnderlying[day];
uint256 currentEquivalentTotalB = historicalEquivalentTotalB[day];
if (currentUnderlying == 0 || currentEquivalentTotalB == 0) {
return (0, 0);
}
{
uint256 ratio =
((lastUnderlying * currentEquivalentTotalB) / currentUnderlying).divideDecimal(
lastEquivalentTotalB
);
incomeOverQ = ratio > 1e18 ? 0 : 1e18 - ratio;
}
incomeOverB = incomeOverQ.mul(navB + navR) / navB;
}
| 9,759,875
|
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './interfaces/IArchRouterImmutableState.sol';
/// @title Immutable state
/// @notice Immutable state used by periphery contracts
abstract contract ArchRouterImmutableState is IArchRouterImmutableState {
/// @inheritdoc IArchRouterImmutableState
address public immutable override uniV3Factory;
/// @inheritdoc IArchRouterImmutableState
address public immutable override WETH;
constructor(address _uniV3Factory, address _WETH) {
uniV3Factory = _uniV3Factory;
WETH = _WETH;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
Copyright 2021 Archer DAO: Chris Piatt ([emailย protected]).
*/
import './interfaces/IERC20Extended.sol';
import './interfaces/IUniswapV2Pair.sol';
import './interfaces/IUniswapV3Pool.sol';
import './interfaces/IUniV3Router.sol';
import './interfaces/IWETH.sol';
import './lib/RouteLib.sol';
import './lib/TransferHelper.sol';
import './lib/SafeCast.sol';
import './lib/Path.sol';
import './lib/CallbackValidation.sol';
import './ArchRouterImmutableState.sol';
import './PaymentsWithFee.sol';
import './Multicall.sol';
import './SelfPermit.sol';
/**
* @title ArcherSwapRouter
* @dev Allows Uniswap V2/V3 Router-compliant trades to be paid via tips instead of gas
*/
contract ArcherSwapRouter is
IUniV3Router,
ArchRouterImmutableState,
PaymentsWithFee,
Multicall,
SelfPermit
{
using Path for bytes;
using SafeCast for uint256;
/// @dev Used as the placeholder value for amountInCached, because the computed amount in for an exact output swap
/// can never actually be this value
uint256 private constant DEFAULT_AMOUNT_IN_CACHED = type(uint256).max;
/// @dev Transient storage variable used for returning the computed amount in for an exact output swap.
uint256 private amountInCached = DEFAULT_AMOUNT_IN_CACHED;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Trade details
struct Trade {
uint amountIn;
uint amountOut;
address[] path;
address payable to;
uint256 deadline;
}
/// @notice Uniswap V3 Swap Callback
struct SwapCallbackData {
bytes path;
address payer;
}
/**
* @notice Construct new ArcherSwap Router
* @param _uniV3Factory Uni V3 Factory address
* @param _WETH WETH address
*/
constructor(address _uniV3Factory, address _WETH) ArchRouterImmutableState(_uniV3Factory, _WETH) {}
/**
* @notice Swap tokens for ETH and pay amount of ETH as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
*/
function swapExactTokensForETHAndTipAmount(
address factory,
Trade calldata trade,
uint256 tipAmount
) external payable {
require(trade.path[trade.path.length - 1] == WETH, 'ArchRouter: INVALID_PATH');
TransferHelper.safeTransferFrom(
trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), trade.amountIn
);
_exactInputSwap(factory, trade.path, address(this));
uint256 amountOut = IWETH(WETH).balanceOf(address(this));
require(amountOut >= trade.amountOut, 'ArchRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
tip(tipAmount);
TransferHelper.safeTransferETH(trade.to, amountOut - tipAmount);
}
/**
* @notice Swap tokens for ETH and pay amount of ETH as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
*/
function swapTokensForExactETHAndTipAmount(
address factory,
Trade calldata trade,
uint256 tipAmount
) external payable {
require(trade.path[trade.path.length - 1] == WETH, 'ArchRouter: INVALID_PATH');
uint[] memory amounts = RouteLib.getAmountsIn(factory, trade.amountOut, trade.path);
require(amounts[0] <= trade.amountIn, 'ArchRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), amounts[0]
);
_exactOutputSwap(factory, amounts, trade.path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
tip(tipAmount);
TransferHelper.safeTransferETH(trade.to, trade.amountOut - tipAmount);
}
/**
* @notice Swap ETH for tokens and pay % of ETH input as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
* @param tipAmount amount of ETH to pay as tip
*/
function swapExactETHForTokensAndTipAmount(
address factory,
Trade calldata trade,
uint256 tipAmount
) external payable {
tip(tipAmount);
require(trade.path[0] == WETH, 'ArchRouter: INVALID_PATH');
uint256 inputAmount = msg.value - tipAmount;
IWETH(WETH).deposit{value: inputAmount}();
assert(IWETH(WETH).transfer(RouteLib.pairFor(factory, trade.path[0], trade.path[1]), inputAmount));
uint256 balanceBefore = IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to);
_exactInputSwap(factory, trade.path, trade.to);
require(
IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to) - balanceBefore >= trade.amountOut,
'ArchRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
/**
* @notice Swap ETH for tokens and pay amount of ETH input as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
* @param tipAmount amount of ETH to pay as tip
*/
function swapETHForExactTokensAndTipAmount(
address factory,
Trade calldata trade,
uint256 tipAmount
) external payable {
tip(tipAmount);
require(trade.path[0] == WETH, 'ArchRouter: INVALID_PATH');
uint[] memory amounts = RouteLib.getAmountsIn(factory, trade.amountOut, trade.path);
uint256 inputAmount = msg.value - tipAmount;
require(amounts[0] <= inputAmount, 'ArchRouter: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(RouteLib.pairFor(factory, trade.path[0], trade.path[1]), amounts[0]));
_exactOutputSwap(factory, amounts, trade.path, trade.to);
if (inputAmount > amounts[0]) {
TransferHelper.safeTransferETH(msg.sender, inputAmount - amounts[0]);
}
}
/**
* @notice Swap tokens for tokens and pay ETH amount as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
*/
function swapExactTokensForTokensAndTipAmount(
address factory,
Trade calldata trade
) external payable {
tip(msg.value);
_swapExactTokensForTokens(factory, trade);
}
/**
* @notice Swap tokens for tokens and pay % of tokens as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
* @param pathToEth Path to ETH for tip
* @param tipPct % of resulting tokens to pay as tip
*/
function swapExactTokensForTokensAndTipPct(
address factory,
Trade calldata trade,
address[] calldata pathToEth,
uint32 tipPct
) external payable {
_swapExactTokensForTokens(factory, trade);
IERC20Extended toToken = IERC20Extended(pathToEth[0]);
uint256 contractTokenBalance = toToken.balanceOf(address(this));
uint256 tipAmount = (contractTokenBalance * tipPct) / 1000000;
TransferHelper.safeTransfer(pathToEth[0], trade.to, contractTokenBalance - tipAmount);
_tipWithTokens(factory, pathToEth);
}
/**
* @notice Swap tokens for tokens and pay ETH amount as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
*/
function swapTokensForExactTokensAndTipAmount(
address factory,
Trade calldata trade
) external payable {
tip(msg.value);
_swapTokensForExactTokens(factory, trade);
}
/**
* @notice Swap tokens for tokens and pay % of tokens as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
* @param pathToEth Path to ETH for tip
* @param tipPct % of resulting tokens to pay as tip
*/
function swapTokensForExactTokensAndTipPct(
address factory,
Trade calldata trade,
address[] calldata pathToEth,
uint32 tipPct
) external payable {
_swapTokensForExactTokens(factory, trade);
IERC20Extended toToken = IERC20Extended(pathToEth[0]);
uint256 contractTokenBalance = toToken.balanceOf(address(this));
uint256 tipAmount = (contractTokenBalance * tipPct) / 1000000;
TransferHelper.safeTransfer(pathToEth[0], trade.to, contractTokenBalance - tipAmount);
_tipWithTokens(factory, pathToEth);
}
/**
* @notice Returns the pool for the given token pair and fee. The pool contract may or may not exist.
* @param tokenA First token
* @param tokenB Second token
* @param fee Pool fee
* @return Uniswap V3 Pool
*/
function getPool(
address tokenA,
address tokenB,
uint24 fee
) private view returns (IUniswapV3Pool) {
return IUniswapV3Pool(RouteLib.computeAddress(uniV3Factory, RouteLib.getPoolKey(tokenA, tokenB, fee)));
}
/**
* @notice Uniswap V3 Callback function that validates and pays for trade
* @dev Called by Uni V3 pool contract
* @param amount0Delta Delta for token 0
* @param amount1Delta Delta for token 1
* @param _data Swap callback data
*/
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata _data
) external override {
require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
(address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool();
CallbackValidation.verifyCallback(uniV3Factory, tokenIn, tokenOut, fee);
(bool isExactInput, uint256 amountToPay) =
amount0Delta > 0
? (tokenIn < tokenOut, uint256(amount0Delta))
: (tokenOut < tokenIn, uint256(amount1Delta));
if (isExactInput) {
pay(tokenIn, data.payer, msg.sender, amountToPay);
} else {
// either initiate the next swap or pay
if (data.path.hasMultiplePools()) {
data.path = data.path.skipToken();
_exactOutputInternal(amountToPay, msg.sender, 0, data);
} else {
amountInCached = amountToPay;
tokenIn = tokenOut; // swap in/out because exact output swaps are reversed
pay(tokenIn, data.payer, msg.sender, amountToPay);
}
}
}
/// @inheritdoc IUniV3Router
function exactInputSingle(ExactInputSingleParams calldata params)
public
payable
override
returns (uint256 amountOut)
{
amountOut = _exactInputInternal(
params.amountIn,
params.recipient,
params.sqrtPriceLimitX96,
SwapCallbackData({path: abi.encodePacked(params.tokenIn, params.fee, params.tokenOut), payer: msg.sender})
);
require(amountOut >= params.amountOutMinimum, 'Too little received');
}
/**
* @notice Performs a single exact input Uni V3 swap and tips an amount of ETH
* @param params Swap params
* @param tipAmount Tip amount
*/
function exactInputSingleAndTipAmount(ExactInputSingleParams calldata params, uint256 tipAmount)
external
payable
returns (uint256 amountOut)
{
amountOut = exactInputSingle(params);
tip(tipAmount);
}
/// @inheritdoc IUniV3Router
function exactInput(ExactInputParams memory params)
public
payable
override
returns (uint256 amountOut)
{
address payer = msg.sender; // msg.sender pays for the first hop
while (true) {
bool hasMultiplePools = params.path.hasMultiplePools();
// the outputs of prior swaps become the inputs to subsequent ones
params.amountIn = _exactInputInternal(
params.amountIn,
hasMultiplePools ? address(this) : params.recipient, // for intermediate swaps, this contract custodies
0,
SwapCallbackData({
path: params.path.getFirstPool(), // only the first pool in the path is necessary
payer: payer
})
);
// decide whether to continue or terminate
if (hasMultiplePools) {
payer = address(this); // at this point, the caller has paid
params.path = params.path.skipToken();
} else {
amountOut = params.amountIn;
break;
}
}
require(amountOut >= params.amountOutMinimum, 'Too little received');
}
/**
* @notice Performs multiple exact input Uni V3 swaps and tips an amount of ETH
* @param params Swap params
* @param tipAmount Tip amount
*/
function exactInputAndTipAmount(ExactInputParams calldata params, uint256 tipAmount)
external
payable
returns (uint256 amountOut)
{
amountOut = exactInput(params);
tip(tipAmount);
}
/// @inheritdoc IUniV3Router
function exactOutputSingle(ExactOutputSingleParams calldata params)
public
payable
override
returns (uint256 amountIn)
{
// avoid an SLOAD by using the swap return data
amountIn = _exactOutputInternal(
params.amountOut,
params.recipient,
params.sqrtPriceLimitX96,
SwapCallbackData({path: abi.encodePacked(params.tokenOut, params.fee, params.tokenIn), payer: msg.sender})
);
require(amountIn <= params.amountInMaximum, 'Too much requested');
// has to be reset even though we don't use it in the single hop case
amountInCached = DEFAULT_AMOUNT_IN_CACHED;
}
/**
* @notice Performs an exact output Uni V3 swap and tips an amount of ETH
* @param params Swap params
* @param tipAmount Tip amount
*/
function exactOutputSingleAndTipAmount(ExactOutputSingleParams calldata params, uint256 tipAmount)
external
payable
returns (uint256 amountIn)
{
amountIn = exactOutputSingle(params);
tip(tipAmount);
}
/// @inheritdoc IUniV3Router
function exactOutput(ExactOutputParams calldata params)
public
payable
override
returns (uint256 amountIn)
{
// it's okay that the payer is fixed to msg.sender here, as they're only paying for the "final" exact output
// swap, which happens first, and subsequent swaps are paid for within nested callback frames
_exactOutputInternal(
params.amountOut,
params.recipient,
0,
SwapCallbackData({path: params.path, payer: msg.sender})
);
amountIn = amountInCached;
require(amountIn <= params.amountInMaximum, 'Too much requested');
amountInCached = DEFAULT_AMOUNT_IN_CACHED;
}
/**
* @notice Performs multiple exact output Uni V3 swaps and tips an amount of ETH
* @param params Swap params
* @param tipAmount Tip amount
*/
function exactOutputAndTipAmount(ExactOutputParams calldata params, uint256 tipAmount)
external
payable
returns (uint256 amountIn)
{
amountIn = exactOutput(params);
tip(tipAmount);
}
/**
* @notice Performs a single exact input Uni V3 swap
* @param amountIn Amount of input token
* @param recipient Recipient of swap result
* @param sqrtPriceLimitX96 Price limit
* @param data Swap callback data
*/
function _exactInputInternal(
uint256 amountIn,
address recipient,
uint160 sqrtPriceLimitX96,
SwapCallbackData memory data
) private returns (uint256 amountOut) {
// allow swapping to the router address with address 0
if (recipient == address(0)) recipient = address(this);
(address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool();
bool zeroForOne = tokenIn < tokenOut;
(int256 amount0, int256 amount1) =
getPool(tokenIn, tokenOut, fee).swap(
recipient,
zeroForOne,
amountIn.toInt256(),
sqrtPriceLimitX96 == 0
? (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1)
: sqrtPriceLimitX96,
abi.encode(data)
);
return uint256(-(zeroForOne ? amount1 : amount0));
}
/**
* @notice Performs a single exact output Uni V3 swap
* @param amountOut Amount of output token
* @param recipient Recipient of swap result
* @param sqrtPriceLimitX96 Price limit
* @param data Swap callback data
*/
function _exactOutputInternal(
uint256 amountOut,
address recipient,
uint160 sqrtPriceLimitX96,
SwapCallbackData memory data
) private returns (uint256 amountIn) {
// allow swapping to the router address with address 0
if (recipient == address(0)) recipient = address(this);
(address tokenOut, address tokenIn, uint24 fee) = data.path.decodeFirstPool();
bool zeroForOne = tokenIn < tokenOut;
(int256 amount0Delta, int256 amount1Delta) =
getPool(tokenIn, tokenOut, fee).swap(
recipient,
zeroForOne,
-amountOut.toInt256(),
sqrtPriceLimitX96 == 0
? (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1)
: sqrtPriceLimitX96,
abi.encode(data)
);
uint256 amountOutReceived;
(amountIn, amountOutReceived) = zeroForOne
? (uint256(amount0Delta), uint256(-amount1Delta))
: (uint256(amount1Delta), uint256(-amount0Delta));
// it's technically possible to not receive the full output amount,
// so if no price limit has been specified, require this possibility away
if (sqrtPriceLimitX96 == 0) require(amountOutReceived == amountOut);
}
/**
* @notice Internal implementation of swap tokens for tokens
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
*/
function _swapExactTokensForTokens(
address factory,
Trade calldata trade
) internal {
TransferHelper.safeTransferFrom(
trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), trade.amountIn
);
uint balanceBefore = IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to);
_exactInputSwap(factory, trade.path, trade.to);
require(
IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to) - balanceBefore >= trade.amountOut,
'ArchRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
/**
* @notice Internal implementation of swap tokens for tokens
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
*/
function _swapTokensForExactTokens(
address factory,
Trade calldata trade
) internal {
uint[] memory amounts = RouteLib.getAmountsIn(factory, trade.amountOut, trade.path);
require(amounts[0] <= trade.amountIn, 'ArchRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), amounts[0]
);
_exactOutputSwap(factory, amounts, trade.path, trade.to);
}
/**
* @notice Internal implementation of exact input Uni V2/Sushi swap
* @param factory Uniswap V2-compliant Factory contract
* @param path Trade path
* @param _to Trade recipient
*/
function _exactInputSwap(
address factory,
address[] memory path,
address _to
) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = RouteLib.sortTokens(input, output);
IUniswapV2Pair pair = IUniswapV2Pair(RouteLib.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20Extended(input).balanceOf(address(pair)) - reserveInput;
amountOutput = RouteLib.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? RouteLib.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
/**
* @notice Internal implementation of exact output Uni V2/Sushi swap
* @param factory Uniswap V2-compliant Factory contract
* @param amounts Output amounts
* @param path Trade path
* @param _to Trade recipient
*/
function _exactOutputSwap(
address factory,
uint[] memory amounts,
address[] memory path,
address _to
) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = RouteLib.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? RouteLib.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(RouteLib.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
/**
* @notice Convert a token balance into ETH and then tip
* @param factory Factory address
* @param path Path for swap
*/
function _tipWithTokens(
address factory,
address[] memory path
) internal {
_exactInputSwap(factory, path, address(this));
uint256 amountOut = IWETH(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(amountOut);
tip(address(this).balance);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './interfaces/IMulticall.sol';
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './interfaces/IERC20Extended.sol';
import './interfaces/IPayments.sol';
import './interfaces/IWETH.sol';
import './lib/TransferHelper.sol';
import './ArchRouterImmutableState.sol';
abstract contract Payments is IPayments, ArchRouterImmutableState {
receive() external payable {
require(msg.sender == WETH, 'Not WETH');
}
/// @inheritdoc IPayments
function unwrapWETH(uint256 amountMinimum, address recipient) external payable override {
uint256 balanceWETH = withdrawWETH(amountMinimum);
TransferHelper.safeTransferETH(recipient, balanceWETH);
}
/// @inheritdoc IPayments
function unwrapWETHAndTip(uint256 tipAmount, uint256 amountMinimum, address recipient) external payable override {
uint256 balanceWETH = withdrawWETH(amountMinimum);
tip(tipAmount);
if(balanceWETH > tipAmount) {
TransferHelper.safeTransferETH(recipient, balanceWETH - tipAmount);
}
}
/// @inheritdoc IPayments
function tip(uint256 tipAmount) public payable override {
TransferHelper.safeTransferETH(block.coinbase, tipAmount);
}
/// @inheritdoc IPayments
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable override {
uint256 balanceToken = IERC20Extended(token).balanceOf(address(this));
require(balanceToken >= amountMinimum, 'Insufficient token');
if (balanceToken > 0) {
TransferHelper.safeTransfer(token, recipient, balanceToken);
}
}
/// @inheritdoc IPayments
function refundETH() external payable override {
if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance);
}
/// @param amountMinimum Min amount of WETH to withdraw
function withdrawWETH(uint256 amountMinimum) public returns(uint256 balanceWETH){
balanceWETH = IWETH(WETH).balanceOf(address(this));
require(balanceWETH >= amountMinimum && balanceWETH > 0, 'Insufficient WETH');
IWETH(WETH).withdraw(balanceWETH);
}
/// @param token The token to pay
/// @param payer The entity that must pay
/// @param recipient The entity that will receive payment
/// @param value The amount to pay
function pay(
address token,
address payer,
address recipient,
uint256 value
) internal {
if (token == WETH && address(this).balance >= value) {
// pay with WETH
IWETH(WETH).deposit{value: value}(); // wrap only what is needed to pay
IWETH(WETH).transfer(recipient, value);
} else if (payer == address(this)) {
// pay with tokens already in the contract (for the exact input multihop case)
TransferHelper.safeTransfer(token, recipient, value);
} else {
// pull payment
TransferHelper.safeTransferFrom(token, payer, recipient, value);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './interfaces/IERC20Extended.sol';
import './interfaces/IPaymentsWithFee.sol';
import './interfaces/IWETH.sol';
import './lib/TransferHelper.sol';
import './Payments.sol';
abstract contract PaymentsWithFee is Payments, IPaymentsWithFee {
/// @inheritdoc IPaymentsWithFee
function unwrapWETHWithFee(
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) public payable override {
require(feeBips > 0 && feeBips <= 100);
uint256 balanceWETH = IWETH(WETH).balanceOf(address(this));
require(balanceWETH >= amountMinimum, 'Insufficient WETH');
if (balanceWETH > 0) {
IWETH(WETH).withdraw(balanceWETH);
uint256 feeAmount = (balanceWETH * feeBips) / 10_000;
if (feeAmount > 0) TransferHelper.safeTransferETH(feeRecipient, feeAmount);
TransferHelper.safeTransferETH(recipient, balanceWETH - feeAmount);
}
}
/// @inheritdoc IPaymentsWithFee
function sweepTokenWithFee(
address token,
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) public payable override {
require(feeBips > 0 && feeBips <= 100);
uint256 balanceToken = IERC20Extended(token).balanceOf(address(this));
require(balanceToken >= amountMinimum, 'Insufficient token');
if (balanceToken > 0) {
uint256 feeAmount = (balanceToken * feeBips) / 10_000;
if (feeAmount > 0) TransferHelper.safeTransfer(token, feeRecipient, feeAmount);
TransferHelper.safeTransfer(token, recipient, balanceToken - feeAmount);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './interfaces/IERC20Extended.sol';
import './interfaces/ISelfPermit.sol';
import './interfaces/IERC20PermitAllowed.sol';
/// @title Self Permit
/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
/// @dev These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function
/// that requires an approval in a single transaction.
abstract contract SelfPermit is ISelfPermit {
/// @inheritdoc ISelfPermit
function selfPermit(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public payable override {
IERC20Extended(token).permit(msg.sender, address(this), value, deadline, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitIfNecessary(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
if (IERC20Extended(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public payable override {
IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitAllowedIfNecessary(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
if (IERC20Extended(token).allowance(msg.sender, address(this)) < type(uint256).max)
selfPermitAllowed(token, nonce, expiry, v, r, s);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IArchRouterImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function uniV3Factory() external view returns (address);
/// @return Returns the address of WETH
function WETH() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC20Extended {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function version() external view returns (uint8);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external;
function receiveWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external;
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function nonces(address) external view returns (uint);
function getDomainSeparator() external view returns (bytes32);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function DOMAIN_TYPEHASH() external view returns (bytes32);
function VERSION_HASH() external view returns (bytes32);
function PERMIT_TYPEHASH() external view returns (bytes32);
function TRANSFER_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32);
function RECEIVE_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Interface for permit
/// @notice Interface used by DAI/CHAI for permit
interface IERC20PermitAllowed {
/// @notice Approve the spender to spend some tokens via the holder signature
/// @dev This is the permit interface used by DAI and CHAI
/// @param holder The address of the token holder, the token owner
/// @param spender The address of the token spender
/// @param nonce The holder's nonce, increases at each call to permit
/// @param expiry The timestamp at which the permit is no longer valid
/// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPayments {
/// @notice Unwraps the contract's WETH balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH from users.
/// @param amountMinimum The minimum amount of WETH to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
/// @notice Tips miners using the WETH balance in the contract and then transfers the remainder to recipient
/// @dev The recipientMinimum parameter prevents malicious contracts from stealing the ETH from users
/// @param tipAmount Tip amount
/// @param amountMinimum The minimum amount of WETH to withdraw
/// @param recipient The destination address of the ETH left after tipping
function unwrapWETHAndTip(
uint256 tipAmount,
uint256 amountMinimum,
address recipient
) external payable;
/// @notice Tips miners using the ETH balance in the contract + msg.value
/// @param tipAmount Tip amount
function tip(
uint256 tipAmount
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './IPayments.sol';
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPaymentsWithFee is IPayments {
/// @notice Unwraps the contract's WETH balance and sends it to recipient as ETH, with a percentage between
/// 0 (exclusive), and 1 (inclusive) going to feeRecipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH from users.
function unwrapWETHWithFee(
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between
/// 0 (exclusive) and 1 (inclusive) going to feeRecipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
function sweepTokenWithFee(
address token,
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Self Permit
/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
interface ISelfPermit {
/// @notice Permits this contract to spend a given token from `msg.sender`
/// @dev The `owner` is always msg.sender and the `spender` is always address(this).
/// @param token The address of the token spent
/// @param value The amount that can be spent of token
/// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermit(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend a given token from `msg.sender`
/// @dev The `owner` is always msg.sender and the `spender` is always address(this).
/// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit
/// @param token The address of the token spent
/// @param value The amount that can be spent of token
/// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitIfNecessary(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
/// @dev The `owner` is always msg.sender and the `spender` is always address(this)
/// @param token The address of the token spent
/// @param nonce The current nonce of the owner
/// @param expiry The timestamp at which the permit is no longer valid
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
/// @dev The `owner` is always msg.sender and the `spender` is always address(this)
/// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.
/// @param token The address of the token spent
/// @param nonce The current nonce of the owner
/// @param expiry The timestamp at which the permit is no longer valid
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitAllowedIfNecessary(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import './IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IUniV3Router is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool
{
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
function transfer(address recipient, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* @title Solidity Bytes Arrays Utils
* @author Gonรงalo Sรก <[emailย protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity ^0.8.0;
library BytesLib {
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, 'slice_overflow');
require(_start + _length >= _start, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_start + 20 >= _start, 'toAddress_overflow');
require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_start + 3 >= _start, 'toUint24_overflow');
require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import '../interfaces/IUniswapV3Pool.sol';
import './RouteLib.sol';
/// @notice Provides validation for callbacks from Uniswap V3 Pools
library CallbackValidation {
/// @notice Returns the address of a valid Uniswap V3 Pool
/// @param factory The contract address of the Uniswap V3 factory
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The V3 pool contract address
function verifyCallback(
address factory,
address tokenA,
address tokenB,
uint24 fee
) internal view returns (IUniswapV3Pool pool) {
return verifyCallback(factory, RouteLib.getPoolKey(tokenA, tokenB, fee));
}
/// @notice Returns the address of a valid Uniswap V3 Pool
/// @param factory The contract address of the Uniswap V3 factory
/// @param poolKey The identifying key of the V3 pool
/// @return pool The V3 pool contract address
function verifyCallback(address factory, RouteLib.PoolKey memory poolKey)
internal
view
returns (IUniswapV3Pool pool)
{
pool = IUniswapV3Pool(RouteLib.computeAddress(factory, poolKey));
require(msg.sender == address(pool));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './BytesLib.sol';
/// @title Functions for manipulating path data for multihop swaps
library Path {
using BytesLib for bytes;
/// @dev The length of the bytes encoded address
uint256 private constant ADDR_SIZE = 20;
/// @dev The length of the bytes encoded fee
uint256 private constant FEE_SIZE = 3;
/// @dev The offset of a single token address and pool fee
uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
/// @dev The offset of an encoded pool key
uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
/// @dev The minimum length of an encoding that contains 2 or more pools
uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;
/// @notice Returns true iff the path contains two or more pools
/// @param path The encoded swap path
/// @return True if path contains two or more pools, otherwise false
function hasMultiplePools(bytes memory path) internal pure returns (bool) {
return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
}
/// @notice Decodes the first pool in path
/// @param path The bytes encoded swap path
/// @return tokenA The first token of the given pool
/// @return tokenB The second token of the given pool
/// @return fee The fee level of the pool
function decodeFirstPool(bytes memory path)
internal
pure
returns (
address tokenA,
address tokenB,
uint24 fee
)
{
tokenA = path.toAddress(0);
fee = path.toUint24(ADDR_SIZE);
tokenB = path.toAddress(NEXT_OFFSET);
}
/// @notice Gets the segment corresponding to the first pool in the path
/// @param path The bytes encoded swap path
/// @return The segment containing all data necessary to target the first pool in the path
function getFirstPool(bytes memory path) internal pure returns (bytes memory) {
return path.slice(0, POP_OFFSET);
}
/// @notice Skips a token + fee element from the buffer and returns the remainder
/// @param path The swap path
/// @return The remaining token + fee elements in the path
function skipToken(bytes memory path) internal pure returns (bytes memory) {
return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '../interfaces/IUniswapV2Pair.sol';
library RouteLib {
address internal constant _SUSHI_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac;
bytes32 internal constant _SUSHI_ROUTER_INIT_HASH = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303;
bytes32 internal constant _UNI_V2_ROUTER_INIT_HASH = 0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f;
bytes32 internal constant _UNI_V3_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
// 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, 'RouteLib: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'RouteLib: 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);
bytes32 initHash = factory == _SUSHI_FACTORY ? _SUSHI_ROUTER_INIT_HASH : _UNI_V2_ROUTER_INIT_HASH;
pair = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
initHash // init code hash
)
)
)
)
);
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
_UNI_V3_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, 'RouteLib: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'RouteLib: INSUFFICIENT_LIQUIDITY');
amountB = amountA * (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, 'RouteLib: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'RouteLib: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn * 997;
uint numerator = amountInWithFee * reserveOut;
uint denominator = reserveIn * 1000 + 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, 'RouteLib: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'RouteLib: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn * amountOut * 1000;
uint denominator = (reserveOut - amountOut) * 997;
amountIn = (numerator / denominator) + 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, 'RouteLib: 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, 'RouteLib: 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);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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');
}
}
|
Periphery Payments Functions to ease deposits and withdrawals of ETH
|
interface IPayments {
function unwrapWETH(uint256 amountMinimum, address recipient) external payable;
function refundETH() external payable;
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
function unwrapWETHAndTip(
uint256 tipAmount,
uint256 amountMinimum,
address recipient
) external payable;
function tip(
uint256 tipAmount
) external payable;
}
pragma solidity ^0.8.0;
}
| 11,683,133
|
./full_match/1/0x0fFe9697c852cBBB35e4EeF49Cbc948dAF855d63/sources/contracts/terraformSandbox.sol
|
Determines the animation style of a dream placement The placement of dream on level/tile before rotation seed Value used to rotate initial dream placement return An Animation enum representing the type of animation Configurable selection, "activation" is a nonce 0.1% are Plague, the rest are Cascade
|
function getActivation(uint placement, uint seed)
internal
pure
returns (ITerraformSVG.Activation)
{
uint activation = uint(
keccak256(abi.encodePacked(placement, seed, "activation"))
) % 10_000;
if (activation >= 9_990){
return ITerraformSVG.Activation.Plague;
return ITerraformSVG.Activation.Cascade;
}
}
| 9,654,935
|
pragma solidity 0.5.3;
/**
* @title ERC20 Full interface
* @dev see https://github.com/ethereum/EIPs/issues/20
* @dev This interface should NOT be used in your contracts. As this includes
* @dev OPTIONAL functions as well.
* @dev Actual interface that you can use is ERC20Interface.sol
*/
interface ERC20FullInterface {
//Below are the functions an implementation MUST have
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
/* solhint-disable no-simple-event-func-name */
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
//Below are the OPTIONAL functions of API
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
|
ERC20 Full interface This interface should NOT be used in your contracts. As this includes OPTIONAL functions as well. Actual interface that you can use is ERC20Interface.sol/Below are the functions an implementation MUST haveBelow are the OPTIONAL functions of API
|
interface ERC20FullInterface {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
| 12,727,355
|
./full_match/11155111/0x45b7bdC937d86ed59ABDeAeC1AC514C8110535aA/sources/project_/contracts/MultiTokenTimeLockedVault.sol
|
Check the user is paying the correct deposit fee Check the deposit parameters Add the deposit fee to the withdrawable fees Transfer the deposit tokens to this contract Store the deposit details
|
function deposit(
address token,
uint256 amount,
uint256 unlockTimestamp
) public payable onlyWhitelistedToken(token) returns (uint256) {
require(
msg.value == depositFee,
"Incorrect deposit fee. Please send the required amount."
);
require(amount > 0, "Amount must be greater than 0.");
require(
unlockTimestamp > block.timestamp,
"Unlock timestamp must be in the future."
);
withdrawableDepositFees += msg.value;
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
_depositIdCounter++;
uint256 depositId = _depositIdCounter;
depositInfo[depositId] = Deposit({
id: depositId,
depositor: msg.sender,
token: token,
amount: amount,
unlockTimestamp: unlockTimestamp
});
emit DepositMade(depositId, msg.sender, token, amount, unlockTimestamp);
return depositId;
}
| 3,812,075
|
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
interface IReverseResolver {
function claim(address owner) external returns (bytes32);
}
interface IVendingMachineFactory {
function moonCatVendingMachineExists(uint256 tokenId) external view returns (bool);
function vendingMachineCanMintStart(uint256 tokenId) external view returns (uint256);
}
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
}
/**
* @title MoonCatPop cans
* @dev ERC721 token of a virtual can of pop.
*/
contract MoonCatPopVendingMachine is ERC721Enumerable, Ownable, Pausable {
using Strings for uint256;
string public baseURI;
/* Financials */
uint256 public constant primarySalesPercent = 80;
uint256 public constant secondaryRoyaltiesPercent = 50;
uint256 public constant moonCatOwnerDiscount = 0.01 ether;
/* Vended Cans */
uint256[256] public totalSupplyPerMachine;
uint256 public maxCansPerMachine = 100;
uint256 public vendingCost = 0.05 ether;
/* External Contracts */
address public moonCatPopVendingMachineFactory;
address public constant moonCatAcclimatorContract = 0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69;
/* Events */
event BaseURISet(string baseURI);
/**
* @dev Deploy contract.
*/
constructor(address _factoryAddress) ERC721("MoonCatPop", "CAN") {
moonCatPopVendingMachineFactory = _factoryAddress;
_pause();
// https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address
IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148)
.claim(msg.sender);
}
/**
* @dev Pause the contract.
* Prevent minting and transferring of tokens
*/
function paws() public onlyOwner {
_pause();
}
/**
* @dev Unpause the contract.
* Allow minting and transferring of tokens
*/
function unpaws() public onlyOwner {
_unpause();
}
/**
* @dev Update the base URI for token metadata.
*/
function setBaseURI(string memory _newbaseURI) public onlyFactoryOwner() {
baseURI = _newbaseURI;
emit BaseURISet(_newbaseURI);
}
/**
* @dev Rescue ERC20 assets sent directly to this contract.
*/
function withdrawForeignERC20(address tokenContract) public onlyOwner {
IERC20 token = IERC20(tokenContract);
token.transfer(owner(), token.balanceOf(address(this)));
}
/**
* @dev Rescue ERC721 assets sent directly to this contract.
*/
function withdrawForeignERC721(address tokenContract, uint256 tokenId) public onlyOwner {
IERC721(tokenContract).safeTransferFrom(address(this), owner(), tokenId);
}
/**
* @dev Create a can of MoonCatPop
*/
function mint(uint vendingMachineId)
public
payable
returns(uint256)
{
uint256 cost = (IERC721(moonCatAcclimatorContract).balanceOf(_msgSender()) == 0)
? vendingCost
: (vendingCost - moonCatOwnerDiscount);
require(msg.value == cost, "Exact Change Required");
return _mint(vendingMachineId, cost);
}
/**
* @dev Create multiple cans of MoonCatPop
*/
function batchMint(uint256[] memory vendingMachineIds)
public
payable
returns(uint256[] memory)
{
uint256[] memory tokenIds = new uint256[](vendingMachineIds.length);
uint256 cost = (IERC721(moonCatAcclimatorContract).balanceOf(_msgSender()) == 0)
? vendingCost
: (vendingCost - moonCatOwnerDiscount);
require(msg.value == cost * vendingMachineIds.length, "Exact Change Required");
for (uint256 i; i < vendingMachineIds.length; i++) {
tokenIds[i] = _mint(vendingMachineIds[i], cost);
}
return tokenIds;
}
/**
* @dev Internal function to do shared minting actions.
*/
function _mint(uint256 _vendingMachineId, uint256 _cost)
internal
whenNotPaused
returns(uint256)
{
IVendingMachineFactory VMF = IVendingMachineFactory(moonCatPopVendingMachineFactory);
require(VMF.moonCatVendingMachineExists(_vendingMachineId), "No Such Vending Machine");
require(block.number >= VMF.vendingMachineCanMintStart(_vendingMachineId), "Can minting not open");
require(totalSupplyPerMachine[_vendingMachineId] < maxCansPerMachine, "Can limit exceeded");
uint256 tokenId = _vendingMachineId * maxCansPerMachine + totalSupplyPerMachine[_vendingMachineId];
_safeMint(_msgSender(), tokenId);
totalSupplyPerMachine[_vendingMachineId]++;
address vendingMachineOwner = ERC721(moonCatPopVendingMachineFactory).ownerOf(_vendingMachineId);
// Check if Owner is ERC998 contract
// 0xed81cdda == rootOwnerOfChild(address,uint256)
// 0xcd740db5 == ERC998 Magic Value
(bool callSuccess, bytes memory data) = vendingMachineOwner.staticcall(abi.encodeWithSelector(0xed81cdda, moonCatPopVendingMachineFactory, _vendingMachineId));
if (data.length != 0) {
bytes32 dataBytes = abi.decode(data, (bytes32));
if (callSuccess && dataBytes >> 224 == 0x00000000000000000000000000000000000000000000000000000000cd740db5) {
// Token owner is a top-down composable
vendingMachineOwner = address(uint160(uint256(dataBytes & 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff)));
}
}
uint256 vendingMachineOwnerPayment = _cost * primarySalesPercent / 100;
(bool success,) = vendingMachineOwner.call{value:vendingMachineOwnerPayment}('');
require(success, "Failed to transfer VM Owner payment");
(success,) = moonCatPopVendingMachineFactory.call{value:_cost - vendingMachineOwnerPayment}('');
require(success, "Failed to transfer Owner payment");
return tokenId;
}
/**
* @dev See {ERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
uint256 vendingMachineId = _tokenId / maxCansPerMachine;
uint256 canId = _tokenId % maxCansPerMachine;
return bytes(baseURI).length > 0 ? string(abi.encodePacked(
baseURI,
vendingMachineId.toString(), '/',
canId.toString(), '.json'
)) : "";
}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override whenNotPaused {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Throws if called by any account other than the factory owner.
*/
modifier onlyFactoryOwner() {
require(Ownable(moonCatPopVendingMachineFactory).owner() == _msgSender(), "Ownable: caller is not factory owner");
_;
}
/**
* @dev Default funds-receiving method.
*/
receive() external payable {
payable(owner()).transfer(msg.value * secondaryRoyaltiesPercent / 100);
(bool success,) = payable(moonCatPopVendingMachineFactory).call{value: address(this).balance}("");
require(success,"transfer failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/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());
}
}
|
Internal function to do shared minting actions./ Check if Owner is ERC998 contract 0xed81cdda == rootOwnerOfChild(address,uint256) 0xcd740db5 == ERC998 Magic Value Token owner is a top-down composable
|
function _mint(uint256 _vendingMachineId, uint256 _cost)
internal
whenNotPaused
returns(uint256)
{
IVendingMachineFactory VMF = IVendingMachineFactory(moonCatPopVendingMachineFactory);
require(VMF.moonCatVendingMachineExists(_vendingMachineId), "No Such Vending Machine");
require(block.number >= VMF.vendingMachineCanMintStart(_vendingMachineId), "Can minting not open");
require(totalSupplyPerMachine[_vendingMachineId] < maxCansPerMachine, "Can limit exceeded");
uint256 tokenId = _vendingMachineId * maxCansPerMachine + totalSupplyPerMachine[_vendingMachineId];
_safeMint(_msgSender(), tokenId);
totalSupplyPerMachine[_vendingMachineId]++;
address vendingMachineOwner = ERC721(moonCatPopVendingMachineFactory).ownerOf(_vendingMachineId);
(bool callSuccess, bytes memory data) = vendingMachineOwner.staticcall(abi.encodeWithSelector(0xed81cdda, moonCatPopVendingMachineFactory, _vendingMachineId));
if (data.length != 0) {
bytes32 dataBytes = abi.decode(data, (bytes32));
if (callSuccess && dataBytes >> 224 == 0x00000000000000000000000000000000000000000000000000000000cd740db5) {
vendingMachineOwner = address(uint160(uint256(dataBytes & 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff)));
}
}
uint256 vendingMachineOwnerPayment = _cost * primarySalesPercent / 100;
require(success, "Failed to transfer VM Owner payment");
require(success, "Failed to transfer Owner payment");
return tokenId;
}
| 588,324
|
./partial_match/1/0xbBe628d7284c88f79C70DeF6867995e313dF525A/sources/YRegistry.sol
|
require(_vault.isContract(), "Vault is not a contract"); Checks if vault is already on the array Adds unique _vault to vaults array
|
function setVault(address _vault) internal {
require(!vaults.contains(_vault), "Vault already exists");
vaults.add(_vault);
}
| 4,441,612
|
// Sources flattened with hardhat v2.1.2 https://hardhat.org
// File deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol
// 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 SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// File deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract 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;
}
// File deps/@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File deps/@openzeppelin/contracts-upgradeable/cryptography/MerkleProofUpgradeable.sol
pragma solidity ^0.6.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProofUpgradeable {
/**
* @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;
}
}
// File interfaces/yearn/GuestlistApi.sol
pragma solidity >=0.6.0 <0.7.0;
interface GuestListAPI {
function authorized(address guest, uint256 amount) external view returns (bool);
}
// File deps/@openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File interfaces/yearn/BadgerWrapperApi.sol
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
interface BadgerWrapperAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function token() external view returns (address);
function pricePerShare() external view returns (uint256);
function totalWrapperBalance(address account) external view returns (uint256);
function totalVaultBalance(address account) external view returns (uint256);
}
// File contracts/yearn/VipCappedGuestListWrapperUpgradeable.sol
pragma solidity >=0.6.0 <0.7.0;
/**
* @notice A basic guest list contract for testing.
* @dev For a Vyper implementation of this contract containing additional
* functionality, see https://github.com/banteg/guest-list/blob/master/contracts/GuestList.vy
* The owner can invite arbitrary guests
* A guest can be added permissionlessly with proof of inclusion in current merkle set
* The owner can change the merkle root at any time
* Merkle-based permission that has been claimed cannot be revoked permissionlessly.
* Any guests can be revoked by the owner at-will
* The TVL cap is based on the number of want tokens in the underlying vaults.
* This can only be made more permissive over time. If decreased, existing TVL is maintained and no deposits are possible until the TVL has gone below the threshold
* A variant of the yearn AffiliateToken that supports guest list control of deposits
* A guest list that gates access by merkle root and a TVL cap
*/
contract VipCappedGuestListWrapperUpgradeable is OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
address public wrapper;
bytes32 public guestRoot;
uint256 public userDepositCap;
uint256 public totalDepositCap;
mapping(address => bool) public guests;
event ProveInvitation(address indexed account, bytes32 indexed guestRoot);
event SetGuestRoot(bytes32 indexed guestRoot);
event SetUserDepositCap(uint256 cap);
event SetTotalDepositCap(uint256 cap);
/**
* @notice Create the test guest list, setting the message sender as
* `owner`.
* @dev Note that since this is just for testing, you're unable to change
* `owner`.
*/
function initialize(address wrapper_) public initializer {
__Ownable_init();
wrapper = wrapper_;
}
/**
* @notice Invite guests or kick them from the party.
* @param _guests The guests to add or update.
* @param _invited A flag for each guest at the matching index, inviting or
* uninviting the guest.
*/
function setGuests(address[] calldata _guests, bool[] calldata _invited) external onlyOwner {
_setGuests(_guests, _invited);
}
function vaultBalance(address account) public view returns (uint256) {
return BadgerWrapperAPI(wrapper).totalVaultBalance(account);
}
function wrapperBalance(address user) public view returns (uint256) {
return BadgerWrapperAPI(wrapper).totalWrapperBalance(user);
}
function remainingTotalDepositAllowed() public view returns (uint256) {
return totalDepositCap.sub(vaultBalance(wrapper));
}
function remainingUserDepositAllowed(address user) public view returns (uint256) {
return userDepositCap.sub(wrapperBalance(user));
}
/**
* @notice Permissionly prove an address is included in the current merkle root, thereby granting access
* @notice Note that the list is designed to ONLY EXPAND in future instances
* @notice The admin does retain the ability to ban individual addresses
*/
function proveInvitation(address account, bytes32[] calldata merkleProof) public {
// Verify Merkle Proof
require(_verifyInvitationProof(account, merkleProof));
address[] memory accounts = new address[](1);
bool[] memory invited = new bool[](1);
accounts[0] = account;
invited[0] = true;
_setGuests(accounts, invited);
emit ProveInvitation(account, guestRoot);
}
/**
* @notice Set the merkle root to verify invitation proofs against.
* @notice Note that accounts not included in the root will still be invited if their inviation was previously approved.
* @notice Setting to 0 removes proof verification versus the root, opening access
*/
function setGuestRoot(bytes32 guestRoot_) external onlyOwner {
guestRoot = guestRoot_;
emit SetGuestRoot(guestRoot);
}
function setUserDepositCap(uint256 cap_) external onlyOwner {
userDepositCap = cap_;
emit SetUserDepositCap(userDepositCap);
}
function setTotalDepositCap(uint256 cap_) external onlyOwner {
totalDepositCap = cap_;
emit SetTotalDepositCap(totalDepositCap);
}
/**
* @notice Check if a guest with a bag of a certain size is allowed into
* the party.
* @dev Note that `_amount` isn't checked to keep test setup simple, since
* from the wrapper tests' perspective this is a pass/fail call anyway.
* @param _guest The guest's address to check.
*/
function authorized(address _guest, uint256 _amount, bytes32[] calldata _merkleProof) external view returns (bool) {
// Yes: If the user is on the list, and under the cap
// Yes: If the user is not on the list, supplies a valid proof (thereby being added to the list), and is under the cap
// No: If the user is not on the list, does not supply a valid proof, or is over the cap
bool invited = guests[_guest];
// If there is no guest root, all users are invited
if (!invited && guestRoot == bytes32(0)) {
invited = true;
}
// If the user is not already invited and there is an active guestList, require verification of merkle proof to grant temporary invitation (does not set storage variable)
if (!invited && guestRoot != bytes32(0)) {
// Will revert on invalid proof
invited = _verifyInvitationProof(_guest, _merkleProof);
}
// If the user was previously invited, or proved invitiation via list, verify if the amount to deposit keeps them under the cap
if (invited && remainingUserDepositAllowed(_guest) >= _amount && remainingTotalDepositAllowed() >= _amount) {
return true;
} else {
return false;
}
}
function _setGuests(address[] memory _guests, bool[] memory _invited) internal {
require(_guests.length == _invited.length);
for (uint256 i = 0; i < _guests.length; i++) {
if (_guests[i] == address(0)) {
break;
}
guests[_guests[i]] = _invited[i];
}
}
function _verifyInvitationProof(address account, bytes32[] calldata merkleProof) internal view returns (bool) {
bytes32 node = keccak256(abi.encodePacked(account));
return MerkleProofUpgradeable.verify(merkleProof, guestRoot, node);
}
}
|
Permissionly prove an address is included in the current merkle root, thereby granting access Note that the list is designed to ONLY EXPAND in future instances The admin does retain the ability to ban individual addresses/ Verify Merkle Proof
|
function proveInvitation(address account, bytes32[] calldata merkleProof) public {
require(_verifyInvitationProof(account, merkleProof));
address[] memory accounts = new address[](1);
bool[] memory invited = new bool[](1);
accounts[0] = account;
invited[0] = true;
_setGuests(accounts, invited);
emit ProveInvitation(account, guestRoot);
}
| 92,800
|
./full_match/97/0xDb27f83Fe37AfC3d85b96271200eD4EF8D9AFc73/sources/contracts/AtarStaking.sol
|
This method may only be invoked by the owner's address and is used to adjust the stake duration (locking period), the argument will be in seconds /
|
function SetStakeDuration(
uint256 first,
uint256 second,
uint256 third,
uint256 fourth,
uint256 fifth,
uint256 sixth,
uint256 seventh
) external onlyowner {
Duration[0] = first;
Duration[1] = second;
Duration[2] = third;
Duration[3] = fourth;
Duration[4] = fifth;
Duration[5] = sixth;
Duration[6] = seventh;
}
| 5,018,453
|
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This function is deprecated.
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length.sub(1);
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
//Optional mapping for IPFS link to canonical image file
mapping(uint256 => string) private _tokenIPFSHashes;
mapping(uint256 => string) private _niftyTypeName;
//Optional mapping for IPFS link to canonical image file by Nifty type
mapping(uint256 => string) private _niftyTypeIPFSHashes;
//Token name
mapping(uint256 => string) private _tokenName;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
//master builder - ONLY DOES STATIC CALLS
address public masterBuilderContract = 0x6EFB06cF568253a53C7511BD3c31AB28BecB0192;
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
/**
* @dev Returns an IPFS Hash for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenIPFSHash(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
//master for static calls
BuilderMaster bm = BuilderMaster(masterBuilderContract);
uint nifty_type = bm.getNiftyTypeId(tokenId);
return _niftyTypeIPFSHashes[nifty_type];
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenName(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
//master for static calls
BuilderMaster bm = BuilderMaster(masterBuilderContract);
uint nifty_type = bm.getNiftyTypeId(tokenId);
return _niftyTypeName[nifty_type];
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to set the token IPFS hash for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param ipfs_hash string IPFS link to assign
*/
function _setTokenIPFSHash(uint256 tokenId, string memory ipfs_hash) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenIPFSHashes[tokenId] = ipfs_hash;
}
/**
* @dev Internal function to set the token IPFS hash for a given token.
* Reverts if the token ID does not exist.
* @param niftyType uint256 ID of the token to set its URI
* @param ipfs_hash string IPFS link to assign
*/
function _setTokenIPFSHashNiftyType(uint256 niftyType, string memory ipfs_hash) internal {
// require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_niftyTypeIPFSHashes[niftyType] = ipfs_hash;
}
/**
* @dev Internal function to set the token IPFS hash for a given token.
* Reverts if the token ID does not exist.
* @param nifty_type uint256 of nifty type name to be set
* @param nifty_type_name name of nifty type
*/
function _setNiftyTypeName(uint256 nifty_type, string memory nifty_type_name) internal {
_niftyTypeName[nifty_type] = nifty_type_name;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
/**
* @title Full ERC721 Token
* @dev This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology.
*
* See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) {
// solhint-disable-previous-line no-empty-blocks
}
}
contract BeepleSpecialEdition is ERC721Full {
//MODIFIERS
modifier onlyOwner() {
require(msg.sender == contractOwner);
_;
}
//CONSTANTS
// how many nifties this contract is selling
// used for metadat retrieval
uint public numNiftiesCurrentlyInContract;
//id of this contract for metadata server
uint public contractId;
//baseURI for metadata server
string public baseURI;
// name of creator
string public nameOfCreator;
//election victor
string public electionVictor;
//ipfs hashes for images if trump or biden wins
string public bidenVictoryIPFSHash;
string public trumpVictoryIPFSHash;
bool public electionVictorEncoded = false;
address public contractOwner;
//master builder - ONLY DOES STATIC CALLS
address public masterBuilderContract = 0x6EFB06cF568253a53C7511BD3c31AB28BecB0192;
using Counters for Counters.Counter;
//MAPPINGS
//mappings for token Ids
mapping (uint => Counters.Counter) public _numNiftyMinted;
mapping (uint => uint) public _numNiftyPermitted;
mapping (uint => uint) public _niftyPrice;
mapping (uint => string) public _niftyIPFSHashes;
// mapping (uint => bool) public _IPFSHashHasBeenSet;
//EVENTS
//purchase + creation events
event NiftyPurchased(address _buyer, uint256 _amount, uint _tokenId);
event NiftyCreated(address new_owner, uint _niftyType, uint _tokenId);
//CONSTRUCTOR FUNCTION
constructor(
string memory biden_victory_ipfs_hash,
string memory trump_victory_ipfs_hash,
string memory special_edition_initial_ipfs_hash,
string memory normal_auction_ipfs_hash,
string memory edition_ipfs_hash,
string memory base_uri) ERC721Full("Beeple Special Edition", "BEEPLE") public {
//set contract owner to deployer wallet
contractOwner = msg.sender;
//set local variables based on inputs
contractId = 1;
numNiftiesCurrentlyInContract = 3;
baseURI = base_uri;
nameOfCreator = "Beeple";
electionVictor = "unknown";
//nifty type 1 is an edition of 1, the special changing auction
_numNiftyPermitted[1] = 1;
//nifty type 2 is the other auction
_numNiftyPermitted[2] = 1;
//nifty type 3 is the edition of 100
_numNiftyPermitted[3] = 100;
//store trump & biden victory ipfs hashes
bidenVictoryIPFSHash = biden_victory_ipfs_hash;
trumpVictoryIPFSHash = trump_victory_ipfs_hash;
_setTokenIPFSHashNiftyType(1,special_edition_initial_ipfs_hash);
_setTokenIPFSHashNiftyType(2,normal_auction_ipfs_hash);
_setTokenIPFSHashNiftyType(3,edition_ipfs_hash);
//set names
_setNiftyTypeName(1, "CROSSROAD");
_setNiftyTypeName(2, "CRYPTO IS BULLSHIT");
_setNiftyTypeName(3, "POLITICS IS BULLSHIT");
}
function certifyBidenVictory() onlyOwner public {
if (electionVictorEncoded == true) {
revert("Election victory has already been encoded!");
} else {
electionVictorEncoded = true;
electionVictor = "Biden";
_setTokenIPFSHashNiftyType(1,bidenVictoryIPFSHash);
}
}
function certifyTrumpVictory() onlyOwner public {
if (electionVictorEncoded == true) {
revert("Election victory has already been encoded!");
} else {
electionVictorEncoded = true;
electionVictor = "Trump";
_setTokenIPFSHashNiftyType(1,trumpVictoryIPFSHash);
}
}
function isNiftySoldOut(uint niftyType) public view returns (bool) {
if (niftyType > numNiftiesCurrentlyInContract) {
return true;
}
if (_numNiftyMinted[niftyType].current() > _numNiftyPermitted[niftyType]) {
return (true);
} else {
return (false);
}
}
function giftNifty(address collector_address,
uint niftyType) onlyOwner public {
//master for static calls
BuilderMaster bm = BuilderMaster(masterBuilderContract);
_numNiftyMinted[niftyType].increment();
//check if this nifty is sold out
if (isNiftySoldOut(niftyType)==true) {
revert("Nifty sold out!");
}
//mint a nifty
uint specificTokenId = _numNiftyMinted[niftyType].current();
uint tokenId = bm.encodeTokenId(contractId, niftyType, specificTokenId);
string memory tokenIdStr = bm.uint2str(tokenId);
string memory tokenURI = bm.strConcat(baseURI, tokenIdStr);
string memory ipfsHash = _niftyIPFSHashes[niftyType];
//mint token
_mint(collector_address, tokenId);
_setTokenURI(tokenId, tokenURI);
_setTokenIPFSHash(tokenId, ipfsHash);
//do events
emit NiftyCreated(collector_address, niftyType, tokenId);
}
function massMintType3NFTs(address collector_address, uint numToMint) onlyOwner public {
//loop through array and create nifties
for (uint i=0; i < numToMint; i++) {
giftNifty(collector_address,3);
}
}
}
contract NiftyRegistry {
function isValidNiftySender(address sending_key) public view returns (bool);
function isOwner(address owner_key) public view returns (bool);
}
contract BuilderMaster {
function getContractId(uint tokenId) public view returns (uint);
function getNiftyTypeId(uint tokenId) public view returns (uint);
function getSpecificNiftyNum(uint tokenId) public view returns (uint);
function encodeTokenId(uint contractId, uint niftyType, uint specificNiftyNum) public view returns (uint);
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) public view returns (string memory);
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) public view returns (string memory);
function strConcat(string memory _a, string memory _b, string memory _c) public view returns (string memory);
function strConcat(string memory _a, string memory _b) public view returns (string memory);
function uint2str(uint _i) public view returns (string memory _uintAsString);
}
/**
* Contracts and libraries below are from OpenZeppelin, except nifty builder instance
**/
/**
* @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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @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);
}
}
|
Internal function to set the token IPFS hash for a given token. Reverts if the token ID does not exist. tokenId uint256 ID of the token to set its URI ipfs_hash string IPFS link to assign/
|
function _setTokenIPFSHash(uint256 tokenId, string memory ipfs_hash) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenIPFSHashes[tokenId] = ipfs_hash;
}
| 7,954,593
|
./partial_match/1/0xE870D00176b2C71AFD4c43ceA550228E22be4ABd/sources/LiquidityPoolV1Converter.sol
|
increases the pool's liquidity and mints new shares in the pool to the caller note that prior to version 28, you should use 'fund' instead _reserveTokens address of each reserve token _reserveAmounts amount of each reserve token _minReturn token minimum return-amount/ verify the user input if one of the reserves is ETH, then verify that the input amount of ETH is equal to the input value of ETH if the input value of ETH is larger than zero, then verify that one of the reserves is ETH get the total supply transfer from the user an equally-worth amount of each one of the reserve tokens verify that the equivalent amount of tokens is equal to or larger than the user's expectation issue the tokens to the user
|
function addLiquidity(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _minReturn)
public
payable
protected
active
{
verifyLiquidityInput(_reserveTokens, _reserveAmounts, _minReturn);
for (uint256 i = 0; i < _reserveTokens.length; i++)
if (_reserveTokens[i] == ETH_RESERVE_ADDRESS)
require(_reserveAmounts[i] == msg.value, "ERR_ETH_AMOUNT_MISMATCH");
if (msg.value > 0)
require(reserves[ETH_RESERVE_ADDRESS].isSet, "ERR_NO_ETH_RESERVE");
uint256 totalSupply = ISmartToken(anchor).totalSupply();
uint256 amount = addLiquidityToPool(_reserveTokens, _reserveAmounts, totalSupply);
require(amount >= _minReturn, "ERR_RETURN_TOO_LOW");
ISmartToken(anchor).issue(msg.sender, amount);
}
| 4,377,605
|
pragma solidity ^0.4.18;
library ByteSlice {
struct Slice {
uint _unsafe_memPtr; // Memory address of the first byte.
uint _unsafe_length; // Length.
}
/// @dev Converts bytes to a slice.
/// @param self The bytes.
/// @return A slice.
function slice(bytes memory self) internal pure returns (Slice memory newSlice) {
assembly {
let length := mload(self)
let memPtr := add(self, 0x20)
mstore(newSlice, mul(memPtr, iszero(iszero(length))))
mstore(add(newSlice, 0x20), length)
}
}
/// @dev Converts bytes to a slice from the given starting position.
/// 'startpos' <= 'len(slice)'
/// @param self The bytes.
/// @param startpos The starting position.
/// @return A slice.
function slice(bytes memory self, uint startpos) internal pure returns (Slice memory) {
return slice(slice(self), startpos);
}
/// @dev Converts bytes to a slice from the given starting position.
/// -len(slice) <= 'startpos' <= 'len(slice)'
/// @param self The bytes.
/// @param startpos The starting position.
/// @return A slice.
function slice(bytes memory self, int startpos) internal pure returns (Slice memory) {
return slice(slice(self), startpos);
}
/// @dev Converts bytes to a slice from the given starting-position, and end-position.
/// 'startpos <= len(slice) and startpos <= endpos'
/// 'endpos <= len(slice)'
/// @param self The bytes.
/// @param startpos The starting position.
/// @param endpos The end position.
/// @return A slice.
function slice(bytes memory self, uint startpos, uint endpos) internal view returns (Slice memory) {
return slice(slice(self), startpos, endpos);
}
/// @dev Converts bytes to a slice from the given starting-position, and end-position.
/// Warning: higher cost then using unsigned integers.
/// @param self The bytes.
/// @param startpos The starting position.
/// @param endpos The end position.
/// @return A slice.
function slice(bytes memory self, int startpos, int endpos) internal view returns (Slice memory) {
return slice(slice(self), startpos, endpos);
}
/// @dev Get the length of the slice (in bytes).
/// @param self The slice.
/// @return the length.
function len(Slice memory self) internal pure returns (uint) {
return self._unsafe_length;
}
/// @dev Returns the byte from the backing array at a given index.
/// The function will throw unless 'index < len(slice)'
/// @param self The slice.
/// @param index The index.
/// @return The byte at that index.
function at(Slice memory self, uint index) internal pure returns (byte b) {
if (index >= self._unsafe_length)
revert();
uint bb;
assembly {
// Get byte at index, and format to 'byte' variable.
bb := byte(0, mload(add(mload(self), index)))
}
b = byte(bb);
}
/// @dev Returns the byte from the backing array at a given index.
/// The function will throw unless '-len(self) <= index < len(self)'.
/// @param self The slice.
/// @param index The index.
/// @return The byte at that index.
function at(Slice memory self, int index) internal pure returns (byte b) {
if (index >= 0)
return at(self, uint(index));
uint iAbs = uint(-index);
if (iAbs > self._unsafe_length)
revert();
return at(self, self._unsafe_length - iAbs);
}
/// @dev Set the byte at the given index.
/// The function will throw unless 'index < len(slice)'
/// @param self The slice.
/// @param index The index.
/// @return The byte at that index.
function set(Slice memory self, uint index, byte b) internal pure {
if (index >= self._unsafe_length)
revert();
assembly {
mstore8(add(mload(self), index), byte(0, b))
}
}
/// @dev Set the byte at the given index.
/// The function will throw unless '-len(self) <= index < len(self)'.
/// @param self The slice.
/// @param index The index.
/// @return The byte at that index.
function set(Slice memory self, int index, byte b) internal pure {
if (index >= 0)
return set(self, uint(index), b);
uint iAbs = uint(-index);
if (iAbs > self._unsafe_length)
revert();
return set(self, self._unsafe_length - iAbs, b);
}
/// @dev Creates a copy of the slice.
/// @param self The slice.
/// @return the new reference.
function slice(Slice memory self) internal pure returns (Slice memory newSlice) {
newSlice._unsafe_memPtr = self._unsafe_memPtr;
newSlice._unsafe_length = self._unsafe_length;
}
/// @dev Create a new slice from the given starting position.
/// 'startpos' <= 'len(slice)'
/// @param self The slice.
/// @param startpos The starting position.
/// @return The new slice.
function slice(Slice memory self, uint startpos) internal pure returns (Slice memory newSlice) {
uint length = self._unsafe_length;
if (startpos > length)
revert();
assembly {
length := sub(length, startpos)
let newMemPtr := mul(add(mload(self), startpos), iszero(iszero(length)))
mstore(newSlice, newMemPtr)
mstore(add(newSlice, 0x20), length)
}
}
/// @dev Create a new slice from the given starting position.
/// -len(slice) <= 'startpos' <= 'len(slice)'
/// @param self The slice.
/// @param startpos The starting position.
/// @return The new slice.
function slice(Slice memory self, int startpos) internal pure returns (Slice memory newSlice) {
uint startpos_;
uint length = self._unsafe_length;
if (startpos >= 0) {
startpos_ = uint(startpos);
if (startpos_ > length)
revert();
} else {
startpos_ = uint(-startpos);
if (startpos_ > length)
revert();
startpos_ = length - startpos_;
}
assembly {
length := sub(length, startpos_)
let newMemPtr := mul(add(mload(self), startpos_), iszero(iszero(length)))
mstore(newSlice, newMemPtr)
mstore(add(newSlice, 0x20), length)
}
}
/// @dev Create a new slice from a given slice, starting-position, and end-position.
/// 'startpos <= len(slice) and startpos <= endpos'
/// 'endpos <= len(slice)'
/// @param self The slice.
/// @param startpos The starting position.
/// @param endpos The end position.
/// @return the new slice.
function slice(Slice memory self, uint startpos, uint endpos) internal pure returns (Slice memory newSlice) {
uint length = self._unsafe_length;
if (startpos > length || endpos > length || startpos > endpos)
revert();
assembly {
length := sub(endpos, startpos)
let newMemPtr := mul(add(mload(self), startpos), iszero(iszero(length)))
mstore(newSlice, newMemPtr)
mstore(add(newSlice, 0x20), length)
}
}
/// Same as new(Slice memory, uint, uint) but allows for negative indices.
/// Warning: higher cost then using unsigned integers.
/// @param self The slice.
/// @param startpos The starting position.
/// @param endpos The end position.
/// @return The new slice.
function slice(Slice memory self, int startpos, int endpos) internal pure returns (Slice memory newSlice) {
// Don't allow slice on bytes of length 0.
uint startpos_;
uint endpos_;
uint length = self._unsafe_length;
if (startpos < 0) {
startpos_ = uint(-startpos);
if (startpos_ > length)
revert();
startpos_ = length - startpos_;
}
else {
startpos_ = uint(startpos);
if (startpos_ > length)
revert();
}
if (endpos < 0) {
endpos_ = uint(-endpos);
if (endpos_ > length)
revert();
endpos_ = length - endpos_;
}
else {
endpos_ = uint(endpos);
if (endpos_ > length)
revert();
}
if(startpos_ > endpos_)
revert();
assembly {
length := sub(endpos_, startpos_)
let newMemPtr := mul(add(mload(self), startpos_), iszero(iszero(length)))
mstore(newSlice, newMemPtr)
mstore(add(newSlice, 0x20), length)
}
}
/// @dev Creates a 'bytes memory' variable from a slice, copying the data.
/// Bytes are copied from the memory address 'self._unsafe_memPtr'.
/// The number of bytes copied is 'self._unsafe_length'.
/// @param self The slice.
/// @return The bytes variable.
function toBytes(Slice memory self) internal constant returns (bytes memory bts) {
uint length = self._unsafe_length;
if (length == 0)
return;
uint memPtr = self._unsafe_memPtr;
bts = new bytes(length);
// We can do word-by-word copying since 'bts' was the last thing to be
// allocated. Just overwrite any excess bytes at the end with zeroes.
assembly {
let i := 0
let btsOffset := add(bts, 0x20)
let words := div(add(length, 31), 32)
tag_loop:
jumpi(end, gt(i, words))
{
let offset := mul(i, 32)
mstore(add(btsOffset, offset), mload(add(memPtr, offset)))
i := add(i, 1)
}
jump(tag_loop)
end:
mstore(add(add(bts, length), 0x20), 0)
}
}
/// @dev Creates an ascii-encoded 'string' variable from a slice, copying the data.
/// Bytes are copied from the memory address 'self._unsafe_memPtr'.
/// The number of bytes copied is 'self._unsafe_length'.
/// @param self The slice.
/// @return The bytes variable.
function toAscii(Slice memory self) internal view returns (string memory str) {
return string(toBytes(self));
}
/// @dev Check if two slices are equal.
/// @param self The slice.
/// @param other The other slice.
/// @return True if both slices point to the same memory address, and has the same length.
function equals(Slice memory self, Slice memory other) internal pure returns (bool) {
return (
self._unsafe_length == other._unsafe_length &&
self._unsafe_memPtr == other._unsafe_memPtr
);
}
}
library Bytes {
function concat(bytes memory self, bytes memory bts) internal view returns (bytes memory newBts) {
uint totLen = self.length + bts.length;
if (totLen == 0)
return;
newBts = new bytes(totLen);
assembly {
let i := 0
let inOffset := 0
let outOffset := add(newBts, 0x20)
let words := 0
let tag := tag_bts
tag_self:
inOffset := add(self, 0x20)
words := div(add(mload(self), 31), 32)
jump(tag_loop)
tag_bts:
i := 0
inOffset := add(bts, 0x20)
outOffset := add(newBts, add(0x20, mload(self)))
words := div(add(mload(bts), 31), 32)
tag := tag_end
tag_loop:
jumpi(tag, gt(i, words))
{
let offset := mul(i, 32)
outOffset := add(outOffset, offset)
mstore(outOffset, mload(add(inOffset, offset)))
i := add(i, 1)
}
jump(tag_loop)
tag_end:
mstore(add(newBts, add(totLen, 0x20)), 0)
}
}
function uintToBytes(uint self) internal pure returns (bytes memory s) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (self != 0) {
uint remainder = self % 10;
self = self / 10;
reversed[i++] = byte(48 + remainder);
}
s = new bytes(i);
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - 1 - j];
}
return s;
}
}
contract PlasmaParent {
using Bytes for *;
using ByteSlice for *;
address public owner = msg.sender;
mapping(address => bool) public operators;
uint32 public blockHeaderLength = 137;
uint256 public lastBlockNumber = 0;
uint256 public lastEthBlockNumber = block.number;
uint256 public depositCounterInBlock = 0;
struct Header {
uint32 blockNumber;
uint32 numTransactions;
uint8 v;
bytes32 previousBlockHash;
bytes32 merkleRootHash;
bytes32 r;
bytes32 s;
}
struct TransactionInput {
uint32 blockNumber;
uint32 txNumberInBlock;
uint8 outputNumberInTX;
uint256 amount;
}
struct TransactionOutput {
address recipient;
uint8 outputNumberInTX;
uint256 amount;
}
struct PlasmaTransaction {
uint32 txNumberInBlock;
uint8 txType;
TransactionInput[] inputs;
TransactionOutput[] outputs;
uint8 v;
bytes32 r;
bytes32 s;
}
uint256 constant TxTypeNull = 0;
uint256 constant TxTypeSplit = 1;
uint256 constant TxTypeMerge = 2;
uint256 constant TxTypeWithdraw = 3;
uint256 constant TxTypeFund = 4;
uint256 constant TxTypeTransfer = 5;
uint256[6] NumInputsForType = [0, 1, 2, 1, 1, 1];
uint256[6] NumOutputsForType = [0, 2, 1, 1, 2, 1];
uint256 constant SignatureLength = 65;
uint256 constant BlockNumberLength = 4;
uint256 constant TxNumberLength = 4;
uint256 constant TxTypeLength = 1;
uint256 constant TxOutputNumberLength = 1;
uint256 constant PreviousHashLength = 32;
uint256 constant MerkleRootHashLength = 32;
uint256 constant TxAmountLength = 32;
bytes constant PersonalMessagePrefixBytes = "\x19Ethereum Signed Message:\n";
uint256 constant PreviousBlockPersonalHashLength = BlockNumberLength +
TxNumberLength +
PreviousHashLength +
MerkleRootHashLength +
SignatureLength;
uint256 constant NewBlockPersonalHashLength = BlockNumberLength +
TxNumberLength +
PreviousHashLength +
MerkleRootHashLength;
uint256 TransactionOutputLength = 20 + TxOutputNumberLength + TxAmountLength;
uint256 TransactionInputLength = BlockNumberLength + TxNumberLength + TxOutputNumberLength + TxAmountLength;
uint256 TxMainLength = TxNumberLength + TxTypeLength + SignatureLength;
uint256[6] TxLengthForType = [0,
TxMainLength + 1*TransactionInputLength + 2*TransactionOutputLength,
TxMainLength + 2*TransactionInputLength + 1*TransactionOutputLength,
TxMainLength + 1*TransactionInputLength + 1*TransactionOutputLength,
TxMainLength + 1*TransactionInputLength + 2*TransactionOutputLength,
TxMainLength + 1*TransactionInputLength + 1*TransactionOutputLength];
mapping (uint256 => Header) public headers;
event Debug(bool indexed _success, bytes32 indexed _b, address indexed _signer);
event DebugUint(uint256 indexed _1, uint256 indexed _2, uint256 indexed _3);
event SigEvent(address indexed _signer, bytes32 indexed _r, bytes32 indexed _s);
function extract32(bytes data, uint pos) pure internal returns (bytes32 result) {
for (uint256 i = 0; i < 32; i++) {
result ^= (bytes32(0xff00000000000000000000000000000000000000000000000000000000000000)&data[i+pos])>>(i*8);
}
}
function extract20(bytes data, uint pos) pure internal returns (bytes20 result) {
for (uint256 i = 0; i < 20; i++) {
result ^= (bytes20(0xff00000000000000000000000000000000000000)&data[i+pos])>>(i*8);
}
}
function extract4(bytes data, uint pos) pure internal returns (bytes4 result) {
for (uint256 i = 0; i < 4; i++) {
result ^= (bytes4(0xff000000)&data[i+pos])>>(i*8);
}
}
function extract2(bytes data, uint pos) pure internal returns (bytes2 result) {
for (uint256 i = 0; i < 2; i++) {
result ^= (bytes2(0xff00)&data[i+pos])>>(i*8);
}
}
function extract1(bytes data, uint pos) pure internal returns (bytes1 result) {
for (uint256 i = 0; i < 1; i++) {
result ^= (bytes1(0xff)&data[i+pos])>>(i*8);
}
}
function PlasmaParent() public {
operators[msg.sender] = true;
}
function setOperator(address _op, bool _status) public returns (bool success) {
require(msg.sender == owner);
operators[_op] = _status;
return true;
}
event HeaderSubmittedEvent(address indexed _signer, uint32 indexed _blockNumber, bytes32 indexed _blockHash);
function submitBlockHeader(bytes header) public returns (bool success) {
require(operators[msg.sender]);
require(header.length == blockHeaderLength);
uint32 blockNumber = uint32(extract4(header, 0));
uint32 numTransactions = uint32(extract4(header, BlockNumberLength));
bytes32 previousBlockHash = extract32(header, BlockNumberLength + TxNumberLength);
bytes32 merkleRootHash = extract32(header, BlockNumberLength + TxNumberLength + PreviousHashLength);
uint8 v = uint8(extract1(header, BlockNumberLength + TxNumberLength + PreviousHashLength + MerkleRootHashLength));
bytes32 r = extract32(header, BlockNumberLength + TxNumberLength + PreviousHashLength + MerkleRootHashLength + 1);
bytes32 s = extract32(header, BlockNumberLength + TxNumberLength + PreviousHashLength + MerkleRootHashLength + 33);
uint256 newBlockNumber = uint256(uint32(blockNumber));
require(newBlockNumber == lastBlockNumber+1);
if (lastBlockNumber != 0) {
Header storage previousHeader = headers[lastBlockNumber];
bytes32 previousHash = keccak256(PersonalMessagePrefixBytes, PreviousBlockPersonalHashLength.uintToBytes(), previousHeader.blockNumber, previousHeader.numTransactions, previousHeader.previousBlockHash, previousHeader.merkleRootHash,
previousHeader.v, previousHeader.r,previousHeader.s);
require(previousHash == previousBlockHash);
}
bytes32 newBlockHash = keccak256(PersonalMessagePrefixBytes, NewBlockPersonalHashLength.uintToBytes(), blockNumber, numTransactions, previousBlockHash, merkleRootHash);
if (v < 27) {
v = v+27;
}
address signer = ecrecover(newBlockHash, v, r, s);
require(operators[signer]);
Header memory newHeader = Header({
blockNumber: blockNumber,
numTransactions: numTransactions,
previousBlockHash: previousBlockHash,
merkleRootHash: merkleRootHash,
v: v,
r: r,
s: s
});
lastBlockNumber = lastBlockNumber+1;
headers[lastBlockNumber] = newHeader;
HeaderSubmittedEvent(signer, blockNumber, newBlockHash);
return true;
}
// ----------------------------------
// Deposit related functions
enum DepositStatus {
NoRecord,
Deposited,
WithdrawStarted,
WithdrawChallenged,
WithdrawCompleted,
DepositConfirmed
}
struct DepositRecord {
address from;
DepositStatus status;
uint256 amount;
uint256 index;
uint256 withdrawStartedTime;
}
event DepositEvent(address indexed _from, uint256 indexed _amount, uint256 indexed _depositIndex);
event DepositWithdrawStartedEvent(uint256 indexed _depositIndex);
event DepositWithdrawChallengedEvent(uint256 indexed _depositIndex);
event DepositWithdrawCompletedEvent(uint256 indexed _depositIndex);
mapping (address => uint256[]) userDepositRecords;
mapping (uint256 => mapping(uint256 => DepositRecord)) public depositRecords;
function () payable external {
deposit();
}
function depositRecordsForUser(address _user) public view returns (uint256[]) {
return userDepositRecords[_user];
}
function deposit() payable public returns (uint256 idx) {
if (block.number != lastEthBlockNumber) {
depositCounterInBlock = 0;
}
uint256 depositIndex = block.number << 32 + depositCounterInBlock;
DepositRecord storage record = depositRecords[0][depositIndex];
require(record.index == 0);
require(record.status == DepositStatus.NoRecord);
record.index = depositIndex;
record.from = msg.sender;
record.amount = msg.value;
record.status = DepositStatus.Deposited;
depositCounterInBlock = depositCounterInBlock + 1;
userDepositRecords[msg.sender].push(depositIndex);
DepositEvent(msg.sender, msg.value, depositIndex);
return depositIndex;
}
// function startDepositWithdraw(uint256 depositIndex) public returns (bool success) {
// DepositRecord storage record = depositRecords[0][depositIndex];
// require(record.index == depositIndex);
// require(record.status == DepositStatus.Deposited);
// require(record.from == msg.sender);
// record.status = DepositStatus.WithdrawStarted;
// record.withdrawStartedTime = now;
// DepositWithdrawStartedEvent(depositIndex);
// return true;
// }
// function finalizeDepositWithdraw(uint256 depositIndex) public returns (bool success) {
// DepositRecord storage record = depositRecords[0][depositIndex];
// require(record.index == depositIndex);
// require(record.status == DepositStatus.WithdrawStarted);
// require(now >= record.withdrawStartedTime + (24 hours));
// record.status = DepositStatus.WithdrawCompleted;
// DepositWithdrawCompletedEvent(depositIndex);
// record.from.transfer(record.amount);
// return true;
// }
// function challengeDepositWithdraw(uint256 depositIndex,
// uint32 _plasmaBlockNumber,
// bytes _plasmaTransaction,
// bytes _merkleProof) public returns (bool success) {
// DepositRecord storage record = depositRecords[0][depositIndex];
// require(record.index == depositIndex);
// require(record.status == DepositStatus.WithdrawStarted);
// record.status = DepositStatus.WithdrawChallenged;
// Header storage header = headers[uint256(_plasmaBlockNumber)];
// require(uint32(header.blockNumber) > 0);
// bool validProof = checkProof(header.merkleRootHash, _plasmaTransaction, _merkleProof, true);
// require(validProof);
// PlasmaTransaction memory TX = plasmaTransactionFromBytes(_plasmaTransaction);
// require(TX.txType == TxTypeFund);
// address signer = recoverTXsigner(_plasmaTransaction, TX.v, TX.r, TX.s, TX.txType);
// require(operators[signer]);
// TransactionOutput memory output0 = TX.outputs[0];
// TransactionOutput memory output1 = TX.outputs[1];
// require(output0.recipient == record.from);
// require(output0.amount == record.amount);
// require(output1.outputNumberInTX == 255);
// require(output1.amount == depositIndex);
// record.status = DepositStatus.DepositConfirmed;
// DepositWithdrawChallengedEvent(depositIndex);
// return true;
// }
// ----------------------------------
// Withdrawrelated functions
enum WithdrawStatus {
NoRecord,
Started,
Challenged,
Completed,
Rejected
}
struct WithdrawRecord {
uint256 index;
uint32 blockNumber;
uint32 txNumberInBlock;
uint8 outputNumberInTX;
address beneficiary;
bool isExpress;
WithdrawStatus status;
uint256 amount;
uint256 timeStarted;
uint256 timeEnded;
}
event WithdrawStartedEvent(uint32 indexed _blockNumber,
uint32 indexed _txNumberInBlock,
uint8 indexed _outputNumberInTX);
event WithdrawRequestAcceptedEvent(address indexed _from,
uint256 indexed _withdrawIndex);
event WithdrawFinalizedEvent(uint32 indexed _blockNumber,
uint32 indexed _txNumberInBlock,
uint8 indexed _outputNumberInTX);
event ExpressWithdrawMadeEvent(uint32 indexed _withdrawTxBlockNumber,
uint32 indexed _withdrawTxNumberInBlock,
address indexed _from);
mapping (address => uint256[]) userWithdrawRecords;
mapping (uint256 => mapping(uint256 => WithdrawRecord)) public withdrawRecords;
function withdrawRecordsForUser(address _user) public view returns (uint256[]) {
return userWithdrawRecords[_user];
}
// function startWithdraw(uint32 _plasmaBlockNumber, //references and proves ownership on output of original transaction
// uint32 _plasmaTxNumInBlock,
// uint8 _outputNumber,
// bytes _plasmaTransaction,
// bytes _merkleProof)
// public returns(bool success, uint256 withdrawIndex) {
// Header storage header = headers[uint256(_plasmaBlockNumber)];
// require(uint32(header.blockNumber) > 0);
// bool validProof = checkProof(header.merkleRootHash, _plasmaTransaction, _merkleProof, true);
// require(validProof);
// PlasmaTransaction memory TX = plasmaTransactionFromBytes(_plasmaTransaction);
// require(TX.txType != TxTypeWithdraw);
// address signer = recoverTXsigner(_plasmaTransaction, TX.v, TX.r, TX.s, TX.txType);
// require(signer != address(0));
// TransactionOutput memory output = TX.outputs[_outputNumber];
// require(output.recipient == msg.sender);
// require(output.outputNumberInTX != 255);
// WithdrawRecord storage record = populateWithdrawRecordFromOutput(output, _plasmaBlockNumber, _plasmaTxNumInBlock, _outputNumber);
// record.beneficiary = output.recipient;
// record.timeEnded = now;
// WithdrawRequestAcceptedEvent(output.recipient, record.index);
// WithdrawStartedEvent(_plasmaBlockNumber, _plasmaTxNumInBlock, _outputNumber);
// userWithdrawRecords[msg.sender].push(record.index);
// return (true, withdrawIndex);
// }
function makeWithdrawExpress(uint32 _plasmaBlockNumber, //references and proves ownership on withdraw transaction
uint32 _plasmaTxNumInBlock,
bytes _plasmaTransaction,
bytes _merkleProof)
public returns(bool success, uint256 withdrawIndex) {
Header storage header = headers[uint256(_plasmaBlockNumber)];
require(uint32(header.blockNumber) > 0);
bool validProof = checkProof(header.merkleRootHash, _plasmaTransaction, _merkleProof, true);
require(validProof);
PlasmaTransaction memory TX = plasmaTransactionFromBytes(_plasmaTransaction);
require(TX.txType == TxTypeWithdraw);
require(TX.txNumberInBlock == _plasmaTxNumInBlock);
address signer = recoverTXsigner(_plasmaTransaction, TX.v, TX.r, TX.s, TX.txType);
require(signer == msg.sender);
TransactionInput memory input = TX.inputs[0];
WithdrawRecord storage record = populateWithdrawRecordForInput(input);
record.beneficiary = signer;
require(record.status == WithdrawStatus.Started);
record.status = WithdrawStatus.Completed;
record.isExpress = true;
record.timeEnded = now;
WithdrawRequestAcceptedEvent(record.beneficiary, record.index);
WithdrawStartedEvent(input.blockNumber, input.txNumberInBlock, input.outputNumberInTX);
WithdrawFinalizedEvent(input.blockNumber, input.txNumberInBlock, input.outputNumberInTX);
ExpressWithdrawMadeEvent(_plasmaBlockNumber, TX.txNumberInBlock, record.beneficiary);
userWithdrawRecords[msg.sender].push(record.index);
signer.transfer(record.amount);
return (true, withdrawIndex);
}
// function getWithdrawRecordForInput(TransactionInput memory _input) internal view returns (WithdrawRecord storage record) {
// uint256 withdrawIndex = makeTransactionIndex(_input.blockNumber, _input.txNumberInBlock, _input.outputNumberInTX);
// withdrawIndex = withdrawIndex + (block.number << 128);
// record = withdrawRecords[0][withdrawIndex];
// require(record.index == withdrawIndex);
// require(record.blockNumber == _input.blockNumber);
// require(record.txNumberInBlock == _input.txNumberInBlock);
// require(record.outputNumberInTX == _input.outputNumberInTX);
// require(record.amount == _input.amount);
// return record;
// }
function populateWithdrawRecordForInput(TransactionInput memory _input) internal returns (WithdrawRecord storage record) {
uint256 withdrawIndex = makeTransactionIndex(_input.blockNumber, _input.txNumberInBlock, _input.outputNumberInTX);
// withdrawIndex = withdrawIndex + (block.number << 128);
record = withdrawRecords[0][withdrawIndex];
require(record.status == WithdrawStatus.NoRecord);
record.index = withdrawIndex;
record.blockNumber = _input.blockNumber;
record.txNumberInBlock = _input.txNumberInBlock;
record.outputNumberInTX = _input.outputNumberInTX;
record.status = WithdrawStatus.Started;
record.amount = _input.amount;
record.timeStarted = now;
return record;
}
function populateWithdrawRecordFromOutput(TransactionOutput memory _output, uint32 _blockNumber, uint32 _txNumberInBlock, uint8 _outputNumberInTX) internal returns (WithdrawRecord storage record) {
uint256 withdrawIndex = makeTransactionIndex(_blockNumber, _txNumberInBlock, _outputNumberInTX);
// withdrawIndex = withdrawIndex + (block.number << 128);
record = withdrawRecords[0][withdrawIndex];
require(record.status == WithdrawStatus.NoRecord);
record.index = withdrawIndex;
record.status = WithdrawStatus.Started;
record.amount = _output.amount;
record.timeStarted = now;
record.blockNumber = _blockNumber;
record.txNumberInBlock = _txNumberInBlock;
record.outputNumberInTX = _outputNumberInTX;
return record;
}
// function finalizeWithdraw(uint256 withdrawIndex) public returns(bool success) {
// WithdrawRecord storage record = withdrawRecords[0][withdrawIndex];
// require(record.status == WithdrawStatus.Started);
// require(now >= record.timeStarted + (24 hours));
// address to = record.beneficiary;
// record.status = WithdrawStatus.Completed;
// record.timeEnded = now;
// WithdrawFinalizedEvent(record.blockNumber, record.txNumberInBlock, record.outputNumberInTX);
// to.transfer(record.amount);
// return true;
// }
// ----------------------------------
// Double-spend related functions
struct DoubleSpendRecord {
bool prooved;
}
struct SpendAndWithdrawRecord {
bool prooved;
}
event DoubleSpendProovedEvent(uint256 indexed _txIndex1, uint256 indexed _txIndex2);
event SpendAndWithdrawProovedEvent(uint256 indexed _txIndex, uint256 indexed _withdrawIndex);
mapping (uint256 => mapping(uint256 => DoubleSpendRecord)) public doubleSpendRecords;
mapping (uint256 => mapping(uint256 => SpendAndWithdrawRecord)) public spendAndWithdrawRecords;
// two transactions spend the same output
function proveDoubleSpend(uint32 _plasmaBlockNumber1, //references and proves transaction number 1
uint32 _plasmaTxNumInBlock1,
uint8 _inputNumber1,
bytes _plasmaTransaction1,
bytes _merkleProof1,
uint32 _plasmaBlockNumber2, //references and proves transaction number 2
uint32 _plasmaTxNumInBlock2,
uint8 _inputNumber2,
bytes _plasmaTransaction2,
bytes _merkleProof2) public returns (bool success) {
uint256 index1 = makeTransactionIndex(_plasmaBlockNumber1, _plasmaTxNumInBlock1, _inputNumber1);
uint256 index2 = makeTransactionIndex(_plasmaBlockNumber2, _plasmaTxNumInBlock2, _inputNumber2);
require(index1 != index2);
require(!doubleSpendRecords[index1][index2].prooved);
require(!doubleSpendRecords[index2][index1].prooved);
require(checkActualDoubleSpendProof(_plasmaBlockNumber1,
_plasmaTxNumInBlock1,
_inputNumber1,
_plasmaTransaction1,
_merkleProof1,
_plasmaBlockNumber2,
_plasmaTxNumInBlock2,
_inputNumber2,
_plasmaTransaction2,
_merkleProof2));
doubleSpendRecords[index1][index2].prooved = true;
doubleSpendRecords[index2][index1].prooved = true;
return true;
}
function checkActualDoubleSpendProof (uint32 _plasmaBlockNumber1, //references and proves transaction number 1
uint32 _plasmaTxNumInBlock1,
uint8 _inputNumber1,
bytes _plasmaTransaction1,
bytes _merkleProof1,
uint32 _plasmaBlockNumber2, //references and proves transaction number 2
uint32 _plasmaTxNumInBlock2,
uint8 _inputNumber2,
bytes _plasmaTransaction2,
bytes _merkleProof2) public view returns (bool success) {
var (signer1, input1) = getTXinputDetailsFromProof(_plasmaBlockNumber1, _plasmaTxNumInBlock1, _inputNumber1, _plasmaTransaction1, _merkleProof1);
var (signer2, input2) = getTXinputDetailsFromProof(_plasmaBlockNumber2, _plasmaTxNumInBlock2, _inputNumber2, _plasmaTransaction2, _merkleProof2);
require(signer1 != address(0));
require(signer2 != address(0));
require(signer1 == signer2);
require(input1.blockNumber == input2.blockNumber);
require(input1.txNumberInBlock == input2.txNumberInBlock);
require(input1.outputNumberInTX == input2.outputNumberInTX);
return true;
}
// transaction output is withdrawn (witthout express process) and spent in Plasma chain
function proveSpendAndWithdraw(uint32 _plasmaBlockNumber, //references and proves transaction
uint32 _plasmaTxNumInBlock,
uint8 _inputNumber,
bytes _plasmaTransaction,
bytes _merkleProof,
uint256 _withdrawIndex //references withdraw
) public returns (bool success) {
uint256 txIndex = makeTransactionIndex(_plasmaBlockNumber, _plasmaTxNumInBlock, _inputNumber);
require(!spendAndWithdrawRecords[txIndex][_withdrawIndex].prooved);
WithdrawRecord storage record = withdrawRecords[0][_withdrawIndex];
var (signer, input) = getTXinputDetailsFromProof(_plasmaBlockNumber, _plasmaTxNumInBlock, _inputNumber, _plasmaTransaction, _merkleProof);
require(signer != address(0));
require(input.blockNumber == record.blockNumber);
require(input.txNumberInBlock == record.txNumberInBlock);
require(input.outputNumberInTX == record.outputNumberInTX);
if (record.status == WithdrawStatus.Completed) {
spendAndWithdrawRecords[txIndex][_withdrawIndex].prooved = true;
SpendAndWithdrawProovedEvent(txIndex, _withdrawIndex);
} else if (record.status == WithdrawStatus.Started) {
record.status = WithdrawStatus.Challenged;
spendAndWithdrawRecords[txIndex][_withdrawIndex].prooved = true;
SpendAndWithdrawProovedEvent(txIndex, _withdrawIndex);
}
return true;
}
// ----------------------------------
// Prove unlawful funding transactions on Plasma
struct FundingWithoutDepositRecord {
bool prooved;
}
struct DoubleFundingRecord {
bool prooved;
}
mapping (uint256 => mapping(uint256 => FundingWithoutDepositRecord)) public fundingWithoutDepositRecords;
mapping (uint256 => mapping(uint256 => DoubleFundingRecord)) public doubleFundingRecords;
event FundingWithoutDepositEvent(uint256 indexed _txIndex, uint256 indexed _depositIndex);
event DoubleFundingEvent(uint256 indexed _txIndex1, uint256 indexed _txIndex2);
function proveFundingWithoutDeposit(uint32 _plasmaBlockNumber, //references and proves transaction
uint32 _plasmaTxNumInBlock,
bytes _plasmaTransaction,
bytes _merkleProof) public returns (bool success) {
Header storage header = headers[uint256(_plasmaBlockNumber)];
require(uint32(header.blockNumber) > 0);
bool validProof = checkProof(header.merkleRootHash, _plasmaTransaction, _merkleProof, true);
require(validProof);
PlasmaTransaction memory TX = plasmaTransactionFromBytes(_plasmaTransaction);
require(TX.txType == TxTypeFund);
address signer = recoverTXsigner(_plasmaTransaction, TX.v, TX.r, TX.s, TX.txType);
require(operators[signer]);
TransactionOutput memory output = TX.outputs[0];
TransactionOutput memory outputAux = TX.outputs[1];
require(outputAux.outputNumberInTX == 255);
require(TX.txNumberInBlock == _plasmaTxNumInBlock);
uint256 depositIndex = output.amount;
uint256 transactionIndex = makeTransactionIndex(_plasmaBlockNumber, TX.txNumberInBlock, 0);
require(!fundingWithoutDepositRecords[transactionIndex][depositIndex].prooved);
DepositRecord storage record = depositRecords[0][depositIndex];
if (record.status == DepositStatus.NoRecord) {
FundingWithoutDepositEvent(transactionIndex, depositIndex);
fundingWithoutDepositRecords[transactionIndex][depositIndex].prooved = true;
return true;
} else if (record.amount != output.amount || record.from != output.recipient) {
FundingWithoutDepositEvent(transactionIndex, depositIndex);
fundingWithoutDepositRecords[transactionIndex][depositIndex].prooved = true;
return true;
}
revert();
return false;
}
//prove double funding of the same
function proveDoubleFunding(uint32 _plasmaBlockNumber1, //references and proves transaction number 1
uint32 _plasmaTxNumInBlock1,
bytes _plasmaTransaction1,
bytes _merkleProof1,
uint32 _plasmaBlockNumber2, //references and proves transaction number 2
uint32 _plasmaTxNumInBlock2,
bytes _plasmaTransaction2,
bytes _merkleProof2) public returns (bool success) {
var (signer1, depositIndex1, transactionIndex1) = getFundingTXdetailsFromProof(_plasmaBlockNumber1, _plasmaTxNumInBlock1, _plasmaTransaction1, _merkleProof1);
var (signer2, depositIndex2, transactionIndex2) = getFundingTXdetailsFromProof(_plasmaBlockNumber2, _plasmaTxNumInBlock2, _plasmaTransaction2, _merkleProof2);
require(checkDoubleFundingFromInternal(signer1, depositIndex1, transactionIndex1, signer2, depositIndex2, transactionIndex2));
doubleFundingRecords[transactionIndex1][transactionIndex2].prooved = true;
doubleFundingRecords[transactionIndex2][transactionIndex1].prooved = true;
return true;
}
function checkDoubleFundingFromInternal (address signer1,
uint256 depositIndex1,
uint256 transactionIndex1,
address signer2,
uint256 depositIndex2,
uint256 transactionIndex2) public view returns (bool) {
require(operators[signer1]);
require(operators[signer2]);
require(depositIndex1 == depositIndex2);
require(transactionIndex1 != transactionIndex2);
require(!doubleFundingRecords[transactionIndex1][transactionIndex2].prooved);
require(!doubleFundingRecords[transactionIndex2][transactionIndex1].prooved);
return true;
}
// ----------------------------------
// Convenience functions
function getTXinputDetailsFromProof(uint32 _plasmaBlockNumber,
uint32 _plasmaTxNumInBlock,
uint8 _inputNumber,
bytes _plasmaTransaction,
bytes _merkleProof) internal view returns (address signer, TransactionInput memory input) {
Header storage header = headers[uint256(_plasmaBlockNumber)];
require(uint32(header.blockNumber) > 0);
bool validProof = checkProof(header.merkleRootHash, _plasmaTransaction, _merkleProof, true);
require(validProof);
PlasmaTransaction memory TX = plasmaTransactionFromBytes(_plasmaTransaction);
require(TX.txType != TxTypeFund);
signer = recoverTXsigner(_plasmaTransaction, TX.v, TX.r, TX.s, TX.txType);
require(signer != address(0));
input = TX.inputs[uint256(_inputNumber)];
}
function getFundingTXdetailsFromProof(uint32 _plasmaBlockNumber,
uint32 _plasmaTxNumInBlock,
bytes _plasmaTransaction,
bytes _merkleProof) internal view returns (address signer, uint256 depositIndex, uint256 transactionIndex) {
Header storage header = headers[uint256(_plasmaBlockNumber)];
require(uint32(header.blockNumber) > 0);
bool validProof = checkProof(header.merkleRootHash, _plasmaTransaction, _merkleProof, true);
require(validProof);
PlasmaTransaction memory TX = plasmaTransactionFromBytes(_plasmaTransaction);
require(TX.txType == TxTypeFund);
signer = recoverTXsigner(_plasmaTransaction, TX.v, TX.r, TX.s, TX.txType);
TransactionOutput memory outputAux = TX.outputs[1];
require(outputAux.outputNumberInTX == 255);
require(TX.txNumberInBlock == _plasmaTxNumInBlock);
depositIndex = outputAux.amount;
transactionIndex = makeTransactionIndex(_plasmaBlockNumber, TX.txNumberInBlock, 0);
return (signer, depositIndex, transactionIndex);
}
function plasmaTransactionFromBytes(bytes _rawTX) internal view returns (PlasmaTransaction memory TX) {
uint8 txType = uint8(extract1(_rawTX, TxNumberLength));
uint256 expectedLength = TxLengthForType[txType];
require(_rawTX.length == expectedLength);
uint256 numInputs = NumInputsForType[txType];
uint256 numOutputs = NumOutputsForType[txType];
uint32 numInBlock = uint32(extract4(_rawTX,0));
uint256 signatureOffset = TxNumberLength + TxTypeLength + numInputs*TransactionInputLength + numOutputs*TransactionOutputLength;
uint8 v = uint8(extract1(_rawTX, signatureOffset));
bytes32 r = extract32(_rawTX, signatureOffset + 1);
bytes32 s = extract32(_rawTX, signatureOffset + 33);
TX = PlasmaTransaction({
txNumberInBlock: numInBlock,
txType: txType,
inputs: new TransactionInput[](numInputs),
outputs: new TransactionOutput[](numOutputs),
v : v,
r: r,
s: s
});
bytes memory insAndOutsSlice = _rawTX.slice(TxNumberLength + TxTypeLength, signatureOffset).toBytes();
assert(populateInsAndOuts(TX, numInputs, numOutputs, insAndOutsSlice));
return TX;
}
function populateInsAndOuts(PlasmaTransaction memory _TX, uint256 _numIns, uint256 _numOuts, bytes memory _insAndOutsSlice)
internal view returns (bool success) {
uint256 i;
for (i = 0; i < _numIns; i++) {
bytes memory rawInput = _insAndOutsSlice.slice(i*TransactionInputLength, (i+1)*TransactionInputLength).toBytes();
TransactionInput memory input = transactionInputFromBytes(rawInput);
_TX.inputs[i] = input;
}
for (i = 0; i < _numOuts; i++) {
bytes memory rawOutput = _insAndOutsSlice.slice(_numIns*TransactionInputLength + i*TransactionOutputLength,
_numIns*TransactionInputLength + (i+1)*TransactionOutputLength).toBytes();
TransactionOutput memory output = transactionOutputFromBytes(rawOutput);
if (output.outputNumberInTX == 255) {
continue;
}
require(output.outputNumberInTX == i);
_TX.outputs[i] = output;
}
return true;
}
function transactionInputFromBytes(bytes _rawInput) internal view returns(TransactionInput memory input) {
require(_rawInput.length == TransactionInputLength);
uint32 blockNumber = uint32(extract4(_rawInput,0));
uint32 txNumberInBlock = uint32(extract4(_rawInput, BlockNumberLength));
uint8 outputNumberInTX = uint8(extract1(_rawInput, BlockNumberLength + TxNumberLength));
uint256 amount = uint256(extract32(_rawInput, BlockNumberLength + TxNumberLength + TxOutputNumberLength));
input = TransactionInput({
blockNumber: blockNumber,
txNumberInBlock: txNumberInBlock,
outputNumberInTX: outputNumberInTX,
amount: amount
});
return input;
}
function transactionOutputFromBytes(bytes _rawOutput) internal view returns(TransactionOutput memory output) {
require(_rawOutput.length == TransactionOutputLength);
address recipient = address(extract20(_rawOutput, 0));
uint8 outputNumberInTX = uint8(extract1(_rawOutput, 20));
uint256 amount = uint256(extract32(_rawOutput, 20 + TxOutputNumberLength));
output = TransactionOutput({
recipient: recipient,
outputNumberInTX: outputNumberInTX,
amount: amount
});
return output;
}
function createPersonalMessageTypeHash(bytes memory message) internal view returns (bytes32 msgHash) {
// bytes memory prefixBytes = "\x19Ethereum Signed Message:\n";
bytes memory lengthBytes = message.length.uintToBytes();
// bytes memory prefix = prefixBytes.concat(lengthBytes);
bytes memory prefix = PersonalMessagePrefixBytes.concat(lengthBytes);
return keccak256(prefix, message);
}
function recoverTXsigner(bytes memory txData, uint8 v, bytes32 r, bytes32 s, uint256 txType) internal view returns (address signer) {
bytes memory sliceNoNumberNoSignatureParts = txData.slice(TxNumberLength, TxLengthForType[txType] - SignatureLength).toBytes();
bytes32 persMessageHashWithoutNumber = createPersonalMessageTypeHash(sliceNoNumberNoSignatureParts);
signer = ecrecover(persMessageHashWithoutNumber, v, r, s);
return signer;
}
function checkProof(bytes32 root, bytes data, bytes proof, bool convertToMessageHash) view public returns (bool) {
bytes32 h;
if (convertToMessageHash) {
h = createPersonalMessageTypeHash(data);
} else {
h = keccak256(data);
}
bytes32 elProvided;
uint8 rightElementProvided;
uint32 loc;
uint32 elLoc;
for (uint32 i = 32; i <= uint32(proof.length); i += 33) {
assembly {
loc := proof
elLoc := add(loc, add(i, 1))
elProvided := mload(elLoc)
}
rightElementProvided = uint8(bytes1(0xff)&proof[i-32]);
if (rightElementProvided > 0) {
h = keccak256(h, elProvided);
} else {
h = keccak256(elProvided, h);
}
}
return h == root;
}
function makeTransactionIndex(uint32 _blockNumber, uint32 _txNumberInBlock, uint8 _outputNumberInTX) pure public returns (uint256 index) {
index = uint256(_blockNumber) << ((TxNumberLength + TxTypeLength)*8) + uint256(_txNumberInBlock) << (TxTypeLength*8) + uint256(_outputNumberInTX);
return index;
}
}
|
Create a new slice from the given starting position. -len(slice) <= 'startpos' <= 'len(slice)' self The slice. startpos The starting position. return The new slice.
|
function slice(Slice memory self, int startpos) internal pure returns (Slice memory newSlice) {
uint startpos_;
uint length = self._unsafe_length;
if (startpos >= 0) {
startpos_ = uint(startpos);
if (startpos_ > length)
revert();
startpos_ = uint(-startpos);
if (startpos_ > length)
revert();
startpos_ = length - startpos_;
}
assembly {
length := sub(length, startpos_)
let newMemPtr := mul(add(mload(self), startpos_), iszero(iszero(length)))
mstore(newSlice, newMemPtr)
mstore(add(newSlice, 0x20), length)
}
}
| 7,218,487
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/IAccessControl.sol";
/**
* @dev This contract is fully forked from OpenZeppelin `AccessControlUpgradeable`.
* The only difference is the removal of the ERC165 implementation as it's not
* needed in Angle.
*
* Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, IAccessControl {
function __AccessControl_init() internal initializer {
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, msg.sender);
_;
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external override {
require(account == msg.sender, "71");
_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 {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) internal {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, msg.sender);
}
}
function _revokeRole(bytes32 role, address account) internal {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, msg.sender);
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IAccessControl
/// @author Forked from OpenZeppelin
/// @notice Interface for `AccessControl` contracts
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
interface IAngleMiddlemanGauge {
function notifyReward(address gauge, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
interface IGaugeController {
//solhint-disable-next-line
function gauge_types(address addr) external view returns (int128);
//solhint-disable-next-line
function gauge_relative_weight_write(address addr, uint256 timestamp) external returns (uint256);
//solhint-disable-next-line
function gauge_relative_weight(address addr, uint256 timestamp) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
interface ILiquidityGauge {
// solhint-disable-next-line
function deposit_reward_token(address _rewardToken, uint256 _amount) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title IStakingRewardsFunctions
/// @author Angle Core Team
/// @notice Interface for the staking rewards contract that interact with the `RewardsDistributor` contract
interface IStakingRewardsFunctions {
function notifyRewardAmount(uint256 reward) external;
function recoverERC20(
address tokenAddress,
address to,
uint256 tokenAmount
) external;
function setNewRewardsDistribution(address newRewardsDistribution) external;
}
/// @title IStakingRewards
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables
interface IStakingRewards is IStakingRewardsFunctions {
function rewardToken() external view returns (IERC20);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "./AngleDistributorEvents.sol";
/// @title AngleDistributor
/// @author Forked from contracts developed by Curve and Frax and adapted by Angle Core Team
/// - ERC20CRV.vy (https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/ERC20CRV.vy)
/// - FraxGaugeFXSRewardsDistributor.sol (https://github.com/FraxFinance/frax-solidity/blob/master/src/hardhat/contracts/Curve/FraxGaugeFXSRewardsDistributor.sol)
/// @notice All the events used in `AngleDistributor` contract
contract AngleDistributor is AngleDistributorEvents, ReentrancyGuardUpgradeable, AccessControlUpgradeable {
using SafeERC20 for IERC20;
/// @notice Role for governors only
bytes32 public constant GOVERNOR_ROLE = keccak256("GOVERNOR_ROLE");
/// @notice Role for the guardian
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
/// @notice Length of a week in seconds
uint256 public constant WEEK = 3600 * 24 * 7;
/// @notice Time at which the emission rate is updated
uint256 public constant RATE_REDUCTION_TIME = WEEK;
/// @notice Reduction of the emission rate
uint256 public constant RATE_REDUCTION_COEFFICIENT = 1007827884862117171; // 1.5 ^ (1/52) * 10**18
/// @notice Base used for computation
uint256 public constant BASE = 10**18;
/// @notice Maps the address of a gauge to the last time this gauge received rewards
mapping(address => uint256) public lastTimeGaugePaid;
/// @notice Maps the address of a gauge to whether it was killed or not
/// A gauge killed in this contract cannot receive any rewards
mapping(address => bool) public killedGauges;
/// @notice Maps the address of a type >= 2 gauge to a delegate address responsible
/// for giving rewards to the actual gauge
mapping(address => address) public delegateGauges;
/// @notice Maps the address of a gauge delegate to whether this delegate supports the `notifyReward` interface
/// and is therefore built for automation
mapping(address => bool) public isInterfaceKnown;
/// @notice Address of the ANGLE token given as a reward
IERC20 public rewardToken;
/// @notice Address of the `GaugeController` contract
IGaugeController public controller;
/// @notice Address responsible for pulling rewards of type >= 2 gauges and distributing it to the
/// associated contracts if there is not already an address delegated for this specific contract
address public delegateGauge;
/// @notice ANGLE current emission rate, it is first defined in the initializer and then updated every week
uint256 public rate;
/// @notice Timestamp at which the current emission epoch started
uint256 public startEpochTime;
/// @notice Amount of ANGLE tokens distributed through staking at the start of the epoch
/// This is an informational variable used to track how much has been distributed through liquidity mining
uint256 public startEpochSupply;
/// @notice Index of the current emission epoch
/// Here also, this variable is not useful per se inside the smart contracts of the protocol, it is
/// just an informational variable
uint256 public miningEpoch;
/// @notice Whether ANGLE distribution through this contract is on or no
bool public distributionsOn;
/// @notice Constructor of the contract
/// @param _rewardToken Address of the ANGLE token
/// @param _controller Address of the GaugeController
/// @param _initialRate Initial ANGLE emission rate
/// @param _startEpochSupply Amount of ANGLE tokens already distributed via liquidity mining
/// @param governor Governor address of the contract
/// @param guardian Address of the guardian of this contract
/// @param _delegateGauge Address that will be used to pull rewards for type 2 gauges
/// @dev After this contract is created, the correct amount of ANGLE tokens should be transferred to the contract
/// @dev The `_delegateGauge` can be the zero address
function initialize(
address _rewardToken,
address _controller,
uint256 _initialRate,
uint256 _startEpochSupply,
address governor,
address guardian,
address _delegateGauge
) external initializer {
require(
_controller != address(0) && _rewardToken != address(0) && guardian != address(0) && governor != address(0),
"0"
);
rewardToken = IERC20(_rewardToken);
controller = IGaugeController(_controller);
startEpochSupply = _startEpochSupply;
miningEpoch = 0;
// Some ANGLE tokens should be sent to the contract directly after initialization
rate = _initialRate;
delegateGauge = _delegateGauge;
distributionsOn = false;
startEpochTime = block.timestamp;
_setRoleAdmin(GOVERNOR_ROLE, GOVERNOR_ROLE);
_setRoleAdmin(GUARDIAN_ROLE, GOVERNOR_ROLE);
_setupRole(GUARDIAN_ROLE, guardian);
_setupRole(GOVERNOR_ROLE, governor);
_setupRole(GUARDIAN_ROLE, governor);
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
// ======================== Internal Functions =================================
/// @notice Internal function to distribute rewards to a gauge
/// @param gaugeAddr Address of the gauge to distribute rewards to
/// @return weeksElapsed Weeks elapsed since the last call
/// @return rewardTally Amount of rewards distributed to the gauge
/// @dev The reason for having an internal function is that it's called by the `distributeReward` and the
/// `distributeRewardToMultipleGauges`
/// @dev Although they would need to be performed all the time this function is called, this function does not
/// contain checks on whether distribution is on, and on whether rate should be reduced. These are done in each external
/// function calling this function for gas efficiency
function _distributeReward(address gaugeAddr) internal returns (uint256 weeksElapsed, uint256 rewardTally) {
// Checking if the gauge has been added or if it still possible to distribute rewards to this gauge
int128 gaugeType = IGaugeController(controller).gauge_types(gaugeAddr);
require(gaugeType >= 0 && !killedGauges[gaugeAddr], "110");
// Calculate the elapsed time in weeks.
uint256 lastTimePaid = lastTimeGaugePaid[gaugeAddr];
// Edge case for first reward for this gauge
if (lastTimePaid == 0) {
weeksElapsed = 1;
if (gaugeType == 0) {
// We give a full approval for the gauges with type zero which correspond to the staking
// contracts of the protocol
rewardToken.safeApprove(gaugeAddr, type(uint256).max);
}
} else {
// Truncation desired
weeksElapsed = (block.timestamp - lastTimePaid) / WEEK;
// Return early here for 0 weeks instead of throwing, as it could have bad effects in other contracts
if (weeksElapsed == 0) {
return (0, 0);
}
}
rewardTally = 0;
// We use this variable to keep track of the emission rate across different weeks
uint256 weeklyRate = rate;
for (uint256 i = 0; i < weeksElapsed; i++) {
uint256 relWeightAtWeek;
if (i == 0) {
// Mutative, for the current week: makes sure the weight is checkpointed. Also returns the weight.
relWeightAtWeek = controller.gauge_relative_weight_write(gaugeAddr, block.timestamp);
} else {
// View
relWeightAtWeek = controller.gauge_relative_weight(gaugeAddr, (block.timestamp - WEEK * i));
}
rewardTally += (weeklyRate * relWeightAtWeek * WEEK) / BASE;
// To get the rate of the week prior from the current rate we just have to multiply by the weekly division
// factor
// There may be some precisions error: inferred previous values of the rate may be different to what we would
// have had if the rate had been computed correctly in these weeks: we expect from empirical observations
// this `weeklyRate` to be inferior to what the `rate` would have been
weeklyRate = (weeklyRate * RATE_REDUCTION_COEFFICIENT) / BASE;
}
// Update the last time paid, rounded to the closest week
// in order not to have an ever moving time on when to call this function
lastTimeGaugePaid[gaugeAddr] = (block.timestamp / WEEK) * WEEK;
// If the `gaugeType >= 2`, this means that the gauge is a gauge on another chain (and corresponds to tokens
// that need to be bridged) or is associated to an external contract of the Angle Protocol
if (gaugeType >= 2) {
// If it is defined, we use the specific delegate attached to the gauge
address delegate = delegateGauges[gaugeAddr];
if (delegate == address(0)) {
// If not, we check if a delegate common to all gauges with type >= 2 can be used
delegate = delegateGauge;
}
if (delegate != address(0)) {
// In the case where the gauge has a delegate (specific or not), then rewards are transferred to this gauge
rewardToken.safeTransfer(delegate, rewardTally);
// If this delegate supports a specific interface, then rewards sent are notified through this
// interface
if (isInterfaceKnown[delegate]) {
IAngleMiddlemanGauge(delegate).notifyReward(gaugeAddr, rewardTally);
}
} else {
rewardToken.safeTransfer(gaugeAddr, rewardTally);
}
} else if (gaugeType == 1) {
// This is for the case of Perpetual contracts which need to be able to receive their reward tokens
rewardToken.safeTransfer(gaugeAddr, rewardTally);
IStakingRewards(gaugeAddr).notifyRewardAmount(rewardTally);
} else {
// Mainnet: Pay out the rewards directly to the gauge
ILiquidityGauge(gaugeAddr).deposit_reward_token(address(rewardToken), rewardTally);
}
emit RewardDistributed(gaugeAddr, rewardTally);
}
/// @notice Updates mining rate and supply at the start of the epoch
/// @dev Any modifying mining call must also call this
/// @dev It is possible that more than one week past between two calls of this function, and for this reason
/// this function has been slightly modified from Curve implementation by Angle Team
function _updateMiningParameters() internal {
// When entering this function, we always have: `(block.timestamp - startEpochTime) / RATE_REDUCTION_TIME >= 1`
uint256 epochDelta = (block.timestamp - startEpochTime) / RATE_REDUCTION_TIME;
// Storing intermediate values for the rate and for the `startEpochSupply`
uint256 _rate = rate;
uint256 _startEpochSupply = startEpochSupply;
startEpochTime += RATE_REDUCTION_TIME * epochDelta;
miningEpoch += epochDelta;
for (uint256 i = 0; i < epochDelta; i++) {
// Updating the intermediate values of the `startEpochSupply`
_startEpochSupply += _rate * RATE_REDUCTION_TIME;
_rate = (_rate * BASE) / RATE_REDUCTION_COEFFICIENT;
}
rate = _rate;
startEpochSupply = _startEpochSupply;
emit UpdateMiningParameters(block.timestamp, _rate, _startEpochSupply);
}
/// @notice Toggles the fact that a gauge delegate can be used for automation or not and therefore supports
/// the `notifyReward` interface
/// @param _delegateGauge Address of the gauge to change
function _toggleInterfaceKnown(address _delegateGauge) internal {
bool isInterfaceKnownMem = isInterfaceKnown[_delegateGauge];
isInterfaceKnown[_delegateGauge] = !isInterfaceKnownMem;
emit InterfaceKnownToggled(_delegateGauge, !isInterfaceKnownMem);
}
// ================= Permissionless External Functions =========================
/// @notice Distributes rewards to a staking contract (also called gauge)
/// @param gaugeAddr Address of the gauge to send tokens too
/// @return weeksElapsed Number of weeks elapsed since the last time rewards were distributed
/// @return rewardTally Amount of tokens sent to the gauge
/// @dev Anyone can call this function to distribute rewards to the different staking contracts
function distributeReward(address gaugeAddr) external nonReentrant returns (uint256, uint256) {
// Checking if distribution is on
require(distributionsOn == true, "109");
// Updating rate distribution parameters if need be
if (block.timestamp >= startEpochTime + RATE_REDUCTION_TIME) {
_updateMiningParameters();
}
return _distributeReward(gaugeAddr);
}
/// @notice Distributes rewards to multiple staking contracts
/// @param gauges Addresses of the gauge to send tokens too
/// @dev Anyone can call this function to distribute rewards to the different staking contracts
/// @dev Compared with the `distributeReward` function, this function sends rewards to multiple
/// contracts at the same time
function distributeRewardToMultipleGauges(address[] memory gauges) external nonReentrant {
// Checking if distribution is on
require(distributionsOn == true, "109");
// Updating rate distribution parameters if need be
if (block.timestamp >= startEpochTime + RATE_REDUCTION_TIME) {
_updateMiningParameters();
}
for (uint256 i = 0; i < gauges.length; i++) {
_distributeReward(gauges[i]);
}
}
/// @notice Updates mining rate and supply at the start of the epoch
/// @dev Callable by any address, but only once per epoch
function updateMiningParameters() external {
require(block.timestamp >= startEpochTime + RATE_REDUCTION_TIME, "108");
_updateMiningParameters();
}
// ========================= Governor Functions ================================
/// @notice Withdraws ERC20 tokens that could accrue on this contract
/// @param tokenAddress Address of the ERC20 token to withdraw
/// @param to Address to transfer to
/// @param amount Amount to transfer
/// @dev Added to support recovering LP Rewards and other mistaken tokens
/// from other systems to be distributed to holders
/// @dev This function could also be used to recover ANGLE tokens in case the rate got smaller
function recoverERC20(
address tokenAddress,
address to,
uint256 amount
) external onlyRole(GOVERNOR_ROLE) {
// If the token is the ANGLE token, we need to make sure that governance is not going to withdraw
// too many tokens and that it'll be able to sustain the weekly distribution forever
// This check assumes that `distributeReward` has been called for gauges and that there are no gauges
// which have not received their past week's rewards
if (tokenAddress == address(rewardToken)) {
uint256 currentBalance = rewardToken.balanceOf(address(this));
// The amount distributed till the end is `rate * WEEK / (1 - RATE_REDUCTION_FACTOR)` where
// `RATE_REDUCTION_FACTOR = BASE / RATE_REDUCTION_COEFFICIENT` which translates to:
require(
currentBalance >=
((rate * RATE_REDUCTION_COEFFICIENT) * WEEK) / (RATE_REDUCTION_COEFFICIENT - BASE) + amount,
"4"
);
}
IERC20(tokenAddress).safeTransfer(to, amount);
emit Recovered(tokenAddress, to, amount);
}
/// @notice Sets a new gauge controller
/// @param _controller Address of the new gauge controller
function setGaugeController(address _controller) external onlyRole(GOVERNOR_ROLE) {
require(_controller != address(0), "0");
controller = IGaugeController(_controller);
emit GaugeControllerUpdated(_controller);
}
/// @notice Sets a new delegate gauge for pulling rewards of a type >= 2 gauges or of all type >= 2 gauges
/// @param gaugeAddr Gauge to change the delegate of
/// @param _delegateGauge Address of the new gauge delegate related to `gaugeAddr`
/// @param toggleInterface Whether we should toggle the fact that the `_delegateGauge` is built for automation or not
/// @dev This function can be used to remove delegating or introduce the pulling of rewards to a given address
/// @dev If `gaugeAddr` is the zero address, this function updates the delegate gauge common to all gauges with type >= 2
/// @dev The `toggleInterface` parameter has been added for convenience to save one transaction when adding a gauge delegate
/// which supports the `notifyReward` interface
function setDelegateGauge(
address gaugeAddr,
address _delegateGauge,
bool toggleInterface
) external onlyRole(GOVERNOR_ROLE) {
if (gaugeAddr != address(0)) {
delegateGauges[gaugeAddr] = _delegateGauge;
} else {
delegateGauge = _delegateGauge;
}
emit DelegateGaugeUpdated(gaugeAddr, _delegateGauge);
if (toggleInterface) {
_toggleInterfaceKnown(_delegateGauge);
}
}
/// @notice Changes the ANGLE emission rate
/// @param _newRate New ANGLE emission rate
/// @dev It is important to be super wary when calling this function and to make sure that `distributeReward`
/// has been called for all gauges in the past weeks. If not, gauges may get an incorrect distribution of ANGLE rewards
/// for these past weeks based on the new rate and not on the old rate
/// @dev Governance should thus make sure to call this function rarely and when it does to do it after the weekly `distributeReward`
/// calls for all existing gauges
/// @dev As this function assumes that `distributeReward` has been called during the week, it also assumes that the `startEpochSupply`
/// parameter has been put up to date
function setRate(uint256 _newRate) external onlyRole(GOVERNOR_ROLE) {
// Checking if the new rate is compatible with the amount of ANGLE tokens this contract has in balance
// This check assumes, like this function, that `distributeReward` has correctly been called before
require(
rewardToken.balanceOf(address(this)) >=
((_newRate * RATE_REDUCTION_COEFFICIENT) * WEEK) / (RATE_REDUCTION_COEFFICIENT - BASE),
"4"
);
rate = _newRate;
emit RateUpdated(_newRate);
}
/// @notice Toggles the status of a gauge to either killed or unkilled
/// @param gaugeAddr Gauge to toggle the status of
/// @dev It is impossible to kill a gauge in the `GaugeController` contract, for this reason killing of gauges
/// takes place in the `AngleDistributor` contract
/// @dev This means that people could vote for a gauge in the gauge controller contract but that rewards are not going
/// to be distributed to it in the end: people would need to remove their weights on the gauge killed to end the diminution
/// in rewards
/// @dev In the case of a gauge being killed, this function resets the timestamps at which this gauge has been approved and
/// disapproves the gauge to spend the token
/// @dev It should be cautiously called by governance as it could result in less ANGLE overall rewards than initially planned
/// if people do not remove their voting weights to the killed gauge
function toggleGauge(address gaugeAddr) external onlyRole(GOVERNOR_ROLE) {
bool gaugeKilledMem = killedGauges[gaugeAddr];
if (!gaugeKilledMem) {
delete lastTimeGaugePaid[gaugeAddr];
rewardToken.safeApprove(gaugeAddr, 0);
}
killedGauges[gaugeAddr] = !gaugeKilledMem;
emit GaugeToggled(gaugeAddr, !gaugeKilledMem);
}
// ========================= Guardian Function =================================
/// @notice Halts or activates distribution of rewards
function toggleDistributions() external onlyRole(GUARDIAN_ROLE) {
bool distributionsOnMem = distributionsOn;
distributionsOn = !distributionsOnMem;
emit DistributionsToggled(!distributionsOnMem);
}
/// @notice Notifies that the interface of a gauge delegate is known or has changed
/// @param _delegateGauge Address of the gauge to change
/// @dev Gauge delegates that are built for automation should be toggled
function toggleInterfaceKnown(address _delegateGauge) external onlyRole(GUARDIAN_ROLE) {
_toggleInterfaceKnown(_delegateGauge);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "../interfaces/IGaugeController.sol";
import "../interfaces/ILiquidityGauge.sol";
import "../interfaces/IAngleMiddlemanGauge.sol";
import "../interfaces/IStakingRewards.sol";
import "../external/AccessControlUpgradeable.sol";
/// @title AngleDistributorEvents
/// @author Angle Core Team
/// @notice All the events used in `AngleDistributor` contract
contract AngleDistributorEvents {
event DelegateGaugeUpdated(address indexed _gaugeAddr, address indexed _delegateGauge);
event DistributionsToggled(bool _distributionsOn);
event GaugeControllerUpdated(address indexed _controller);
event GaugeToggled(address indexed gaugeAddr, bool newStatus);
event InterfaceKnownToggled(address indexed _delegateGauge, bool _isInterfaceKnown);
event RateUpdated(uint256 _newRate);
event Recovered(address indexed tokenAddress, address indexed to, uint256 amount);
event RewardDistributed(address indexed gaugeAddr, uint256 rewardTally);
event UpdateMiningParameters(uint256 time, uint256 rate, uint256 supply);
}
|
Distributes rewards to a staking contract (also called gauge) gaugeAddr Address of the gauge to send tokens too return weeksElapsed Number of weeks elapsed since the last time rewards were distributed return rewardTally Amount of tokens sent to the gauge Anyone can call this function to distribute rewards to the different staking contracts Checking if distribution is on Updating rate distribution parameters if need be
|
function distributeReward(address gaugeAddr) external nonReentrant returns (uint256, uint256) {
require(distributionsOn == true, "109");
if (block.timestamp >= startEpochTime + RATE_REDUCTION_TIME) {
_updateMiningParameters();
}
return _distributeReward(gaugeAddr);
}
| 5,933,732
|
/**
*Submitted for verification at Etherscan.io on 2021-11-28
*/
// 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);
}
/**
* @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 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);
}
/**
* @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);
}
/**
* @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);
}
}
}
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev 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 {}
}
/**
* @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 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;
// }
}
}
library CustomString {
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory) {
return strConcat(_a, _b, "", "", "");
}
function uint2str( uint256 _i ) internal pure returns (string memory str) {
if (_i == 0)
{
return "0";
}
uint256 j = _i;
uint256 length;
while (j != 0)
{
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint256 k = length;
j = _i;
while (j != 0)
{
bstr[--k] = bytes1(uint8(48 + j % 10));
j /= 10;
}
str = string(bstr);
}
}
contract HellDemons is ERC721, Ownable {
using SafeMath for uint256;
uint256 public currentSupply = 0;
uint256 public totalSupply = 6666;
uint256 public mintPrice = 0.06 ether; // ETH
uint256 public devFee = 20; // 2% with 1000 unit
address public devWallet = 0x5eacBb8267458B6bAC84D4019Bb64CC1a35b248E;
address public giveaway = 0x71CB438EA19af946e639d7845681E7ca8f4fe01a;
uint256 public numOfGiveaway = 66;
uint256 public maxMintNumber = 6;
string baseTokenURI = "https://ipfs.helldemons.io/metadata/";
bool public paused = true;
mapping (address=>uint256) private _tokenBalance;
bool public presale = true;
uint256 public presalePrice = 0.05 ether;
uint256 public presaleAmount = 666;
uint256 public presaleMaxMintNumber = 6;
// team addresses
address[] team = [
0xF9B28B8Fc1Dc4236392db45d8749b1E11aa96F0E, // Kindie
0xfE358a267a504c3B8887677013ADE56E209547b8, // Lucio
0x11985aDF71a48c1b0A6254f16cD2d7211De055E7, // Konraad
0x75Bc3aBA468CCc876208Cd53991A9dc136d8196b, // Tylte
0xe4B038C90F2eAeC5AF8562ff021cC4f2d4D76844, // Byok
devWallet
];
struct Token {
uint256 tokenId;
address creator;
address owner;
string uri;
}
mapping(uint256=>Token) private tokens;
mapping(address=>bool) public whitelist;
event TokenMint(address indexed to, Token _token);
event SetPrice(uint256 _value);
event MaxMintNumber(uint256 _value);
event ChangePaused(bool _value);
event ChangePresale(bool _value);
event SetPresalePrice(uint256 _value);
event MaxPresaleNumber(uint256 _value);
constructor() ERC721("Hell Demons", "$HELLD") {
mintByTeam();
}
function changePaused() public onlyOwner {
paused = !paused;
emit ChangePaused(paused);
}
function setMintPrice(uint256 _mintPrice) public onlyOwner {
mintPrice = _mintPrice;
emit SetPrice(_mintPrice);
}
function setMaxMintNumber(uint256 _maxMintNumber) public onlyOwner {
require(_maxMintNumber <= 20, "Too many tokens for one mint!");
maxMintNumber = _maxMintNumber;
emit MaxMintNumber(maxMintNumber);
}
function changePresale() public onlyOwner {
presale = !presale;
emit ChangePresale(presale);
}
function setPresalePrice(uint256 _presalePrice) public onlyOwner {
presalePrice = _presalePrice;
emit SetPresalePrice(presalePrice);
}
function setMaxPresaleNumber(uint256 _maxPresaleNumber) public onlyOwner {
presaleMaxMintNumber = _maxPresaleNumber;
emit MaxPresaleNumber(presaleMaxMintNumber);
}
function setBaseTokenURI(string memory _baseTokenURI) public onlyOwner {
baseTokenURI = _baseTokenURI;
}
function createTokenURI(uint256 tokenId) public view returns(string memory) {
return CustomString.strConcat(baseTokenURI, CustomString.uint2str(tokenId));
}
function mintByTeam() internal onlyOwner {
uint256 _index = currentSupply;
currentSupply += team.length;
for(uint256 i = 1; i <= team.length; i++) {
Token storage newToken = tokens[_index.add(i)];
newToken.tokenId = _index.add(i);
newToken.creator = team[i - 1];
newToken.owner = team[i - 1];
newToken.uri = createTokenURI(_index.add(i));
_safeMint(team[i - 1], _index.add(i));
_tokenBalance[team[i - 1]] += 1;
emit TokenMint(team[i - 1], newToken);
}
}
function mintForGiveaway() external onlyOwner {
uint256 _index = currentSupply;
require(_tokenBalance[giveaway] < numOfGiveaway, "Exceed for giveaway");
uint256 numberOfMint = numOfGiveaway.sub(_tokenBalance[giveaway]);
if (numberOfMint > 20) numberOfMint = 20;
currentSupply += numberOfMint;
for(uint256 i = 1; i <= numberOfMint; i++) {
Token storage newToken = tokens[_index.add(i)];
newToken.tokenId = _index.add(i);
newToken.creator = giveaway;
newToken.owner = giveaway;
newToken.uri = createTokenURI(_index.add(i));
_safeMint(giveaway, _index.add(i));
_tokenBalance[giveaway] += 1;
emit TokenMint(giveaway, newToken);
}
}
function setAddressGiveaway(address _giveawayAddress) public onlyOwner {
giveaway = _giveawayAddress;
}
function setNumOfGiveaway(uint256 _numOfGiveaway) public onlyOwner {
numOfGiveaway = _numOfGiveaway;
}
function addWhitelist(address[] memory accounts) public onlyOwner {
for (uint256 i = 0; i < accounts.length; i++) {
whitelist[accounts[i]] = true;
}
}
function removeWhitelist(address[] memory accounts) public onlyOwner {
for (uint256 i = 0; i < accounts.length; i++) {
whitelist[accounts[i]] = false;
}
}
function mintDemon(uint256 _numberOfTokens) public payable {
uint256 price = mintPrice;
if (presale) {
require(whitelist[_msgSender()], "You are not in whitelist");
require(_numberOfTokens <= presaleMaxMintNumber, "Unable to mint exceed number of demons per mint.");
require(_tokenBalance[_msgSender()].add(_numberOfTokens) <= presaleMaxMintNumber, "You have a demon already.");
require(currentSupply.add(_numberOfTokens) < presaleAmount.add(numOfGiveaway).add(6), "No tokens available for presale");
price = presalePrice;
} else {
require(!paused, "Minting is paused");
require(_numberOfTokens <= maxMintNumber, "Too many tokens to mint at once.");
require(_tokenBalance[_msgSender()].add(_numberOfTokens) <= maxMintNumber, "You have enough demons already.");
require(currentSupply.add(_numberOfTokens) <= totalSupply, "No tokens available for minting!");
}
require(msg.value >= price.mul(_numberOfTokens), "Amount is not enough!");
uint256 _index = currentSupply;
currentSupply += _numberOfTokens;
_tokenBalance[_msgSender()] += _numberOfTokens;
for (uint256 i = 1; i <= _numberOfTokens; i++) {
Token storage newToken = tokens[_index.add(i)];
newToken.tokenId = _index.add(i);
newToken.creator = _msgSender();
newToken.owner = _msgSender();
newToken.uri = createTokenURI(_index.add(i));
_safeMint(_msgSender(), _index.add(i));
emit TokenMint(_msgSender(), newToken);
}
}
function creatorOf(uint256 _tokenId) public view returns (address) {
return tokens[_tokenId].creator;
}
function balanceOf(address account) public view virtual override returns(uint256) {
return _tokenBalance[account];
}
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
require(_tokenId <= currentSupply, "ERC721Metadata: URI query for nonexistent token");
return tokens[_tokenId].uri;
}
function withdraw() public onlyOwner {
(bool hs, ) = payable(devWallet).call{value: address(this).balance * devFee / 1000}("");
require(hs);
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = tokens[tokenId].owner;
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function _transfer(address from, address to, uint256 tokenId) internal virtual override {
// check demon index is available
require(tokenId <= currentSupply, "Undefined tokenID!");
// check owner of demon
require(ownerOf(tokenId) == from, "Caller is not owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
tokens[tokenId].owner = to;
_tokenBalance[from]--;
_tokenBalance[to]++;
emit Transfer(from, to, tokenId);
}
}
|
check demon index is available check owner of demon
|
function _transfer(address from, address to, uint256 tokenId) internal virtual override {
require(tokenId <= currentSupply, "Undefined tokenID!");
require(ownerOf(tokenId) == from, "Caller is not owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
tokens[tokenId].owner = to;
_tokenBalance[from]--;
_tokenBalance[to]++;
emit Transfer(from, to, tokenId);
}
| 2,116,141
|
/**
*Submitted for verification at Etherscan.io on 2021-03-31
*/
// File: contracts/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
/**
* @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/IWCHI.sol
// Copyright (C) 2021 Autonomous Worlds Ltd
pragma solidity ^0.7.6;
/**
* @dev Interface for the wrapped CHI (WCHI) token.
*/
interface IWCHI is IERC20
{
/**
* @dev Burns the given number of tokens, reducing total supply.
*/
function burn (uint256 value) external;
/**
* @dev Increases the allowance of a given spender by the given amount.
*/
function increaseAllowance (address spender, uint256 addedValue)
external returns (bool);
/**
* @dev Decreases the allowance of a given spender by the given amount.
*/
function decreaseAllowance (address spender, uint256 removedValue)
external returns (bool);
}
// File: contracts/WCHI.sol
// Copyright (C) 2021 Autonomous Worlds Ltd
pragma solidity ^0.7.6;
/**
* @dev Wrapped CHI (WCHI) token. This contract is not upgradable and not
* owned, but it grants an initial supply to the contract creator. The Xaya
* team will hold these tokens, and give them out for CHI locked on the
* Xaya network. When WCHI tokens are returned, those CHI will be released
* again.
*/
contract WCHI is IWCHI
{
string public constant name = "Wrapped CHI";
string public constant symbol = "WCHI";
/** @dev Native CHI has 8 decimals (like BTC), we mimic that here. */
uint8 public constant decimals = 8;
/**
* @dev Initial supply of tokens minted. This is a bit larger than the
* real total supply of CHI.
*/
uint256 internal constant initialSupply = 78 * 10**6 * 10**decimals;
/**
* @dev Total supply of tokens. This includes tokens that are in the
* Xaya team's reserve, i.e. do not correspond to real CHI locked
* in the treasury.
*/
uint256 public override totalSupply;
/** @dev Balances of tokens per address. */
mapping (address => uint256) public override balanceOf;
/**
* @dev Allowances for accounts (second) to spend from the balance
* of an owner (first).
*/
mapping (address => mapping (address => uint256)) public override allowance;
/**
* @dev In the constructor, we grant the contract creator the initial balance.
* This is the only place where any address has special rights compared
* to all others.
*/
constructor ()
{
totalSupply = initialSupply;
balanceOf[msg.sender] = initialSupply;
emit Transfer (address (0), msg.sender, initialSupply);
}
/**
* @dev Sets the allowance afforded to the given spender by
* the message sender.
*/
function approve (address spender, uint256 value)
external override returns (bool)
{
setApproval (msg.sender, spender, value);
return true;
}
/**
* @dev Moves a given amount of tokens from the message sender's
* account to the recipient. If to is the zero address, then those
* tokens are burnt and reduce the total supply.
*/
function transfer (address to, uint256 value) external override returns (bool)
{
uncheckedTransfer (msg.sender, to, value);
return true;
}
/**
* @dev Moves a given amount of tokens from the sender account to the
* recipient. If from is not the message sender, then it needs to have
* sufficient allowance.
*/
function transferFrom (address from, address to, uint256 value)
external override returns (bool)
{
if (from != msg.sender)
{
/* Check for the allowance and reduce it. */
uint256 allowed = allowance[from][msg.sender];
if (allowed != type (uint256).max)
{
require (allowed >= value, "WCHI: allowance exceeded");
uint256 newAllowed = allowed - value;
setApproval (from, msg.sender, newAllowed);
}
}
uncheckedTransfer (from, to, value);
return true;
}
/**
* @dev Internal transfer implementation. This is used to implement transfer
* and transferFrom, and does not check that the sender is actually
* allowed to spend the tokens.
*/
function uncheckedTransfer (address from, address to, uint256 value) internal
{
require (to != address (0), "WCHI: transfer to zero address");
require (to != address (this), "WCHI: transfer to contract address");
deductBalance (from, value);
balanceOf[to] += value;
emit Transfer (from, to, value);
}
/**
* @dev Burns tokens from the sender's balance, reducing total supply.
*/
function burn (uint256 value) external override
{
deductBalance (msg.sender, value);
assert (totalSupply >= value);
totalSupply -= value;
emit Transfer (msg.sender, address (0), value);
}
/**
* @dev Increases the allowance of a given spender by a certain
* amount (rather than explicitly setting the new allowance). This fails
* if the new allowance would be at infinity (or overflow).
*/
function increaseAllowance (address spender, uint256 addedValue)
external override returns (bool)
{
uint256 allowed = allowance[msg.sender][spender];
uint256 increaseToInfinity = type (uint256).max - allowed;
require (addedValue < increaseToInfinity,
"WCHI: increase allowance overflow");
setApproval (msg.sender, spender, allowed + addedValue);
return true;
}
/**
* @dev Decreases the allowance of a given spender by a certain value.
* If the value is more than the current allowance, it is set to zero.
*/
function decreaseAllowance (address spender, uint256 removedValue)
external override returns (bool)
{
uint256 allowed = allowance[msg.sender][spender];
if (removedValue >= allowed)
setApproval (msg.sender, spender, 0);
else
setApproval (msg.sender, spender, allowed - removedValue);
return true;
}
/**
* @dev Internal helper function to check the balance of the given user
* and deduct the given amount.
*/
function deductBalance (address from, uint256 value) internal
{
uint256 balance = balanceOf[from];
require (balance >= value, "WCHI: insufficient balance");
balanceOf[from] = balance - value;
}
/**
* @dev Internal helper function to explicitly set the allowance of
* a spender without any checks, and emit the Approval event.
*/
function setApproval (address owner, address spender, uint256 value) internal
{
allowance[owner][spender] = value;
emit Approval (owner, spender, value);
}
}
|
Internal helper function to check the balance of the given user and deduct the given amount./
|
function deductBalance (address from, uint256 value) internal
{
uint256 balance = balanceOf[from];
require (balance >= value, "WCHI: insufficient balance");
balanceOf[from] = balance - value;
}
| 2,455,407
|
pragma solidity ^0.4.25;
// ----------------------------------------------------------------------------
//
// Symbol : CRP
// Name : Chiwoo Rotary Press
// Total supply: 8000000000
// Decimals : 18
// (c) by Team @ CRP 2018.
// ----------------------------------------------------------------------------
/**
* @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) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract owned {
address public owner;
constructor () public {
owner = msg.sender;
}
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 {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract CRP_ERC20 is owned {
using SafeMath for uint;
string public name = "Chiwoo Rotary Press";
string public symbol = "CRP";
uint8 public decimals = 18;
uint256 public totalSupply = 8000000000 * 10 ** uint256(decimals);
/// the price of tokenBuy
uint256 public TokenPerETHBuy = 1000;
/// the price of tokenSell
uint256 public TokenPerETHSell = 1000;
/// sell token is enabled
bool public SellTokenAllowed;
/// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => bool) public frozenAccount;
/// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
/// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/// This notifies clients about the new Buy price
event BuyRateChanged(uint256 oldValue, uint256 newValue);
/// This notifies clients about the new Sell price
event SellRateChanged(uint256 oldValue, uint256 newValue);
/// This notifies clients about the Buy Token
event BuyToken(address user, uint256 eth, uint256 token);
/// This notifies clients about the Sell Token
event SellToken(address user, uint256 eth, uint256 token);
/// Log the event about a deposit being made by an address and its amount
event LogDepositMade(address indexed accountAddress, uint amount);
/// This generates a public event on the blockchain that will notify clients
event FrozenFunds(address target, bool frozen);
event SellTokenAllowedEvent(bool isAllowed);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor () public {
balanceOf[owner] = totalSupply;
SellTokenAllowed = true;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint256 _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Check if sender is frozen
require(!frozenAccount[_from]);
// Check if recipient is frozen
require(!frozenAccount[_to]);
// Save this for an assertion in the future
uint256 previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(this, target, mintedAmount);
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* Set price function for Buy
*
* @param value the amount new Buy Price
*/
function setBuyRate(uint256 value) onlyOwner public {
require(value > 0);
emit BuyRateChanged(TokenPerETHBuy, value);
TokenPerETHBuy = value;
}
/**
* Set price function for Sell
*
* @param value the amount new Sell Price
*/
function setSellRate(uint256 value) onlyOwner public {
require(value > 0);
emit SellRateChanged(TokenPerETHSell, value);
TokenPerETHSell = value;
}
/**
* function for Buy Token
*/
function buy() payable public returns (uint amount){
require(msg.value > 0);
require(!frozenAccount[msg.sender]); // check sender is not frozen account
amount = ((msg.value.mul(TokenPerETHBuy)).mul( 10 ** uint256(decimals))).div(1 ether);
balanceOf[this] -= amount; // adds the amount to owner's
balanceOf[msg.sender] += amount;
emit Transfer(this,msg.sender ,amount);
return amount;
}
/**
* function for Sell Token
*/
function sell(uint amount) public returns (uint revenue){
require(balanceOf[msg.sender] >= amount); // checks if the sender has enough to sell
require(SellTokenAllowed); // check if the sender whitelist
require(!frozenAccount[msg.sender]); // check sender is not frozen account
balanceOf[this] += amount; // adds the amount to owner's balance
balanceOf[msg.sender] -= amount; // subtracts the amount from seller's balance
revenue = (amount.mul(1 ether)).div(TokenPerETHSell.mul(10 ** uint256(decimals))) ;
msg.sender.transfer(revenue); // sends ether to the seller: it's important to do this last to prevent recursion attacks
emit Transfer(msg.sender, this, amount); // executes an event reflecting on the change
return revenue; // ends function and returns
}
/**
* Deposit Ether in owner account, requires method is "payable"
*/
function deposit() public payable {
}
/**
*@notice Withdraw for Ether
*/
function withdraw(uint withdrawAmount) onlyOwner public {
if (withdrawAmount <= address(this).balance) {
owner.transfer(withdrawAmount);
}
}
function () public payable {
buy();
}
/**
* Enable Sell Token
*/
function enableSellToken() onlyOwner public {
SellTokenAllowed = true;
emit SellTokenAllowedEvent (true);
}
/**
* Disable Sell Token
*/
function disableSellToken() onlyOwner public {
SellTokenAllowed = false;
emit SellTokenAllowedEvent (false);
}
}
|
Disable Sell Token/
|
function disableSellToken() onlyOwner public {
SellTokenAllowed = false;
emit SellTokenAllowedEvent (false);
}
| 11,964,385
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma abicoder v2;
import "../../interfaces/IPendleCompoundForge.sol";
import "./../abstract/PendleMarketBase.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract PendleCompoundMarket is PendleMarketBase {
using Math for uint256;
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private globalLastExchangeRate;
constructor(
address _governanceManager,
address _xyt,
address _token
) PendleMarketBase(_governanceManager, _xyt, _token) {}
function _getExchangeRate() internal returns (uint256) {
return IPendleCompoundForge(forge).getExchangeRate(underlyingAsset);
}
function _afterBootstrap() internal override {
paramL = 1;
globalLastExchangeRate = _getExchangeRate();
}
/// @inheritdoc PendleMarketBase
/*
* Please refer to AaveMarket's _updateDueInterests to better understand this function
* The key difference between Aave & Compound is in Compound there is no compound effect for locked in asset
I.e: Only when the user use the cToken to redeem the underlyingAsset that he will enjoy the
compound effect
*/
function _updateDueInterests(address user) internal override {
// before calc the interest for users, updateParamL
_updateParamL();
uint256 _paramL = paramL;
uint256 userLastParamL = lastParamL[user];
if (userLastParamL == 0) {
lastParamL[user] = _paramL;
return;
}
uint256 principal = balanceOf(user);
uint256 interestValuePerLP = _paramL.sub(userLastParamL);
uint256 interestFromLp = principal.mul(interestValuePerLP).div(MULTIPLIER);
dueInterests[user] = dueInterests[user].add(interestFromLp);
lastParamL[user] = _paramL;
}
/// @inheritdoc PendleMarketBase
// Please refer to AaveMarket's _getFirstTermAndParamR to better understand this function
function _getFirstTermAndParamR(uint256 currentNYield)
internal
override
returns (uint256 firstTerm, uint256 paramR)
{
firstTerm = paramL;
paramR = currentNYield.sub(lastNYield);
globalLastExchangeRate = _getExchangeRate();
}
/// @inheritdoc PendleMarketBase
function _getIncomeIndexIncreaseRate() internal override returns (uint256 increaseRate) {
return _getExchangeRate().rdiv(globalLastExchangeRate).sub(Math.RONE);
}
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
import "./IPendleForge.sol";
interface IPendleCompoundForge is IPendleForge {
/**
@dev directly get the exchangeRate from Compound
*/
function getExchangeRate(address _underlyingAsset) external returns (uint256);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma abicoder v2;
import "../../interfaces/IPendleData.sol";
import "../../interfaces/IPendleMarket.sol";
import "../../interfaces/IPendleForge.sol";
import "../../interfaces/IPendleMarketFactory.sol";
import "../../interfaces/IPendleYieldToken.sol";
import "../../interfaces/IPendlePausingManager.sol";
import "../../periphery/WithdrawableV2.sol";
import "../../tokens/PendleBaseToken.sol";
import "../../libraries/MarketMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/**
@dev HIGH LEVEL PRINCIPAL:
* So most of the functions in market is only callable by Router, except view/pure functions.
If a function is non view/pure and is callable by anyone, it must be explicitly stated so
* Market will not do any yieldToken/baseToken transfer but instead will fill in the transfer array
and router will do them instead. (This is to reduce the number of approval users need to do)
* mint, burn will be done directly with users
*/
abstract contract PendleMarketBase is IPendleMarket, PendleBaseToken, WithdrawableV2 {
using Math for uint256;
using SafeMath for uint256;
using SafeERC20 for IERC20;
bytes32 public immutable override factoryId;
address internal immutable forge;
address public immutable override token;
address public immutable override xyt;
bool public bootstrapped;
string private constant NAME = "Pendle Market";
string private constant SYMBOL = "PENDLE-LPT";
uint256 private constant MINIMUM_LIQUIDITY = 10**3;
uint8 private constant DECIMALS = 18;
uint256 private constant LN_PI_PLUSONE = 1562071538258; // this is equal to Math.ln(Math.PI_PLUSONE,Math.RONE)
uint256 internal constant MULTIPLIER = 10**20;
// variables for LP interests calc
uint256 public paramL;
uint256 public lastNYield;
mapping(address => uint256) internal lastParamL;
mapping(address => uint256) internal dueInterests;
// paramK used for mintProtocolFee. ParamK = xytBal ^ xytWeight * tokenBal ^ tokenW
uint256 public lastParamK;
// the last block that we do curveShift
uint256 public lastCurveShiftBlock;
/*
* The reserveData will consist of 3 variables: xytBalance, tokenBalance & xytWeight
To save gas, we will pack these 3 variables into a single uint256 variable as follows:
Bit 148 -> 255: xytBalance
Bit 40 -> 147: tokenBalance
Bit 0 -> 39: xytWeight
tokenWeight = Math.RONE - xytWeight
Refer to writeReserveData and readReserveData for more details
*/
uint256 private reserveData;
uint256 private lastRelativePrice = Math.RONE;
uint256 private constant MASK_148_TO_255 = type(uint256).max ^ ((1 << 148) - 1);
uint256 private constant MASK_40_TO_147 = ((1 << 148) - 1) ^ ((1 << 40) - 1);
uint256 private constant MASK_0_TO_39 = ((1 << 40) - 1);
uint256 private constant MAX_TOKEN_RESERVE_BALANCE = (1 << 108) - 1;
/*
* the lockStartTime is set at the bootstrap time of the market, and will not be changed for the entire market duration
Once the market has been locked, only removeMarketLiquidityDual is allowed
* Why lock the market? Because when the time is very close to the end of the market, the ratio of weights are either
extremely big or small, which leads to high precision error
*/
uint256 public lockStartTime;
/* these variables are used often, so we get them once in the constructor
and save gas for retrieving them afterwards */
bytes32 private immutable forgeId;
address internal immutable underlyingAsset;
IERC20 private immutable underlyingYieldToken;
IPendleData private immutable data;
IPendlePausingManager private immutable pausingManager;
uint256 private immutable xytStartTime;
constructor(
address _governanceManager,
address _xyt,
address _token
)
PendleBaseToken(
address(IPendleYieldToken(_xyt).forge().router()),
NAME,
SYMBOL,
DECIMALS,
block.timestamp,
IPendleYieldToken(_xyt).expiry()
)
PermissionsV2(_governanceManager)
{
require(_xyt != address(0), "ZERO_ADDRESS");
require(_token != address(0), "ZERO_ADDRESS");
require(_token != IPendleYieldToken(_xyt).underlyingYieldToken(), "INVALID_TOKEN_PAIR");
IPendleForge _forge = IPendleYieldToken(_xyt).forge();
forge = address(_forge);
xyt = _xyt;
token = _token;
forgeId = _forge.forgeId();
underlyingAsset = IPendleYieldToken(_xyt).underlyingAsset();
underlyingYieldToken = IERC20(IPendleYieldToken(_xyt).underlyingYieldToken());
data = _forge.data();
pausingManager = _forge.data().pausingManager();
xytStartTime = IPendleYieldToken(_xyt).start();
factoryId = IPendleMarketFactory(msg.sender).marketFactoryId();
address _router = address(_forge.router());
IERC20(_xyt).safeApprove(_router, type(uint256).max);
IERC20(_token).safeApprove(_router, type(uint256).max);
}
// INVARIANT: All write functions, except for ERC20's approve(), increaseAllowance(), decreaseAllowance()
// must go through this check. This means that minting/burning/transferring of LP tokens is paused too.
function checkNotPaused() internal {
(bool paused, ) = pausingManager.checkMarketStatus(factoryId, address(this));
require(!paused, "MARKET_PAUSED");
}
/// Refer to the docs for reserveData
function readReserveData()
internal
view
returns (
uint256 xytBalance,
uint256 tokenBalance,
uint256 xytWeight,
uint256 tokenWeight
)
{
xytBalance = (reserveData & MASK_148_TO_255) >> 148;
tokenBalance = (reserveData & MASK_40_TO_147) >> 40;
xytWeight = reserveData & MASK_0_TO_39;
tokenWeight = Math.RONE - xytWeight;
}
/// parse an asset address to tokenReserve
/// _asset will only be either xyt or baseToken
function parseTokenReserveData(address _asset)
internal
view
returns (TokenReserve memory tokenReserve)
{
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight) =
readReserveData();
if (_asset == xyt) {
tokenReserve = TokenReserve(xytWeight, xytBalance);
} else {
tokenReserve = TokenReserve(tokenWeight, tokenBalance);
}
}
/// pass in a tokenReserve & the type of token (through _asset), update the reserveData
function updateReserveData(TokenReserve memory tokenReserve, address _asset) internal {
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight) =
readReserveData();
// Basically just update the weight & bal of the corresponding token & write the reserveData again
if (_asset == xyt) {
(xytWeight, xytBalance) = (tokenReserve.weight, tokenReserve.balance);
} else {
(tokenWeight, tokenBalance) = (tokenReserve.weight, tokenReserve.balance);
xytWeight = Math.RONE.sub(tokenWeight);
}
writeReserveData(xytBalance, tokenBalance, xytWeight);
}
/// Refer to the docs for reserveData
function writeReserveData(
uint256 xytBalance,
uint256 tokenBalance,
uint256 xytWeight
) internal {
require(0 < xytBalance && xytBalance <= MAX_TOKEN_RESERVE_BALANCE, "YT_BALANCE_ERROR");
require(
0 < tokenBalance && tokenBalance <= MAX_TOKEN_RESERVE_BALANCE,
"TOKEN_BALANCE_ERROR"
);
reserveData = (xytBalance << 148) | (tokenBalance << 40) | xytWeight;
}
// Only the marketEmergencyHandler can call this function, when its in emergencyMode
// this will allow a spender to spend the whole balance of the specified tokens
// the spender should ideally be a contract with logic for users to withdraw out their funds.
function setUpEmergencyMode(address spender) external override {
(, bool emergencyMode) = pausingManager.checkMarketStatus(factoryId, address(this));
require(emergencyMode, "NOT_EMERGENCY");
(address marketEmergencyHandler, , ) = pausingManager.marketEmergencyHandler();
require(msg.sender == marketEmergencyHandler, "NOT_EMERGENCY_HANDLER");
IERC20(xyt).safeApprove(spender, type(uint256).max);
IERC20(token).safeApprove(spender, type(uint256).max);
IERC20(underlyingYieldToken).safeApprove(spender, type(uint256).max);
}
function bootstrap(
address user,
uint256 initialXytLiquidity,
uint256 initialTokenLiquidity
) external override returns (PendingTransfer[2] memory transfers, uint256 exactOutLp) {
require(msg.sender == address(router), "ONLY_ROUTER");
checkNotPaused();
require(!bootstrapped, "ALREADY_BOOTSTRAPPED");
// market's lock params should be initialized at bootstrap time
_initializeLock();
// at the start of the market, xytWeight = tokenWeight = Math.RONE / 2
// As such, we will write it into the reserveData
writeReserveData(initialXytLiquidity, initialTokenLiquidity, Math.RONE / 2);
_updateLastParamK(); // update paramK since this is the first time it's set
emit Sync(initialXytLiquidity, Math.RONE / 2, initialTokenLiquidity);
_afterBootstrap();
// Taking inspiration from Uniswap, we will keep MINIMUM_LIQUIDITY in the market to make sure the market is always non-empty
exactOutLp = Math.sqrt(initialXytLiquidity.mul(initialTokenLiquidity)).sub(
MINIMUM_LIQUIDITY
);
// No one should possibly own a specific address like this 0x1
// We mint to 0x1 instead of 0x0 because sending to 0x0 is not permitted
_mint(address(0x1), MINIMUM_LIQUIDITY);
_mint(user, exactOutLp);
transfers[0].amount = initialXytLiquidity;
transfers[0].isOut = false;
transfers[1].amount = initialTokenLiquidity;
transfers[1].isOut = false;
lastCurveShiftBlock = block.number;
bootstrapped = true;
}
/**
* @notice Join the market by specifying the desired (and max) amount of xyts
* and tokens to put in.
* @param _desiredXytAmount amount of XYTs user wants to contribute
* @param _desiredTokenAmount amount of tokens user wants to contribute
* @param _xytMinAmount min amount of XYTs user wants to be able to contribute
* @param _tokenMinAmount min amount of tokens user wants to be able to contribute
* @dev no curveShift to save gas because this function
doesn't depend on weights of tokens
* Note: the logic of this function is similar to that of Uniswap
* Conditions:
* checkAddRemoveSwapClaimAllowed(false) is true
*/
function addMarketLiquidityDual(
address user,
uint256 _desiredXytAmount,
uint256 _desiredTokenAmount,
uint256 _xytMinAmount,
uint256 _tokenMinAmount
) external override returns (PendingTransfer[2] memory transfers, uint256 lpOut) {
checkAddRemoveSwapClaimAllowed(false);
// mint protocol fees before k is changed by a non-swap event (add liquidity)
_mintProtocolFees();
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) = readReserveData();
uint256 amountXytUsed;
uint256 amountTokenUsed = _desiredXytAmount.mul(tokenBalance).div(xytBalance);
if (amountTokenUsed <= _desiredTokenAmount) {
// using _desiredXytAmount to determine the LP and add liquidity
require(amountTokenUsed >= _tokenMinAmount, "INSUFFICIENT_TOKEN_AMOUNT");
amountXytUsed = _desiredXytAmount;
lpOut = _desiredXytAmount.mul(totalSupply()).div(xytBalance);
} else {
// using _desiredTokenAmount to determine the LP and add liquidity
amountXytUsed = _desiredTokenAmount.mul(xytBalance).div(tokenBalance);
require(amountXytUsed >= _xytMinAmount, "INSUFFICIENT_YT_AMOUNT");
amountTokenUsed = _desiredTokenAmount;
lpOut = _desiredTokenAmount.mul(totalSupply()).div(tokenBalance);
}
xytBalance = xytBalance.add(amountXytUsed);
transfers[0].amount = amountXytUsed;
transfers[0].isOut = false;
tokenBalance = tokenBalance.add(amountTokenUsed);
transfers[1].amount = amountTokenUsed;
transfers[1].isOut = false;
writeReserveData(xytBalance, tokenBalance, xytWeight);
_updateLastParamK(); // update paramK since it has changed due to a non-swap event
// Mint LP directly to the user
_mint(user, lpOut);
emit Sync(xytBalance, xytWeight, tokenBalance);
}
/**
* @notice Join the market by deposit token (single) and get liquidity token
* need to specify the desired amount of contributed token (xyt or token)
* and minimum output liquidity token
* @param _inToken address of token (xyt or token) user wants to contribute
* @param _exactIn amount of tokens (xyt or token) user wants to contribute
* @param _minOutLp min amount of liquidity token user expect to receive
* @dev curveShift needed since function operation relies on weights
*/
function addMarketLiquiditySingle(
address user,
address _inToken,
uint256 _exactIn,
uint256 _minOutLp
) external override returns (PendingTransfer[2] memory transfers, uint256 exactOutLp) {
checkAddRemoveSwapClaimAllowed(false);
// mint protocol fees before k is changed by a non-swap event (add liquidity)
_mintProtocolFees();
_curveShift();
/*
* Note that in theory we could do another _mintProtocolFee in this function
to take a portion of the swap fees for the implicit swap of this operation
* However, we have decided to not charge the protocol fees on the swap fees for this
operation.
* The user will still pay the swap fees, just that all the swap fees in the implicit swap
will all go back to the market (and shared among the LP holders)
*/
TokenReserve memory inTokenReserve = parseTokenReserveData(_inToken);
uint256 totalLp = totalSupply();
// Calc out amount of LP token.
exactOutLp = MarketMath._calcOutAmountLp(
_exactIn,
inTokenReserve,
data.swapFee(),
totalLp
);
require(exactOutLp >= _minOutLp, "HIGH_LP_OUT_LIMIT");
// Update reserves and operate underlying LP and inToken.
inTokenReserve.balance = inTokenReserve.balance.add(_exactIn);
transfers[0].amount = _exactIn;
transfers[0].isOut = false;
// repack data
updateReserveData(inTokenReserve, _inToken);
_updateLastParamK(); // update paramK since it has changed not due to swap
// Mint and push LP token.
_mint(user, exactOutLp);
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) = readReserveData(); // unpack data
emit Sync(xytBalance, xytWeight, tokenBalance);
}
/**
* @notice Exit the market by putting in the desired amount of LP tokens
* and getting back XYT and pair tokens.
* @dev no curveShift to save gas because this function
doesn't depend on weights of tokens
* @dev this function will never be locked since we always let users withdraw
their funds. That's why we skip time check in checkAddRemoveSwapClaimAllowed
*/
function removeMarketLiquidityDual(
address user,
uint256 _inLp,
uint256 _minOutXyt,
uint256 _minOutToken
) external override returns (PendingTransfer[2] memory transfers) {
checkAddRemoveSwapClaimAllowed(true);
// mint protocol fees before k is changed by a non-swap event (remove liquidity)
_mintProtocolFees();
uint256 totalLp = totalSupply();
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) = readReserveData(); // unpack data
// Calc and withdraw xyt token.
uint256 xytOut = _inLp.mul(xytBalance).div(totalLp);
uint256 tokenOut = _inLp.mul(tokenBalance).div(totalLp);
require(tokenOut >= _minOutToken, "INSUFFICIENT_TOKEN_OUT");
require(xytOut >= _minOutXyt, "INSUFFICIENT_YT_OUT");
xytBalance = xytBalance.sub(xytOut);
tokenBalance = tokenBalance.sub(tokenOut);
transfers[0].amount = xytOut;
transfers[0].isOut = true;
transfers[1].amount = tokenOut;
transfers[1].isOut = true;
writeReserveData(xytBalance, tokenBalance, xytWeight); // repack data
_updateLastParamK(); // update paramK since it has changed due to a non-swap event
_burn(user, _inLp);
emit Sync(xytBalance, xytWeight, tokenBalance);
}
/**
* @notice Exit the market by putting in the desired amount of LP tokens
* and getting back XYT or pair tokens.
* @param _outToken address of the token that user wants to get back
* @param _inLp the exact amount of liquidity token that user wants to put back
* @param _minOutAmountToken the minimum of token that user wants to get back
* @dev curveShift needed since function operation relies on weights
*/
function removeMarketLiquiditySingle(
address user,
address _outToken,
uint256 _inLp,
uint256 _minOutAmountToken
) external override returns (PendingTransfer[2] memory transfers) {
checkAddRemoveSwapClaimAllowed(false);
// mint protocol fees before k is changed by a non-swap event (remove liquidity)
_mintProtocolFees();
_curveShift();
/*
* Note that in theory we should do another _mintProtocolFee in this function
since this add single involves an implicit swap operation
* The reason we don't do that is same as in addMarketLiquiditySingle
*/
TokenReserve memory outTokenReserve = parseTokenReserveData(_outToken);
uint256 swapFee = data.swapFee();
uint256 totalLp = totalSupply();
uint256 outAmountToken =
MarketMath._calcOutAmountToken(outTokenReserve, totalLp, _inLp, swapFee);
require(outAmountToken >= _minOutAmountToken, "INSUFFICIENT_TOKEN_OUT");
outTokenReserve.balance = outTokenReserve.balance.sub(outAmountToken);
transfers[0].amount = outAmountToken;
transfers[0].isOut = true;
updateReserveData(outTokenReserve, _outToken);
_updateLastParamK(); // update paramK since it has changed by a non-swap event
_burn(user, _inLp);
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) = readReserveData(); // unpack data
emit Sync(xytBalance, xytWeight, tokenBalance);
}
function swapExactIn(
address inToken,
uint256 inAmount,
address outToken,
uint256 minOutAmount
) external override returns (uint256 outAmount, PendingTransfer[2] memory transfers) {
checkAddRemoveSwapClaimAllowed(false);
// We only need to do _mintProtocolFees if there is a curveShift that follows
if (checkNeedCurveShift()) {
_mintProtocolFees();
_curveShift();
_updateLastParamK(); // update paramK since it has changed due to a non-swap event
}
TokenReserve memory inTokenReserve = parseTokenReserveData(inToken);
TokenReserve memory outTokenReserve = parseTokenReserveData(outToken);
// calc out amount of token to be swapped out
outAmount = MarketMath._calcExactOut(
inTokenReserve,
outTokenReserve,
inAmount,
data.swapFee()
);
require(outAmount >= minOutAmount, "HIGH_OUT_LIMIT");
inTokenReserve.balance = inTokenReserve.balance.add(inAmount);
outTokenReserve.balance = outTokenReserve.balance.sub(outAmount);
// repack data
updateReserveData(inTokenReserve, inToken);
updateReserveData(outTokenReserve, outToken);
// no update paramK since it has changed but due to swap
transfers[0].amount = inAmount;
transfers[0].isOut = false;
transfers[1].amount = outAmount;
transfers[1].isOut = true;
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) = readReserveData(); // unpack data
emit Sync(xytBalance, xytWeight, tokenBalance);
}
function swapExactOut(
address inToken,
uint256 maxInAmount,
address outToken,
uint256 outAmount
) external override returns (uint256 inAmount, PendingTransfer[2] memory transfers) {
checkAddRemoveSwapClaimAllowed(false);
// We only need to do _mintProtocolFees if there is a curveShift that follows
if (checkNeedCurveShift()) {
_mintProtocolFees();
_curveShift();
_updateLastParamK(); // update paramK since it has changed due to a non-swap event
}
TokenReserve memory inTokenReserve = parseTokenReserveData(inToken);
TokenReserve memory outTokenReserve = parseTokenReserveData(outToken);
// Calc in amount.
inAmount = MarketMath._calcExactIn(
inTokenReserve,
outTokenReserve,
outAmount,
data.swapFee()
);
require(inAmount <= maxInAmount, "LOW_IN_LIMIT");
inTokenReserve.balance = inTokenReserve.balance.add(inAmount);
outTokenReserve.balance = outTokenReserve.balance.sub(outAmount);
// repack data
updateReserveData(inTokenReserve, inToken);
updateReserveData(outTokenReserve, outToken);
// no update paramK since it has changed but due to swap
transfers[0].amount = inAmount;
transfers[0].isOut = false;
transfers[1].amount = outAmount;
transfers[1].isOut = true;
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) = readReserveData(); // unpack data
emit Sync(xytBalance, xytWeight, tokenBalance);
}
/**
* @notice for user to claim their interest as holder of underlyingYield token
* @param user user's address
* @dev only can claim through router (included in checkAddRemoveSwapClaimAllowed)
* We skip time check in checkAddRemoveSwapClaimAllowed because users can always claim interests
* Since the Router has already had Reentrancy protection, we don't need one here
*/
function redeemLpInterests(address user) external override returns (uint256 interests) {
checkAddRemoveSwapClaimAllowed(true);
interests = _beforeTransferDueInterests(user);
_safeTransferYieldToken(user, interests);
}
/**
* @notice get the most up-to-date reserveData of the market by doing a dry curveShift
*/
function getReserves()
external
view
override
returns (
uint256 xytBalance,
uint256 xytWeight,
uint256 tokenBalance,
uint256 tokenWeight,
uint256 currentBlock
)
{
(xytBalance, tokenBalance, xytWeight, tokenWeight) = readReserveData();
if (checkNeedCurveShift()) {
(xytWeight, tokenWeight, ) = _updateWeightDry();
}
currentBlock = block.number;
}
/**
* @notice update the weights of the market
*/
function _updateWeight() internal {
(uint256 xytBalance, uint256 tokenBalance, , ) = readReserveData(); // unpack data
(uint256 xytWeightUpdated, , uint256 currentRelativePrice) = _updateWeightDry();
writeReserveData(xytBalance, tokenBalance, xytWeightUpdated); // repack data
lastRelativePrice = currentRelativePrice;
}
// do the weight update calculation but don't update the token reserve memory
function _updateWeightDry()
internal
view
returns (
uint256 xytWeightUpdated,
uint256 tokenWeightUpdated,
uint256 currentRelativePrice
)
{
// get current timestamp currentTime
uint256 currentTime = block.timestamp;
uint256 endTime = expiry;
uint256 startTime = xytStartTime;
uint256 duration = endTime - startTime;
(, , uint256 xytWeight, uint256 tokenWeight) = readReserveData(); // unpack data
uint256 timeLeft;
if (endTime >= currentTime) {
timeLeft = endTime - currentTime;
} else {
timeLeft = 0;
}
// get time_to_mature = (endTime - currentTime) / (endTime - startTime)
uint256 timeToMature = Math.rdiv(timeLeft * Math.RONE, duration * Math.RONE);
// get price for now = ln(3.14 * t + 1) / ln(4.14)
currentRelativePrice = Math.rdiv(
Math.ln(Math.rmul(Math.PI, timeToMature).add(Math.RONE), Math.RONE),
LN_PI_PLUSONE
);
uint256 r = Math.rdiv(currentRelativePrice, lastRelativePrice);
require(Math.RONE >= r, "MATH_ERROR");
uint256 thetaNumerator = Math.rmul(Math.rmul(xytWeight, tokenWeight), Math.RONE.sub(r));
uint256 thetaDenominator = Math.rmul(r, xytWeight).add(tokenWeight);
// calc weight changes theta
uint256 theta = Math.rdiv(thetaNumerator, thetaDenominator);
xytWeightUpdated = xytWeight.sub(theta);
tokenWeightUpdated = tokenWeight.add(theta);
}
/*
To add/remove/swap/claim, the market must have been
* bootstrapped
* only Router can call it
* if the function is not removeMarketLiquidityDual, then must check the market hasn't been locked yet
*/
function checkAddRemoveSwapClaimAllowed(bool skipOpenCheck) internal {
checkNotPaused();
require(bootstrapped, "NOT_BOOTSTRAPPED");
require(msg.sender == address(router), "ONLY_ROUTER");
if (!skipOpenCheck) {
require(block.timestamp < lockStartTime, "MARKET_LOCKED");
}
}
//curve shift will be called before any calculation using weight
//Note: there must be a _mintProtocolFees() before calling _curveShift()
function _curveShift() internal {
if (!checkNeedCurveShift()) return;
_updateWeight();
lastCurveShiftBlock = block.number;
}
/**
@notice To be called before the dueInterest of any users is redeemed
*/
function _beforeTransferDueInterests(address user) internal returns (uint256 amountOut) {
_updateDueInterests(user);
amountOut = dueInterests[user];
dueInterests[user] = 0;
// Use subMax0 to handle the extreme case of the market lacking a few wei of tokens to send out
lastNYield = lastNYield.subMax0(amountOut);
}
/**
* We will only updateParamL if the normalisedIncome / exchangeRate has increased more than a delta
* This delta is expected to be very small
*/
function checkNeedUpdateParamL() internal returns (bool) {
return _getIncomeIndexIncreaseRate() > data.interestUpdateRateDeltaForMarket();
}
/**
* We will only do curveShift() once every curveShiftBlockDelta blocks
*/
function checkNeedCurveShift() internal view returns (bool) {
return block.number > lastCurveShiftBlock.add(data.curveShiftBlockDelta());
}
/**
* @notice use to updateParamL. Must only be called by _updateDueInterests
* ParamL can be thought of as an always-increase incomeIndex for 1 LP
Consideration:
* Theoretically we have to updateParamL whenever the _updateDueInterests is called, since the external incomeIndex
(normalisedIncome/exchangeRate) is always increasing, and there are always interests to be claimed
* Yet, if we do so, the amount of interests to be claimed maybe negligible while the amount of gas spent is
tremendous (100k~200k last time we checked) => Caching is actually beneficial to user
* The users may lose some negligible amount of interest when they do removeLiquidity or transfer LP to others
(to be exact, they will lose NO MORE THAN interestUpdateRateDeltaForMarket%). In exchange, they will save
a lot of gas.
* If we assume the yearly interest rate is 10%, and we would like to only update the market's interest every one hour,
interestUpdateRateDeltaForMarket% = 1.10 ^ (1/ (365*24)) - 1 = 0.00108802167011 %
* The correctness of caching can be thought of like this: We just pretend that there are only income once in a while,
and when that income come, they will come in large amount, and we will distribute them fairly to all users
*/
function _updateParamL() internal {
if (!checkNeedUpdateParamL()) return;
// redeem the interest from XYT
router.redeemDueInterests(forgeId, underlyingAsset, expiry, address(this));
uint256 currentNYield = underlyingYieldToken.balanceOf(address(this));
(uint256 firstTerm, uint256 paramR) = _getFirstTermAndParamR(currentNYield);
uint256 secondTerm;
/*
* paramR can be thought of as the amount of interest earned by the market
(but excluding the compound effect). paramR is normally small & totalSupply is
normally much larger so we need to multiply them with MULTIPLIER
*/
if (totalSupply() != 0) secondTerm = paramR.mul(MULTIPLIER).div(totalSupply());
// firstTerm & secondTerm are not the best names, but please refer to AMM specs
// to understand the meaning of these 2 params
paramL = firstTerm.add(secondTerm);
lastNYield = currentNYield;
}
// before we send LPs, we need to update LP interests for both the to and from addresses
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override {
super._beforeTokenTransfer(from, to, amount);
checkNotPaused();
if (from != address(0)) _updateDueInterests(from);
if (to != address(0)) _updateDueInterests(to);
}
/**
@dev Must be the only way to transfer aToken/cToken out
// Please refer to _safeTransfer of PendleForgeBase for the rationale of this function
*/
function _safeTransferYieldToken(address _user, uint256 _amount) internal {
if (_amount == 0) return;
_amount = Math.min(_amount, underlyingYieldToken.balanceOf(address(this)));
underlyingYieldToken.safeTransfer(_user, _amount);
}
/**
* @notice _initialize the lock of the market. Must only be called in bootstrap
*/
function _initializeLock() internal {
uint256 duration = expiry.sub(xytStartTime); // market expiry = xyt expiry
uint256 lockDuration = duration.mul(data.lockNumerator()).div(data.lockDenominator());
lockStartTime = expiry.sub(lockDuration);
}
/**
@notice _mint new LP for protocol fee. Mint them directly to the treasury
@dev this function should be very similar to Uniswap
*/
function _mintProtocolFees() internal {
uint256 feeRatio = data.protocolSwapFee();
uint256 _lastParamK = lastParamK;
if (feeRatio > 0) {
if (_lastParamK != 0) {
uint256 k = _calcParamK();
if (k > _lastParamK) {
uint256 numer = totalSupply().mul(k.sub(_lastParamK));
uint256 denom = Math.RONE.sub(feeRatio).mul(k).div(feeRatio).add(_lastParamK);
uint256 liquidity = numer / denom;
address treasury = data.treasury();
if (liquidity > 0) {
_mint(treasury, liquidity);
}
}
}
} else if (_lastParamK != 0) {
// if fee is turned off, we need to reset lastParamK as well
lastParamK = 0;
}
}
/**
Equation for paramK: paramK = xytBal ^ xytWeight * tokenBal ^ tokenW
* @dev must be called whenever the above equation changes but not due to a swapping action
I.e: after add/remove/bootstrap liquidity or curveShift
*/
function _updateLastParamK() internal {
if (data.protocolSwapFee() == 0) return;
lastParamK = _calcParamK();
}
/**
* @notice calc the value of paramK. The formula for this can be referred in the AMM specs
*/
function _calcParamK() internal view returns (uint256 paramK) {
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight) =
readReserveData();
paramK = Math
.rpow(xytBalance.toFP(), xytWeight)
.rmul(Math.rpow(tokenBalance.toFP(), tokenWeight))
.toInt();
}
function _allowedToWithdraw(address _token) internal view override returns (bool allowed) {
allowed =
_token != xyt &&
_token != token &&
_token != address(this) &&
_token != address(underlyingYieldToken);
}
function _afterBootstrap() internal virtual;
/**
@notice update the LP interest for users (before their balances of LP changes)
@dev This must be called before any transfer / mint/ burn action of LP
(and this has been implemented in the beforeTokenTransfer of this contract)
*/
function _updateDueInterests(address user) internal virtual;
/// @notice Get params to update paramL. Must only be called by updateParamL
function _getFirstTermAndParamR(uint256 currentNYield)
internal
virtual
returns (uint256 firstTerm, uint256 paramR);
/// @notice Get the increase rate of normalisedIncome / exchangeRate
function _getIncomeIndexIncreaseRate() internal virtual returns (uint256 increaseRate);
}
// 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
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
import "./IPendleRouter.sol";
import "./IPendleRewardManager.sol";
import "./IPendleYieldContractDeployer.sol";
import "./IPendleData.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IPendleForge {
/**
* @dev Emitted when the Forge has minted the OT and XYT tokens.
* @param forgeId The forgeId
* @param underlyingAsset The address of the underlying yield token.
* @param expiry The expiry of the XYT token
* @param amountToTokenize The amount of yield bearing assets to tokenize
* @param amountTokenMinted The amount of OT/XYT minted
**/
event MintYieldTokens(
bytes32 forgeId,
address indexed underlyingAsset,
uint256 indexed expiry,
uint256 amountToTokenize,
uint256 amountTokenMinted,
address indexed user
);
/**
* @dev Emitted when the Forge has created new yield token contracts.
* @param forgeId The forgeId
* @param underlyingAsset The address of the underlying asset.
* @param expiry The date in epoch time when the contract will expire.
* @param ot The address of the ownership token.
* @param xyt The address of the new future yield token.
**/
event NewYieldContracts(
bytes32 forgeId,
address indexed underlyingAsset,
uint256 indexed expiry,
address ot,
address xyt,
address yieldBearingAsset
);
/**
* @dev Emitted when the Forge has redeemed the OT and XYT tokens.
* @param forgeId The forgeId
* @param underlyingAsset the address of the underlying asset
* @param expiry The expiry of the XYT token
* @param amountToRedeem The amount of OT to be redeemed.
* @param redeemedAmount The amount of yield token received
**/
event RedeemYieldToken(
bytes32 forgeId,
address indexed underlyingAsset,
uint256 indexed expiry,
uint256 amountToRedeem,
uint256 redeemedAmount,
address indexed user
);
/**
* @dev Emitted when interest claim is settled
* @param forgeId The forgeId
* @param underlyingAsset the address of the underlying asset
* @param expiry The expiry of the XYT token
* @param user Interest receiver Address
* @param amount The amount of interest claimed
**/
event DueInterestsSettled(
bytes32 forgeId,
address indexed underlyingAsset,
uint256 indexed expiry,
uint256 amount,
uint256 forgeFeeAmount,
address indexed user
);
/**
* @dev Emitted when forge fee is withdrawn
* @param forgeId The forgeId
* @param underlyingAsset the address of the underlying asset
* @param expiry The expiry of the XYT token
* @param amount The amount of interest claimed
**/
event ForgeFeeWithdrawn(
bytes32 forgeId,
address indexed underlyingAsset,
uint256 indexed expiry,
uint256 amount
);
function setUpEmergencyMode(
address _underlyingAsset,
uint256 _expiry,
address spender
) external;
function newYieldContracts(address underlyingAsset, uint256 expiry)
external
returns (address ot, address xyt);
function redeemAfterExpiry(
address user,
address underlyingAsset,
uint256 expiry
) external returns (uint256 redeemedAmount);
function redeemDueInterests(
address user,
address underlyingAsset,
uint256 expiry
) external returns (uint256 interests);
function updateDueInterests(
address underlyingAsset,
uint256 expiry,
address user
) external;
function updatePendingRewards(
address _underlyingAsset,
uint256 _expiry,
address _user
) external;
function redeemUnderlying(
address user,
address underlyingAsset,
uint256 expiry,
uint256 amountToRedeem
) external returns (uint256 redeemedAmount);
function mintOtAndXyt(
address underlyingAsset,
uint256 expiry,
uint256 amountToTokenize,
address to
)
external
returns (
address ot,
address xyt,
uint256 amountTokenMinted
);
function withdrawForgeFee(address underlyingAsset, uint256 expiry) external;
function getYieldBearingToken(address underlyingAsset) external returns (address);
/**
* @notice Gets a reference to the PendleRouter contract.
* @return Returns the router contract reference.
**/
function router() external view returns (IPendleRouter);
function data() external view returns (IPendleData);
function rewardManager() external view returns (IPendleRewardManager);
function yieldContractDeployer() external view returns (IPendleYieldContractDeployer);
function rewardToken() external view returns (IERC20);
/**
* @notice Gets the bytes32 ID of the forge.
* @return Returns the forge and protocol identifier.
**/
function forgeId() external view returns (bytes32);
function dueInterests(
address _underlyingAsset,
uint256 expiry,
address _user
) external view returns (uint256);
function yieldTokenHolders(address _underlyingAsset, uint256 _expiry)
external
view
returns (address yieldTokenHolder);
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
pragma abicoder v2;
import "../interfaces/IWETH.sol";
import "./IPendleData.sol";
import "../libraries/PendleStructs.sol";
import "./IPendleMarketFactory.sol";
interface IPendleRouter {
/**
* @notice Emitted when a market for a future yield token and an ERC20 token is created.
* @param marketFactoryId Forge identifier.
* @param xyt The address of the tokenized future yield token as the base asset.
* @param token The address of an ERC20 token as the quote asset.
* @param market The address of the newly created market.
**/
event MarketCreated(
bytes32 marketFactoryId,
address indexed xyt,
address indexed token,
address indexed market
);
/**
* @notice Emitted when a swap happens on the market.
* @param trader The address of msg.sender.
* @param inToken The input token.
* @param outToken The output token.
* @param exactIn The exact amount being traded.
* @param exactOut The exact amount received.
* @param market The market address.
**/
event SwapEvent(
address indexed trader,
address inToken,
address outToken,
uint256 exactIn,
uint256 exactOut,
address market
);
/**
* @dev Emitted when user adds liquidity
* @param sender The user who added liquidity.
* @param token0Amount the amount of token0 (xyt) provided by user
* @param token1Amount the amount of token1 provided by user
* @param market The market address.
* @param exactOutLp The exact LP minted
*/
event Join(
address indexed sender,
uint256 token0Amount,
uint256 token1Amount,
address market,
uint256 exactOutLp
);
/**
* @dev Emitted when user removes liquidity
* @param sender The user who removed liquidity.
* @param token0Amount the amount of token0 (xyt) given to user
* @param token1Amount the amount of token1 given to user
* @param market The market address.
* @param exactInLp The exact Lp to remove
*/
event Exit(
address indexed sender,
uint256 token0Amount,
uint256 token1Amount,
address market,
uint256 exactInLp
);
/**
* @notice Gets a reference to the PendleData contract.
* @return Returns the data contract reference.
**/
function data() external view returns (IPendleData);
/**
* @notice Gets a reference of the WETH9 token contract address.
* @return WETH token reference.
**/
function weth() external view returns (IWETH);
/***********
* FORGE *
***********/
function newYieldContracts(
bytes32 forgeId,
address underlyingAsset,
uint256 expiry
) external returns (address ot, address xyt);
function redeemAfterExpiry(
bytes32 forgeId,
address underlyingAsset,
uint256 expiry
) external returns (uint256 redeemedAmount);
function redeemDueInterests(
bytes32 forgeId,
address underlyingAsset,
uint256 expiry,
address user
) external returns (uint256 interests);
function redeemUnderlying(
bytes32 forgeId,
address underlyingAsset,
uint256 expiry,
uint256 amountToRedeem
) external returns (uint256 redeemedAmount);
function renewYield(
bytes32 forgeId,
uint256 oldExpiry,
address underlyingAsset,
uint256 newExpiry,
uint256 renewalRate
)
external
returns (
uint256 redeemedAmount,
uint256 amountRenewed,
address ot,
address xyt,
uint256 amountTokenMinted
);
function tokenizeYield(
bytes32 forgeId,
address underlyingAsset,
uint256 expiry,
uint256 amountToTokenize,
address to
)
external
returns (
address ot,
address xyt,
uint256 amountTokenMinted
);
/***********
* MARKET *
***********/
function addMarketLiquidityDual(
bytes32 _marketFactoryId,
address _xyt,
address _token,
uint256 _desiredXytAmount,
uint256 _desiredTokenAmount,
uint256 _xytMinAmount,
uint256 _tokenMinAmount
)
external
payable
returns (
uint256 amountXytUsed,
uint256 amountTokenUsed,
uint256 lpOut
);
function addMarketLiquiditySingle(
bytes32 marketFactoryId,
address xyt,
address token,
bool forXyt,
uint256 exactInAsset,
uint256 minOutLp
) external payable returns (uint256 exactOutLp);
function removeMarketLiquidityDual(
bytes32 marketFactoryId,
address xyt,
address token,
uint256 exactInLp,
uint256 minOutXyt,
uint256 minOutToken
) external returns (uint256 exactOutXyt, uint256 exactOutToken);
function removeMarketLiquiditySingle(
bytes32 marketFactoryId,
address xyt,
address token,
bool forXyt,
uint256 exactInLp,
uint256 minOutAsset
) external returns (uint256 exactOutXyt, uint256 exactOutToken);
/**
* @notice Creates a market given a protocol ID, future yield token, and an ERC20 token.
* @param marketFactoryId Market Factory identifier.
* @param xyt Token address of the future yield token as base asset.
* @param token Token address of an ERC20 token as quote asset.
* @return market Returns the address of the newly created market.
**/
function createMarket(
bytes32 marketFactoryId,
address xyt,
address token
) external returns (address market);
function bootstrapMarket(
bytes32 marketFactoryId,
address xyt,
address token,
uint256 initialXytLiquidity,
uint256 initialTokenLiquidity
) external payable;
function swapExactIn(
address tokenIn,
address tokenOut,
uint256 inTotalAmount,
uint256 minOutTotalAmount,
bytes32 marketFactoryId
) external payable returns (uint256 outTotalAmount);
function swapExactOut(
address tokenIn,
address tokenOut,
uint256 outTotalAmount,
uint256 maxInTotalAmount,
bytes32 marketFactoryId
) external payable returns (uint256 inTotalAmount);
function redeemLpInterests(address market, address user) external returns (uint256 interests);
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
interface IPendleRewardManager {
event UpdateFrequencySet(address[], uint256[]);
event SkippingRewardsSet(bool);
event DueRewardsSettled(
bytes32 forgeId,
address underlyingAsset,
uint256 expiry,
uint256 amountOut,
address user
);
function redeemRewards(
address _underlyingAsset,
uint256 _expiry,
address _user
) external returns (uint256 dueRewards);
function updatePendingRewards(
address _underlyingAsset,
uint256 _expiry,
address _user
) external;
function updateParamLManual(address _underlyingAsset, uint256 _expiry) external;
function setUpdateFrequency(
address[] calldata underlyingAssets,
uint256[] calldata frequencies
) external;
function setSkippingRewards(bool skippingRewards) external;
function forgeId() external returns (bytes32);
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
interface IPendleYieldContractDeployer {
function forgeId() external returns (bytes32);
function forgeOwnershipToken(
address _underlyingAsset,
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _expiry
) external returns (address ot);
function forgeFutureYieldToken(
address _underlyingAsset,
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _expiry
) external returns (address xyt);
function deployYieldTokenHolder(address yieldToken, uint256 expiry)
external
returns (address yieldTokenHolder);
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
import "./IPendleRouter.sol";
import "./IPendleYieldToken.sol";
import "./IPendlePausingManager.sol";
import "./IPendleMarket.sol";
interface IPendleData {
/**
* @notice Emitted when validity of a forge-factory pair is updated
* @param _forgeId the forge id
* @param _marketFactoryId the market factory id
* @param _valid valid or not
**/
event ForgeFactoryValiditySet(bytes32 _forgeId, bytes32 _marketFactoryId, bool _valid);
/**
* @notice Emitted when Pendle and PendleFactory addresses have been updated.
* @param treasury The address of the new treasury contract.
**/
event TreasurySet(address treasury);
/**
* @notice Emitted when LockParams is changed
**/
event LockParamsSet(uint256 lockNumerator, uint256 lockDenominator);
/**
* @notice Emitted when ExpiryDivisor is changed
**/
event ExpiryDivisorSet(uint256 expiryDivisor);
/**
* @notice Emitted when forge fee is changed
**/
event ForgeFeeSet(uint256 forgeFee);
/**
* @notice Emitted when interestUpdateRateDeltaForMarket is changed
* @param interestUpdateRateDeltaForMarket new interestUpdateRateDeltaForMarket setting
**/
event InterestUpdateRateDeltaForMarketSet(uint256 interestUpdateRateDeltaForMarket);
/**
* @notice Emitted when market fees are changed
* @param _swapFee new swapFee setting
* @param _protocolSwapFee new protocolSwapFee setting
**/
event MarketFeesSet(uint256 _swapFee, uint256 _protocolSwapFee);
/**
* @notice Emitted when the curve shift block delta is changed
* @param _blockDelta new block delta setting
**/
event CurveShiftBlockDeltaSet(uint256 _blockDelta);
/**
* @dev Emitted when new forge is added
* @param marketFactoryId Human Readable Market Factory ID in Bytes
* @param marketFactoryAddress The Market Factory Address
*/
event NewMarketFactory(bytes32 indexed marketFactoryId, address indexed marketFactoryAddress);
/**
* @notice Set/update validity of a forge-factory pair
* @param _forgeId the forge id
* @param _marketFactoryId the market factory id
* @param _valid valid or not
**/
function setForgeFactoryValidity(
bytes32 _forgeId,
bytes32 _marketFactoryId,
bool _valid
) external;
/**
* @notice Sets the PendleTreasury contract addresses.
* @param newTreasury Address of new treasury contract.
**/
function setTreasury(address newTreasury) external;
/**
* @notice Gets a reference to the PendleRouter contract.
* @return Returns the router contract reference.
**/
function router() external view returns (IPendleRouter);
/**
* @notice Gets a reference to the PendleRouter contract.
* @return Returns the router contract reference.
**/
function pausingManager() external view returns (IPendlePausingManager);
/**
* @notice Gets the treasury contract address where fees are being sent to.
* @return Address of the treasury contract.
**/
function treasury() external view returns (address);
/***********
* FORGE *
***********/
/**
* @notice Emitted when a forge for a protocol is added.
* @param forgeId Forge and protocol identifier.
* @param forgeAddress The address of the added forge.
**/
event ForgeAdded(bytes32 indexed forgeId, address indexed forgeAddress);
/**
* @notice Adds a new forge for a protocol.
* @param forgeId Forge and protocol identifier.
* @param forgeAddress The address of the added forge.
**/
function addForge(bytes32 forgeId, address forgeAddress) external;
/**
* @notice Store new OT and XYT details.
* @param forgeId Forge and protocol identifier.
* @param ot The address of the new XYT.
* @param xyt The address of the new XYT.
* @param underlyingAsset Token address of the underlying asset.
* @param expiry Yield contract expiry in epoch time.
**/
function storeTokens(
bytes32 forgeId,
address ot,
address xyt,
address underlyingAsset,
uint256 expiry
) external;
/**
* @notice Set a new forge fee
* @param _forgeFee new forge fee
**/
function setForgeFee(uint256 _forgeFee) external;
/**
* @notice Gets the OT and XYT tokens.
* @param forgeId Forge and protocol identifier.
* @param underlyingYieldToken Token address of the underlying yield token.
* @param expiry Yield contract expiry in epoch time.
* @return ot The OT token references.
* @return xyt The XYT token references.
**/
function getPendleYieldTokens(
bytes32 forgeId,
address underlyingYieldToken,
uint256 expiry
) external view returns (IPendleYieldToken ot, IPendleYieldToken xyt);
/**
* @notice Gets a forge given the identifier.
* @param forgeId Forge and protocol identifier.
* @return forgeAddress Returns the forge address.
**/
function getForgeAddress(bytes32 forgeId) external view returns (address forgeAddress);
/**
* @notice Checks if an XYT token is valid.
* @param forgeId The forgeId of the forge.
* @param underlyingAsset Token address of the underlying asset.
* @param expiry Yield contract expiry in epoch time.
* @return True if valid, false otherwise.
**/
function isValidXYT(
bytes32 forgeId,
address underlyingAsset,
uint256 expiry
) external view returns (bool);
/**
* @notice Checks if an OT token is valid.
* @param forgeId The forgeId of the forge.
* @param underlyingAsset Token address of the underlying asset.
* @param expiry Yield contract expiry in epoch time.
* @return True if valid, false otherwise.
**/
function isValidOT(
bytes32 forgeId,
address underlyingAsset,
uint256 expiry
) external view returns (bool);
function validForgeFactoryPair(bytes32 _forgeId, bytes32 _marketFactoryId)
external
view
returns (bool);
/**
* @notice Gets a reference to a specific OT.
* @param forgeId Forge and protocol identifier.
* @param underlyingYieldToken Token address of the underlying yield token.
* @param expiry Yield contract expiry in epoch time.
* @return ot Returns the reference to an OT.
**/
function otTokens(
bytes32 forgeId,
address underlyingYieldToken,
uint256 expiry
) external view returns (IPendleYieldToken ot);
/**
* @notice Gets a reference to a specific XYT.
* @param forgeId Forge and protocol identifier.
* @param underlyingAsset Token address of the underlying asset
* @param expiry Yield contract expiry in epoch time.
* @return xyt Returns the reference to an XYT.
**/
function xytTokens(
bytes32 forgeId,
address underlyingAsset,
uint256 expiry
) external view returns (IPendleYieldToken xyt);
/***********
* MARKET *
***********/
event MarketPairAdded(address indexed market, address indexed xyt, address indexed token);
function addMarketFactory(bytes32 marketFactoryId, address marketFactoryAddress) external;
function isMarket(address _addr) external view returns (bool result);
function isXyt(address _addr) external view returns (bool result);
function addMarket(
bytes32 marketFactoryId,
address xyt,
address token,
address market
) external;
function setMarketFees(uint256 _swapFee, uint256 _protocolSwapFee) external;
function setInterestUpdateRateDeltaForMarket(uint256 _interestUpdateRateDeltaForMarket)
external;
function setLockParams(uint256 _lockNumerator, uint256 _lockDenominator) external;
function setExpiryDivisor(uint256 _expiryDivisor) external;
function setCurveShiftBlockDelta(uint256 _blockDelta) external;
/**
* @notice Displays the number of markets currently existing.
* @return Returns markets length,
**/
function allMarketsLength() external view returns (uint256);
function forgeFee() external view returns (uint256);
function interestUpdateRateDeltaForMarket() external view returns (uint256);
function expiryDivisor() external view returns (uint256);
function lockNumerator() external view returns (uint256);
function lockDenominator() external view returns (uint256);
function swapFee() external view returns (uint256);
function protocolSwapFee() external view returns (uint256);
function curveShiftBlockDelta() external view returns (uint256);
function getMarketByIndex(uint256 index) external view returns (address market);
/**
* @notice Gets a market given a future yield token and an ERC20 token.
* @param xyt Token address of the future yield token as base asset.
* @param token Token address of an ERC20 token as quote asset.
* @return market Returns the market address.
**/
function getMarket(
bytes32 marketFactoryId,
address xyt,
address token
) external view returns (address market);
/**
* @notice Gets a market factory given the identifier.
* @param marketFactoryId MarketFactory identifier.
* @return marketFactoryAddress Returns the factory address.
**/
function getMarketFactoryAddress(bytes32 marketFactoryId)
external
view
returns (address marketFactoryAddress);
function getMarketFromKey(
address xyt,
address token,
bytes32 marketFactoryId
) external view returns (address market);
}
// 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
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.6;
struct TokenReserve {
uint256 weight;
uint256 balance;
}
struct PendingTransfer {
uint256 amount;
bool isOut;
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
import "./IPendleRouter.sol";
interface IPendleMarketFactory {
/**
* @notice Creates a market given a protocol ID, future yield token, and an ERC20 token.
* @param xyt Token address of the futuonlyCorere yield token as base asset.
* @param token Token address of an ERC20 token as quote asset.
* @return market Returns the address of the newly created market.
**/
function createMarket(address xyt, address token) external returns (address market);
/**
* @notice Gets a reference to the PendleRouter contract.
* @return Returns the router contract reference.
**/
function router() external view returns (IPendleRouter);
function marketFactoryId() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IPendleBaseToken.sol";
import "./IPendleForge.sol";
interface IPendleYieldToken is IERC20, IPendleBaseToken {
/**
* @notice Emitted when burning OT or XYT tokens.
* @param user The address performing the burn.
* @param amount The amount to be burned.
**/
event Burn(address indexed user, uint256 amount);
/**
* @notice Emitted when minting OT or XYT tokens.
* @param user The address performing the mint.
* @param amount The amount to be minted.
**/
event Mint(address indexed user, uint256 amount);
/**
* @notice Burns OT or XYT tokens from user, reducing the total supply.
* @param user The address performing the burn.
* @param amount The amount to be burned.
**/
function burn(address user, uint256 amount) external;
/**
* @notice Mints new OT or XYT tokens for user, increasing the total supply.
* @param user The address to send the minted tokens.
* @param amount The amount to be minted.
**/
function mint(address user, uint256 amount) external;
/**
* @notice Gets the forge address of the PendleForge contract for this yield token.
* @return Retuns the forge address.
**/
function forge() external view returns (IPendleForge);
/**
* @notice Returns the address of the underlying asset.
* @return Returns the underlying asset address.
**/
function underlyingAsset() external view returns (address);
/**
* @notice Returns the address of the underlying yield token.
* @return Returns the underlying yield token address.
**/
function underlyingYieldToken() external view returns (address);
/**
* @notice let the router approve itself to spend OT/XYT/LP from any wallet
* @param user user to approve
**/
function approveRouter(address user) external;
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
interface IPendlePausingManager {
event AddPausingAdmin(address admin);
event RemovePausingAdmin(address admin);
event PendingForgeEmergencyHandler(address _pendingForgeHandler);
event PendingMarketEmergencyHandler(address _pendingMarketHandler);
event PendingLiqMiningEmergencyHandler(address _pendingLiqMiningHandler);
event ForgeEmergencyHandlerSet(address forgeEmergencyHandler);
event MarketEmergencyHandlerSet(address marketEmergencyHandler);
event LiqMiningEmergencyHandlerSet(address liqMiningEmergencyHandler);
event PausingManagerLocked();
event ForgeHandlerLocked();
event MarketHandlerLocked();
event LiqMiningHandlerLocked();
event SetForgePaused(bytes32 forgeId, bool settingToPaused);
event SetForgeAssetPaused(bytes32 forgeId, address underlyingAsset, bool settingToPaused);
event SetForgeAssetExpiryPaused(
bytes32 forgeId,
address underlyingAsset,
uint256 expiry,
bool settingToPaused
);
event SetForgeLocked(bytes32 forgeId);
event SetForgeAssetLocked(bytes32 forgeId, address underlyingAsset);
event SetForgeAssetExpiryLocked(bytes32 forgeId, address underlyingAsset, uint256 expiry);
event SetMarketFactoryPaused(bytes32 marketFactoryId, bool settingToPaused);
event SetMarketPaused(bytes32 marketFactoryId, address market, bool settingToPaused);
event SetMarketFactoryLocked(bytes32 marketFactoryId);
event SetMarketLocked(bytes32 marketFactoryId, address market);
event SetLiqMiningPaused(address liqMiningContract, bool settingToPaused);
event SetLiqMiningLocked(address liqMiningContract);
function forgeEmergencyHandler()
external
view
returns (
address handler,
address pendingHandler,
uint256 timelockDeadline
);
function marketEmergencyHandler()
external
view
returns (
address handler,
address pendingHandler,
uint256 timelockDeadline
);
function liqMiningEmergencyHandler()
external
view
returns (
address handler,
address pendingHandler,
uint256 timelockDeadline
);
function permLocked() external view returns (bool);
function permForgeHandlerLocked() external view returns (bool);
function permMarketHandlerLocked() external view returns (bool);
function permLiqMiningHandlerLocked() external view returns (bool);
function isPausingAdmin(address) external view returns (bool);
function setPausingAdmin(address admin, bool isAdmin) external;
function requestForgeHandlerChange(address _pendingForgeHandler) external;
function requestMarketHandlerChange(address _pendingMarketHandler) external;
function requestLiqMiningHandlerChange(address _pendingLiqMiningHandler) external;
function applyForgeHandlerChange() external;
function applyMarketHandlerChange() external;
function applyLiqMiningHandlerChange() external;
function lockPausingManagerPermanently() external;
function lockForgeHandlerPermanently() external;
function lockMarketHandlerPermanently() external;
function lockLiqMiningHandlerPermanently() external;
function setForgePaused(bytes32 forgeId, bool paused) external;
function setForgeAssetPaused(
bytes32 forgeId,
address underlyingAsset,
bool paused
) external;
function setForgeAssetExpiryPaused(
bytes32 forgeId,
address underlyingAsset,
uint256 expiry,
bool paused
) external;
function setForgeLocked(bytes32 forgeId) external;
function setForgeAssetLocked(bytes32 forgeId, address underlyingAsset) external;
function setForgeAssetExpiryLocked(
bytes32 forgeId,
address underlyingAsset,
uint256 expiry
) external;
function checkYieldContractStatus(
bytes32 forgeId,
address underlyingAsset,
uint256 expiry
) external returns (bool _paused, bool _locked);
function setMarketFactoryPaused(bytes32 marketFactoryId, bool paused) external;
function setMarketPaused(
bytes32 marketFactoryId,
address market,
bool paused
) external;
function setMarketFactoryLocked(bytes32 marketFactoryId) external;
function setMarketLocked(bytes32 marketFactoryId, address market) external;
function checkMarketStatus(bytes32 marketFactoryId, address market)
external
returns (bool _paused, bool _locked);
function setLiqMiningPaused(address liqMiningContract, bool settingToPaused) external;
function setLiqMiningLocked(address liqMiningContract) external;
function checkLiqMiningStatus(address liqMiningContract)
external
returns (bool _paused, bool _locked);
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
pragma abicoder v2;
import "./IPendleRouter.sol";
import "./IPendleBaseToken.sol";
import "../libraries/PendleStructs.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IPendleMarket is IERC20 {
/**
* @notice Emitted when reserves pool has been updated
* @param reserve0 The XYT reserves.
* @param weight0 The XYT weight
* @param reserve1 The generic token reserves.
* For the generic Token weight it can be inferred by (2^40) - weight0
**/
event Sync(uint256 reserve0, uint256 weight0, uint256 reserve1);
function setUpEmergencyMode(address spender) external;
function bootstrap(
address user,
uint256 initialXytLiquidity,
uint256 initialTokenLiquidity
) external returns (PendingTransfer[2] memory transfers, uint256 exactOutLp);
function addMarketLiquiditySingle(
address user,
address inToken,
uint256 inAmount,
uint256 minOutLp
) external returns (PendingTransfer[2] memory transfers, uint256 exactOutLp);
function addMarketLiquidityDual(
address user,
uint256 _desiredXytAmount,
uint256 _desiredTokenAmount,
uint256 _xytMinAmount,
uint256 _tokenMinAmount
) external returns (PendingTransfer[2] memory transfers, uint256 lpOut);
function removeMarketLiquidityDual(
address user,
uint256 inLp,
uint256 minOutXyt,
uint256 minOutToken
) external returns (PendingTransfer[2] memory transfers);
function removeMarketLiquiditySingle(
address user,
address outToken,
uint256 exactInLp,
uint256 minOutToken
) external returns (PendingTransfer[2] memory transfers);
function swapExactIn(
address inToken,
uint256 inAmount,
address outToken,
uint256 minOutAmount
) external returns (uint256 outAmount, PendingTransfer[2] memory transfers);
function swapExactOut(
address inToken,
uint256 maxInAmount,
address outToken,
uint256 outAmount
) external returns (uint256 inAmount, PendingTransfer[2] memory transfers);
function redeemLpInterests(address user) external returns (uint256 interests);
function getReserves()
external
view
returns (
uint256 xytBalance,
uint256 xytWeight,
uint256 tokenBalance,
uint256 tokenWeight,
uint256 currentBlock
);
function factoryId() external view returns (bytes32);
function token() external view returns (address);
function xyt() external view returns (address);
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IPendleBaseToken is IERC20 {
/**
* @notice Decreases the allowance granted to spender by the caller.
* @param spender The address to reduce the allowance from.
* @param subtractedValue The amount allowance to subtract.
* @return Returns true if allowance has decreased, otherwise false.
**/
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
/**
* @notice The yield contract start in epoch time.
* @return Returns the yield start date.
**/
function start() external view returns (uint256);
/**
* @notice The yield contract expiry in epoch time.
* @return Returns the yield expiry date.
**/
function expiry() external view returns (uint256);
/**
* @notice Increases the allowance granted to spender by the caller.
* @param spender The address to increase the allowance from.
* @param addedValue The amount allowance to add.
* @return Returns true if allowance has increased, otherwise false
**/
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
/**
* @notice Returns the number of decimals the token uses.
* @return Returns the token's decimals.
**/
function decimals() external view returns (uint8);
/**
* @notice Returns the name of the token.
* @return Returns the token's name.
**/
function name() external view returns (string memory);
/**
* @notice Returns the symbol of the token.
* @return Returns the token's symbol.
**/
function symbol() external view returns (string memory);
/**
* @notice approve using the owner's signature
**/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./PermissionsV2.sol";
abstract contract WithdrawableV2 is PermissionsV2 {
using SafeERC20 for IERC20;
event EtherWithdraw(uint256 amount, address sendTo);
event TokenWithdraw(IERC20 token, uint256 amount, address sendTo);
/**
* @dev Allows governance to withdraw Ether in a Pendle contract
* in case of accidental ETH transfer into the contract.
* @param amount The amount of Ether to withdraw.
* @param sendTo The recipient address.
*/
function withdrawEther(uint256 amount, address payable sendTo) external onlyGovernance {
(bool success, ) = sendTo.call{value: amount}("");
require(success, "WITHDRAW_FAILED");
emit EtherWithdraw(amount, sendTo);
}
/**
* @dev Allows governance to withdraw all IERC20 compatible tokens in a Pendle
* contract in case of accidental token transfer into the contract.
* @param token IERC20 The address of the token contract.
* @param amount The amount of IERC20 tokens to withdraw.
* @param sendTo The recipient address.
*/
function withdrawToken(
IERC20 token,
uint256 amount,
address sendTo
) external onlyGovernance {
require(_allowedToWithdraw(address(token)), "TOKEN_NOT_ALLOWED");
token.safeTransfer(sendTo, amount);
emit TokenWithdraw(token, amount, sendTo);
}
// must be overridden by the sub contracts, so we must consider explicitly
// in each and every contract which tokens are allowed to be withdrawn
function _allowedToWithdraw(address) internal view virtual returns (bool allowed);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "../interfaces/IPendleBaseToken.sol";
import "../interfaces/IPendleRouter.sol";
/**
* @title PendleBaseToken
* @dev The contract implements the standard ERC20 functions, plus some
* Pendle specific fields and functions, namely:
* - expiry
*
* This abstract contract is inherited by PendleFutureYieldToken
* and PendleOwnershipToken contracts.
**/
abstract contract PendleBaseToken is ERC20 {
using SafeMath for uint256;
uint256 public immutable start;
uint256 public immutable expiry;
IPendleRouter public immutable router;
//// Start of EIP-2612 related part, exactly the same as UniswapV2ERC20.sol
bytes32 public immutable DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public nonces;
//// End of EIP-2612 related part
constructor(
address _router,
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _start,
uint256 _expiry
) ERC20(_name, _symbol) {
_setupDecimals(_decimals);
start = _start;
expiry = _expiry;
router = IPendleRouter(_router);
//// Start of EIP-2612 related part, exactly the same as UniswapV2ERC20.sol, except for the noted parts below
uint256 chainId;
assembly {
chainId := chainid() // chainid() is a function in assembly in this solidity version
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(_name)), // use our own _name here
keccak256(bytes("1")),
chainId,
address(this)
)
);
//// End of EIP-2612 related part
}
//// Start of EIP-2612 related part, exactly the same as UniswapV2ERC20.sol
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, "PERMIT_EXPIRED");
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
);
address recoveredAddress = ECDSA.recover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNATURE");
_approve(owner, spender, value);
}
//// End of EIP-2612 related part
function _beforeTokenTransfer(
address from,
address to,
uint256
) internal virtual override {
require(to != address(this), "SEND_TO_TOKEN_CONTRACT");
require(to != from, "SEND_TO_SELF");
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./MathLib.sol";
import "./PendleStructs.sol";
library MarketMath {
using SafeMath for uint256;
/**
* @notice calculate the exact amount of tokens that user need to put in the market
* in order to get back certain amount of the other token
* @param inTokenReserve market reserve details of token that user wants to put in
* @param outTokenReserve market reserve details of token that user wants to get back
* @param exactOut exact amount of token that user wants to get back
* @param swapFee swap fee ratio for swap
* @dev The formula for this function can be referred in the AMM Specs
*/
function _calcExactIn(
TokenReserve memory inTokenReserve,
TokenReserve memory outTokenReserve,
uint256 exactOut,
uint256 swapFee
) internal pure returns (uint256 exactIn) {
uint256 weightRatio = Math.rdiv(outTokenReserve.weight, inTokenReserve.weight);
uint256 diff = outTokenReserve.balance.sub(exactOut);
uint256 y = Math.rdiv(outTokenReserve.balance, diff);
uint256 foo = Math.rpow(y, weightRatio);
foo = foo.sub(Math.RONE);
exactIn = Math.RONE.sub(swapFee);
exactIn = Math.rdiv(Math.rmul(inTokenReserve.balance, foo), exactIn);
}
/**
* @notice calculate the exact amount of tokens that user can get back from the market
* if user put in certain amount of the other token
* @param inTokenReserve market reserve details of token that user wants to put in
* @param outTokenReserve market reserve details of token that user wants to get back
* @param exactIn exact amount of token that user wants to put in
* @param swapFee swap fee (percentage) for swap
* @dev The formula for this function can be referred in the AMM Specs
*/
function _calcExactOut(
TokenReserve memory inTokenReserve,
TokenReserve memory outTokenReserve,
uint256 exactIn,
uint256 swapFee
) internal pure returns (uint256 exactOut) {
uint256 weightRatio = Math.rdiv(inTokenReserve.weight, outTokenReserve.weight);
uint256 adjustedIn = Math.RONE.sub(swapFee);
adjustedIn = Math.rmul(exactIn, adjustedIn);
uint256 y = Math.rdiv(inTokenReserve.balance, inTokenReserve.balance.add(adjustedIn));
uint256 foo = Math.rpow(y, weightRatio);
uint256 bar = Math.RONE.sub(foo);
exactOut = Math.rmul(outTokenReserve.balance, bar);
}
/**
* @notice to calculate exact amount of lp token to be minted if single token liquidity is added to market
* @param inAmount exact amount of the token that user wants to put in
* @param inTokenReserve market reserve details of the token that user wants to put in
* @param swapFee swap fee (percentage) for swap
* @param totalSupplyLp current (before adding liquidity) lp supply
* @dev swap fee applies here since add liquidity by single token is equivalent of a swap
* @dev used when add liquidity by single token
* @dev The formula for this function can be referred in the AMM Specs
*/
function _calcOutAmountLp(
uint256 inAmount,
TokenReserve memory inTokenReserve,
uint256 swapFee,
uint256 totalSupplyLp
) internal pure returns (uint256 exactOutLp) {
uint256 nWeight = inTokenReserve.weight;
uint256 feePortion = Math.rmul(Math.RONE.sub(nWeight), swapFee);
uint256 inAmountAfterFee = Math.rmul(inAmount, Math.RONE.sub(feePortion));
uint256 inBalanceUpdated = inTokenReserve.balance.add(inAmountAfterFee);
uint256 inTokenRatio = Math.rdiv(inBalanceUpdated, inTokenReserve.balance);
uint256 lpTokenRatio = Math.rpow(inTokenRatio, nWeight);
uint256 totalSupplyLpUpdated = Math.rmul(lpTokenRatio, totalSupplyLp);
exactOutLp = totalSupplyLpUpdated.sub(totalSupplyLp);
return exactOutLp;
}
/**
* @notice to calculate exact amount of token that user can get back if
* single token liquidity is removed from market
* @param outTokenReserve market reserve details of the token that user wants to get back
* @param totalSupplyLp current (before adding liquidity) lp supply
* @param inLp exact amount of the lp token (single liquidity to remove) that user wants to put in
* @param swapFee swap fee (percentage) for swap
* @dev swap fee applies here since add liquidity by single token is equivalent of a swap
* @dev used when remove liquidity by single token
* @dev The formula for this function can be referred in the AMM Specs
*/
function _calcOutAmountToken(
TokenReserve memory outTokenReserve,
uint256 totalSupplyLp,
uint256 inLp,
uint256 swapFee
) internal pure returns (uint256 exactOutToken) {
uint256 nWeight = outTokenReserve.weight;
uint256 totalSupplyLpUpdated = totalSupplyLp.sub(inLp);
uint256 lpRatio = Math.rdiv(totalSupplyLpUpdated, totalSupplyLp);
uint256 outTokenRatio = Math.rpow(lpRatio, Math.rdiv(Math.RONE, nWeight));
uint256 outTokenBalanceUpdated = Math.rmul(outTokenRatio, outTokenReserve.balance);
uint256 outAmountTokenBeforeSwapFee = outTokenReserve.balance.sub(outTokenBalanceUpdated);
uint256 feePortion = Math.rmul(Math.RONE.sub(nWeight), swapFee);
exactOutToken = Math.rmul(outAmountTokenBeforeSwapFee, Math.RONE.sub(feePortion));
return exactOutToken;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../core/PendleGovernanceManager.sol";
import "../interfaces/IPermissionsV2.sol";
abstract contract PermissionsV2 is IPermissionsV2 {
PendleGovernanceManager public immutable override governanceManager;
address internal initializer;
constructor(address _governanceManager) {
require(_governanceManager != address(0), "ZERO_ADDRESS");
initializer = msg.sender;
governanceManager = PendleGovernanceManager(_governanceManager);
}
modifier initialized() {
require(initializer == address(0), "NOT_INITIALIZED");
_;
}
modifier onlyGovernance() {
require(msg.sender == _governance(), "ONLY_GOVERNANCE");
_;
}
function _governance() internal view returns (address) {
return governanceManager.governance();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
contract PendleGovernanceManager {
address public governance;
address public pendingGovernance;
event GovernanceClaimed(address newGovernance, address previousGovernance);
event TransferGovernancePending(address pendingGovernance);
constructor(address _governance) {
require(_governance != address(0), "ZERO_ADDRESS");
governance = _governance;
}
modifier onlyGovernance() {
require(msg.sender == governance, "ONLY_GOVERNANCE");
_;
}
/**
* @dev Allows the pendingGovernance address to finalize the change governance process.
*/
function claimGovernance() external {
require(pendingGovernance == msg.sender, "WRONG_GOVERNANCE");
emit GovernanceClaimed(pendingGovernance, governance);
governance = pendingGovernance;
pendingGovernance = address(0);
}
/**
* @dev Allows the current governance to set the pendingGovernance address.
* @param _governance The address to transfer ownership to.
*/
function transferGovernance(address _governance) external onlyGovernance {
require(_governance != address(0), "ZERO_ADDRESS");
pendingGovernance = _governance;
emit TransferGovernancePending(pendingGovernance);
}
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
pragma abicoder v2;
import "../core/PendleGovernanceManager.sol";
interface IPermissionsV2 {
function governanceManager() external returns (PendleGovernanceManager);
}
// 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;
/*
* @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-2.0-or-later
pragma solidity ^0.7.0;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
library Math {
using SafeMath for uint256;
uint256 internal constant BIG_NUMBER = (uint256(1) << uint256(200));
uint256 internal constant PRECISION_BITS = 40;
uint256 internal constant RONE = uint256(1) << PRECISION_BITS;
uint256 internal constant PI = (314 * RONE) / 10**2;
uint256 internal constant PI_PLUSONE = (414 * RONE) / 10**2;
uint256 internal constant PRECISION_POW = 1e2;
function checkMultOverflow(uint256 _x, uint256 _y) internal pure returns (bool) {
if (_y == 0) return false;
return (((_x * _y) / _y) != _x);
}
/**
@notice find the integer part of log2(p/q)
=> find largest x s.t p >= q * 2^x
=> find largest x s.t 2^x <= p / q
*/
function log2Int(uint256 _p, uint256 _q) internal pure returns (uint256) {
uint256 res = 0;
uint256 remain = _p / _q;
while (remain > 0) {
res++;
remain /= 2;
}
return res - 1;
}
/**
@notice log2 for a number that it in [1,2)
@dev _x is FP, return a FP
@dev function is from Kyber. Long modified the condition to be (_x >= one) && (_x < two)
to avoid the case where x = 2 may lead to incorrect result
*/
function log2ForSmallNumber(uint256 _x) internal pure returns (uint256) {
uint256 res = 0;
uint256 one = (uint256(1) << PRECISION_BITS);
uint256 two = 2 * one;
uint256 addition = one;
require((_x >= one) && (_x < two), "MATH_ERROR");
require(PRECISION_BITS < 125, "MATH_ERROR");
for (uint256 i = PRECISION_BITS; i > 0; i--) {
_x = (_x * _x) / one;
addition = addition / 2;
if (_x >= two) {
_x = _x / 2;
res += addition;
}
}
return res;
}
/**
@notice log2 of (p/q). returns result in FP form
@dev function is from Kyber.
@dev _p & _q is FP, return a FP
*/
function logBase2(uint256 _p, uint256 _q) internal pure returns (uint256) {
uint256 n = 0;
if (_p > _q) {
n = log2Int(_p, _q);
}
require(n * RONE <= BIG_NUMBER, "MATH_ERROR");
require(!checkMultOverflow(_p, RONE), "MATH_ERROR");
require(!checkMultOverflow(n, RONE), "MATH_ERROR");
require(!checkMultOverflow(uint256(1) << n, _q), "MATH_ERROR");
uint256 y = (_p * RONE) / (_q * (uint256(1) << n));
uint256 log2Small = log2ForSmallNumber(y);
assert(log2Small <= BIG_NUMBER);
return n * RONE + log2Small;
}
/**
@notice calculate ln(p/q). returned result >= 0
@dev function is from Kyber.
@dev _p & _q is FP, return a FP
*/
function ln(uint256 p, uint256 q) internal pure returns (uint256) {
uint256 ln2Numerator = 6931471805599453094172;
uint256 ln2Denomerator = 10000000000000000000000;
uint256 log2x = logBase2(p, q);
require(!checkMultOverflow(ln2Numerator, log2x), "MATH_ERROR");
return (ln2Numerator * log2x) / ln2Denomerator;
}
/**
@notice extract the fractional part of a FP
@dev value is a FP, return a FP
*/
function fpart(uint256 value) internal pure returns (uint256) {
return value % RONE;
}
/**
@notice convert a FP to an Int
@dev value is a FP, return an Int
*/
function toInt(uint256 value) internal pure returns (uint256) {
return value / RONE;
}
/**
@notice convert an Int to a FP
@dev value is an Int, return a FP
*/
function toFP(uint256 value) internal pure returns (uint256) {
return value * RONE;
}
/**
@notice return e^exp in FP form
@dev estimation by formula at http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html
the function is based on exp function of:
https://github.com/NovakDistributed/macroverse/blob/master/contracts/RealMath.sol
@dev the function is expected to converge quite fast, after about 20 iteration
@dev exp is a FP, return a FP
*/
function rpowe(uint256 exp) internal pure returns (uint256) {
uint256 res = 0;
uint256 curTerm = RONE;
for (uint256 n = 0; ; n++) {
res += curTerm;
curTerm = rmul(curTerm, rdiv(exp, toFP(n + 1)));
if (curTerm == 0) {
break;
}
if (n == 500) {
/*
testing shows that in the most extreme case, it will take 430 turns to converge.
however, it's expected that the numbers will not exceed 2^120 in normal situation
the most extreme case is rpow((1<<256)-1,(1<<40)-1) (equal to rpow((2^256-1)/2^40,0.99..9))
*/
revert("RPOWE_SLOW_CONVERGE");
}
}
return res;
}
/**
@notice calculate base^exp with base and exp being FP int
@dev to improve accuracy, base^exp = base^(int(exp)+frac(exp))
= base^int(exp) * base^frac
@dev base & exp are FP, return a FP
*/
function rpow(uint256 base, uint256 exp) internal pure returns (uint256) {
if (exp == 0) {
// Anything to the 0 is 1
return RONE;
}
if (base == 0) {
// 0 to anything except 0 is 0
return 0;
}
uint256 frac = fpart(exp); // get the fractional part
uint256 whole = exp - frac;
uint256 wholePow = rpowi(base, toInt(whole)); // whole is a FP, convert to Int
uint256 fracPow;
// instead of calculating base ^ frac, we will calculate e ^ (frac*ln(base))
if (base < RONE) {
/* since the base is smaller than 1.0, ln(base) < 0.
Since 1 / (e^(frac*ln(1/base))) = e ^ (frac*ln(base)),
we will calculate 1 / (e^(frac*ln(1/base))) instead.
*/
uint256 newExp = rmul(frac, ln(rdiv(RONE, base), RONE));
fracPow = rdiv(RONE, rpowe(newExp));
} else {
/* base is greater than 1, calculate normally */
uint256 newExp = rmul(frac, ln(base, RONE));
fracPow = rpowe(newExp);
}
return rmul(wholePow, fracPow);
}
/**
@notice return base^exp with base in FP form and exp in Int
@dev this function use a technique called: exponentiating by squaring
complexity O(log(q))
@dev function is from Kyber.
@dev base is a FP, exp is an Int, return a FP
*/
function rpowi(uint256 base, uint256 exp) internal pure returns (uint256) {
uint256 res = exp % 2 != 0 ? base : RONE;
for (exp /= 2; exp != 0; exp /= 2) {
base = rmul(base, base);
if (exp % 2 != 0) {
res = rmul(res, base);
}
}
return res;
}
/**
@dev y is an Int, returns an Int
@dev babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
@dev from Uniswap
*/
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;
}
}
/**
@notice divide 2 FP, return a FP
@dev function is from Balancer.
@dev x & y are FP, return a FP
*/
function rdiv(uint256 x, uint256 y) internal pure returns (uint256) {
return (y / 2).add(x.mul(RONE)).div(y);
}
/**
@notice multiply 2 FP, return a FP
@dev function is from Balancer.
@dev x & y are FP, return a FP
*/
function rmul(uint256 x, uint256 y) internal pure returns (uint256) {
return (RONE / 2).add(x.mul(y)).div(RONE);
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function subMax0(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a - b : 0;
}
}
|
We only need to do _mintProtocolFees if there is a curveShift that follows
|
function swapExactIn(
address inToken,
uint256 inAmount,
address outToken,
uint256 minOutAmount
) external override returns (uint256 outAmount, PendingTransfer[2] memory transfers) {
checkAddRemoveSwapClaimAllowed(false);
if (checkNeedCurveShift()) {
_mintProtocolFees();
_curveShift();
}
TokenReserve memory inTokenReserve = parseTokenReserveData(inToken);
TokenReserve memory outTokenReserve = parseTokenReserveData(outToken);
inTokenReserve,
outTokenReserve,
inAmount,
data.swapFee()
);
require(outAmount >= minOutAmount, "HIGH_OUT_LIMIT");
inTokenReserve.balance = inTokenReserve.balance.add(inAmount);
outTokenReserve.balance = outTokenReserve.balance.sub(outAmount);
updateReserveData(outTokenReserve, outToken);
transfers[0].amount = inAmount;
transfers[0].isOut = false;
transfers[1].amount = outAmount;
transfers[1].isOut = true;
emit Sync(xytBalance, xytWeight, tokenBalance);
}
| 349,111
|
/**
*Submitted for verification at Etherscan.io on 2021-10-22
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
}
interface IWETH is IERC20 {
function deposit() external payable;
}
interface IDEXFactory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IDEXRouter {
function factory() external pure returns (IDEXFactory);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
interface ITokenConverter {
function convertViaWETH(
address _tokenA,
address _tokenB,
uint256 _amount
) external view returns (uint256);
function DEFAULT_FACTORY() external view returns (IDEXFactory);
}
abstract contract Auth {
address public owner;
mapping(address => bool) public isAuthorized;
constructor() {
owner = msg.sender;
isAuthorized[msg.sender] = true;
}
modifier onlyOwner() {
require(msg.sender == owner, "!OWNER");
_;
}
modifier authorized() {
require(isAuthorized[msg.sender], "!AUTHORIZED");
_;
}
function authorize(address adr) external onlyOwner {
isAuthorized[adr] = true;
}
function unauthorize(address adr) external onlyOwner {
isAuthorized[adr] = false;
}
function setAuthorizationMultiple(address[] memory adr, bool value) external onlyOwner {
for (uint256 i = 0; i < adr.length; i++) {
isAuthorized[adr[i]] = value;
}
}
function transferOwnership(address payable adr) external onlyOwner {
isAuthorized[owner] = false;
owner = adr;
isAuthorized[adr] = true;
emit OwnershipTransferred(adr);
}
event OwnershipTransferred(address owner);
}
contract DividendDistributor {
address public _token;
IWETH WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IERC20 public dividendToken;
IDEXRouter public router = IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
struct Share {
uint256 amount;
uint256 totalExcluded;
uint256 totalRealised;
uint256 index;
uint256 lastClaimed;
}
mapping(address => Share) public shares;
address[] shareholders;
uint256 public totalShares;
uint256 public totalDividends;
uint256 public totalDistributed;
uint256 public dividendsPerShare;
uint256 public _ACCURACY_ = 1e36;
uint256 public minPeriod = 30 minutes;
uint256 public minDistribution = 1e18;
uint256 public shareThreshold = 0;
uint256 public currentIndex;
uint256 public maxGas = 500000;
modifier onlyToken() {
require(msg.sender == _token);
_;
}
constructor(IERC20 _dividendToken) {
dividendToken = _dividendToken;
_token = msg.sender;
}
function setDistributionCriteria(
uint256 _minPeriod,
uint256 _minDistribution,
uint256 _shareThreshold
) external onlyToken {
minPeriod = _minPeriod;
minDistribution = _minDistribution;
shareThreshold = _shareThreshold;
}
function setMaxGas(uint256 gas) external onlyToken {
maxGas = gas;
}
function setShare(address shareholder, uint256 amount) external onlyToken {
Share storage _S = shares[shareholder];
if (_S.amount > 0) {
_sendDividend(shareholder);
if (amount < shareThreshold) _removeShareholder(shareholder);
} else if (amount >= shareThreshold) _addShareholder(shareholder);
totalShares -= _S.amount;
totalShares += amount;
_S.amount = amount;
_S.totalExcluded = _getCumulativeDividends(shareholder);
}
function deposit() external payable onlyToken {
uint256 gotDividendToken;
gotDividendToken = dividendToken.balanceOf(address(this));
if (address(dividendToken) == address(WETH)) {
WETH.deposit{value: msg.value}();
} else {
address[] memory path = new address[](2);
path[0] = address(WETH);
path[1] = address(dividendToken);
router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: msg.value}(
0,
path,
address(this),
block.timestamp
);
}
gotDividendToken = dividendToken.balanceOf(address(this)) - gotDividendToken;
totalDividends += gotDividendToken;
dividendsPerShare += (_ACCURACY_ * gotDividendToken) / totalShares;
}
function sendDividends() external onlyToken {
uint256 shareholderCount = shareholders.length;
if (shareholderCount == 0) return;
uint256 gasUsed;
uint256 gasLeft = gasleft();
uint256 _currentIndex = currentIndex;
for (uint256 i = 0; i < shareholderCount && gasUsed < maxGas; i++) {
if (_currentIndex >= shareholderCount) _currentIndex = 0;
address _shareholder = shareholders[_currentIndex];
if (
block.timestamp > shares[_shareholder].lastClaimed + minPeriod &&
getUnpaidEarnings(_shareholder) > minDistribution
) {
_sendDividend(_shareholder);
}
gasUsed += gasLeft - gasleft();
gasLeft = gasleft();
_currentIndex++;
}
currentIndex = _currentIndex;
}
function _getCumulativeDividends(address shareholder) internal view returns (uint256) {
return (shares[shareholder].amount * dividendsPerShare) / _ACCURACY_;
}
function _sendDividend(address shareholder) internal {
uint256 amount = getUnpaidEarnings(shareholder);
if (amount == 0) return;
dividendToken.transfer(shareholder, amount);
totalDistributed += amount;
shares[shareholder].totalRealised += amount;
shares[shareholder].totalExcluded = _getCumulativeDividends(shareholder);
shares[shareholder].lastClaimed = block.timestamp;
}
function _addShareholder(address shareholder) internal {
shares[shareholder].index = shareholders.length;
shareholders.push(shareholder);
}
function _removeShareholder(address shareholder) internal {
_sendDividend(shareholder);
shareholders[shares[shareholder].index] = shareholders[shareholders.length - 1];
shares[shareholders[shareholders.length - 1]].index = shares[shareholder].index;
delete shares[shareholder];
shareholders.pop();
}
function claimDividend() external {
_sendDividend(msg.sender);
}
function getUnpaidEarnings(address shareholder) public view returns (uint256) {
uint256 _dividends = _getCumulativeDividends(shareholder);
uint256 _excluded = shares[shareholder].totalExcluded;
return _dividends > _excluded ? _dividends - _excluded : 0;
}
}
contract HyperSonic is Auth {
address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address DEAD = 0x000000000000000000000000000000000000dEaD;
address ZERO = 0x0000000000000000000000000000000000000000;
ITokenConverter public TOKEN_CONVERTER = ITokenConverter(address(0));
string public constant name = "HyperSonic";
string public constant symbol = "HYPERSONIC";
uint8 public constant decimals = 18;
uint256 public constant totalSupply = 1e6 * 1e18;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
mapping(address => bool) public isFeeExempt;
mapping(address => bool) public isBuyLimitExempt;
mapping(address => bool) public isWalletLimitExempt;
mapping(address => bool) public isDividendExempt;
mapping(address => bool) public isPair;
mapping(address => bool) public isRouter;
bool public buyLimitEnabled = true;
uint256 public buyLimitBUSD = 5000e18;
uint256 public walletLimit = 5000e18;
IDEXRouter public router;
address public pair;
DividendDistributor public distributor;
uint256 public launchedAt;
bool public tradingOpen;
struct FeeSettings {
uint256 liquidity;
uint256 dividends;
uint256 total;
uint256 _burn;
uint256 _denominator;
}
struct SwapbackSettings {
bool enabled;
uint256 amount;
}
FeeSettings public fees =
FeeSettings({liquidity: 100, dividends: 300, total: 400, _burn: 100, _denominator: 10000});
SwapbackSettings public swapback = SwapbackSettings({enabled: true, amount: totalSupply / 1000});
bool inSwap;
modifier swapping() {
inSwap = true;
_;
inSwap = false;
}
event AutoLiquify(uint256 amountBNB, uint256 amountTKN);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor() {
// UNISWAP V2 ROUTER 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
router = IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
pair = router.factory().createPair(WETH, address(this));
allowance[address(this)][address(router)] = ~uint256(0);
distributor = new DividendDistributor(IERC20(WETH));
isFeeExempt[DEAD] = true;
isFeeExempt[msg.sender] = true;
isFeeExempt[address(this)] = true;
isFeeExempt[address(router)] = true;
isBuyLimitExempt[DEAD] = true;
isBuyLimitExempt[msg.sender] = true;
isBuyLimitExempt[address(this)] = true;
isBuyLimitExempt[address(router)] = true;
isWalletLimitExempt[DEAD] = true;
isWalletLimitExempt[msg.sender] = true;
isWalletLimitExempt[address(this)] = true;
isWalletLimitExempt[address(router)] = true;
isDividendExempt[DEAD] = true;
isDividendExempt[msg.sender] = true;
isDividendExempt[address(this)] = true;
isDividendExempt[address(router)] = true;
isDividendExempt[pair] = true;
isWalletLimitExempt[pair] = true;
isPair[pair] = true;
isRouter[address(router)] = true;
// Owner must manually whitelist DXSale presale contract
// isFeeExempt[_presaleContract] = true;
// isBuyLimitExempt[_presaleContract] = true;
// isDividendExempt[_presaleContract] = true;
balanceOf[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
receive() external payable {}
function getOwner() external view returns (address) {
return owner;
}
function approve(address spender, uint256 amount) public returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function approveMax(address spender) external returns (bool) {
return approve(spender, ~uint256(0));
}
function transfer(address recipient, uint256 amount) external returns (bool) {
return _transferFrom(msg.sender, recipient, amount);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool) {
if (allowance[sender][msg.sender] != ~uint256(0)) allowance[sender][msg.sender] -= amount;
return _transferFrom(sender, recipient, amount);
}
function _transferFrom(
address sender,
address recipient,
uint256 amount
) internal returns (bool) {
if (inSwap) return _basicTransfer(sender, recipient, amount);
if (!tradingOpen) require(isAuthorized[sender], "Trading not open yet");
bool _isBuy = isPair[sender] && !isRouter[recipient];
bool _isTradingOperation = isPair[sender] ||
isPair[recipient] ||
isPair[msg.sender] ||
isRouter[sender] ||
isRouter[recipient] ||
isRouter[msg.sender];
bool _isFirst24Hours = block.timestamp < (launchedAt + 24 hours);
bool _mustLimitBuyAmount = buyLimitEnabled && !isBuyLimitExempt[recipient];
bool _isTemporaryTaxFreeBuy = _isFirst24Hours && _isBuy;
// Limit wallet balance during first 24h
if (_isFirst24Hours && !isWalletLimitExempt[recipient])
require(balanceOf[recipient] + amount <= walletLimit, "Recipient balance limit exceeded");
// Limit BUY during first 24h
if (_isBuy && _mustLimitBuyAmount) {
uint256 _BUSDEquivalent = TOKEN_CONVERTER.convertViaWETH(address(this), USDT, amount);
if (_BUSDEquivalent > 0) require(_BUSDEquivalent <= buyLimitBUSD, "BUY limit exceeded");
}
// Sells accumulated fee for BNB and distribute
if (swapback.enabled && (balanceOf[address(this)] >= swapback.amount) && !_isTradingOperation) {
// (?swapback enabled?) Sells accumulated TKN fees for BNB
_sellAndDistributeAccumulatedTKNFee();
}
// Launch at first liquidity
if (launchedAt == 0 && isPair[recipient]) {
require(balanceOf[sender] > 0);
launchedAt = block.timestamp;
}
// Take fee; burn;
// Exchange balances
balanceOf[sender] -= amount;
uint256 amountReceived = amount;
if (!isFeeExempt[sender] && !isFeeExempt[recipient] && !_isTemporaryTaxFreeBuy) {
if (fees.total > 0) {
uint256 feeAmount = (amount * fees.total) / fees._denominator;
balanceOf[address(this)] += feeAmount;
emit Transfer(sender, address(this), feeAmount);
amountReceived -= feeAmount;
}
if (fees._burn > 0) {
uint256 burnAmount = (amount * fees._burn) / fees._denominator;
balanceOf[DEAD] += burnAmount;
emit Transfer(sender, DEAD, burnAmount);
amountReceived -= burnAmount;
}
}
balanceOf[recipient] += amountReceived;
emit Transfer(sender, recipient, amountReceived);
// Dividend tracker
if (!isDividendExempt[sender]) try distributor.setShare(sender, balanceOf[sender]) {} catch {}
if (!isDividendExempt[recipient]) try distributor.setShare(recipient, balanceOf[recipient]) {} catch {}
try distributor.sendDividends() {} catch {}
return true;
}
function _basicTransfer(
address sender,
address recipient,
uint256 amount
) internal returns (bool) {
balanceOf[sender] -= amount;
balanceOf[recipient] += amount;
emit Transfer(sender, recipient, amount);
return true;
}
function _sellAndDistributeAccumulatedTKNFee() internal swapping {
// Swap the fee taken above to BNB and distribute to liquidity and dividends;
// Add some liquidity
uint256 halfLiquidityFee = fees.liquidity / 2;
uint256 TKNtoLiquidity = (swapback.amount * halfLiquidityFee) / fees.total;
uint256 amountToSwap = swapback.amount - TKNtoLiquidity;
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = WETH;
uint256 gotBNB = address(this).balance;
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amountToSwap,
0,
path,
address(this),
block.timestamp
);
gotBNB = address(this).balance - gotBNB;
uint256 totalBNBFee = fees.total - halfLiquidityFee;
uint256 BNBtoLiquidity = (gotBNB * halfLiquidityFee) / totalBNBFee;
uint256 BNBtoDividends = (gotBNB * fees.dividends) / totalBNBFee;
try distributor.deposit{value: BNBtoDividends}() {} catch {}
if (TKNtoLiquidity > 0) {
router.addLiquidityETH{value: BNBtoLiquidity}(address(this), TKNtoLiquidity, 0, 0, owner, block.timestamp);
emit AutoLiquify(BNBtoLiquidity, TKNtoLiquidity);
}
}
function _sellBNB(uint256 amount, address to) internal swapping {
address[] memory path = new address[](2);
path[0] = WETH;
path[1] = address(this);
router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(0, path, to, block.timestamp);
}
function getCirculatingSupply() public view returns (uint256) {
return totalSupply - balanceOf[DEAD] - balanceOf[ZERO];
}
// SET EXEMPTS
function setIsFeeExempt(address[] memory holders, bool exempt) public onlyOwner {
for (uint256 i = 0; i < holders.length; i++) {
isFeeExempt[holders[i]] = exempt;
}
}
function setIsBuyLimitExempt(address[] memory holders, bool exempt) public onlyOwner {
for (uint256 i = 0; i < holders.length; i++) {
isBuyLimitExempt[holders[i]] = exempt;
}
}
function setIsWalletLimitExempt(address[] memory holders, bool exempt) public onlyOwner {
for (uint256 i = 0; i < holders.length; i++) {
isWalletLimitExempt[holders[i]] = exempt;
}
}
function setIsDividendExempt(address[] memory holders, bool exempt) public onlyOwner {
for (uint256 i = 0; i < holders.length; i++) {
require(holders[i] != address(this) && !(isPair[holders[i]] && !exempt)); // Forbid including back token and pairs
isDividendExempt[holders[i]] = exempt;
distributor.setShare(holders[i], exempt ? 0 : balanceOf[holders[i]]);
}
}
function setFullExempt(address[] memory holders, bool exempt) public onlyOwner {
setIsFeeExempt(holders, exempt);
setIsBuyLimitExempt(holders, exempt);
setIsWalletLimitExempt(holders, exempt);
setIsDividendExempt(holders, exempt);
}
function setIsPair(address[] memory addresses, bool isPair_) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
isPair[addresses[i]] = isPair_;
}
setIsDividendExempt(addresses, isPair_);
setIsWalletLimitExempt(addresses, isPair_);
}
function setIsRouter(address[] memory addresses, bool isRouter_) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
isRouter[addresses[i]] = isRouter_;
}
setFullExempt(addresses, isRouter_);
}
// TOKEN SETTINGS
function setBuyLimitSettings(uint256 amount, bool enabled) external onlyOwner {
buyLimitBUSD = amount;
buyLimitEnabled = enabled;
}
function setWalletLimitSettings(uint256 amount) external onlyOwner {
walletLimit = amount;
}
function setFees(
uint256 _liquidity,
uint256 _dividends,
uint256 _burn,
uint256 _denominator
) external onlyOwner {
fees = FeeSettings({
liquidity: _liquidity,
dividends: _dividends,
total: _liquidity + _dividends,
_burn: _burn,
_denominator: _denominator
});
require(fees.total + _burn < fees._denominator / 4);
}
function setSwapBackSettings(bool _enabled, uint256 _amount) external onlyOwner {
swapback.enabled = _enabled;
swapback.amount = _amount;
}
function setTradingStatus(bool _status) external onlyOwner {
tradingOpen = _status;
}
// DISTRIBUTOR SETTINGS
function deployNewDistributor(IERC20 _dividendToken) external onlyOwner {
distributor = new DividendDistributor(_dividendToken);
}
function setDistributionCriteria(
uint256 _minPeriod,
uint256 _minDistribution,
uint256 _shareThreshold
) external onlyOwner {
distributor.setDistributionCriteria(_minPeriod, _minDistribution, _shareThreshold);
}
function setDistributorGas(uint256 gas) external onlyOwner {
require(gas <= 750000, "Max 750000 gas allowed");
distributor.setMaxGas(gas);
}
function setTokenConverter(ITokenConverter tokenConverter) external onlyOwner {
TOKEN_CONVERTER = tokenConverter;
}
/* Airdrop Begins */
function makeItRain(address[] memory addresses, uint256[] memory tokens) external onlyOwner {
uint256 showerCapacity = 0;
require(addresses.length == tokens.length, "Mismatch between Address and token count");
for (uint256 i = 0; i < addresses.length; i++) showerCapacity += tokens[i];
require(balanceOf[msg.sender] >= showerCapacity, "Not enough tokens to airdrop");
for (uint256 i = 0; i < addresses.length; i++) _basicTransfer(msg.sender, addresses[i], tokens[i]);
}
}
|
Limit wallet balance during first 24h Limit BUY during first 24h Sells accumulated fee for BNB and distribute (?swapback enabled?) Sells accumulated TKN fees for BNB Launch at first liquidity
|
function _transferFrom(
address sender,
address recipient,
uint256 amount
) internal returns (bool) {
if (inSwap) return _basicTransfer(sender, recipient, amount);
if (!tradingOpen) require(isAuthorized[sender], "Trading not open yet");
bool _isBuy = isPair[sender] && !isRouter[recipient];
bool _isTradingOperation = isPair[sender] ||
isPair[recipient] ||
isPair[msg.sender] ||
isRouter[sender] ||
isRouter[recipient] ||
isRouter[msg.sender];
bool _isFirst24Hours = block.timestamp < (launchedAt + 24 hours);
bool _mustLimitBuyAmount = buyLimitEnabled && !isBuyLimitExempt[recipient];
bool _isTemporaryTaxFreeBuy = _isFirst24Hours && _isBuy;
if (_isFirst24Hours && !isWalletLimitExempt[recipient])
require(balanceOf[recipient] + amount <= walletLimit, "Recipient balance limit exceeded");
if (_isBuy && _mustLimitBuyAmount) {
uint256 _BUSDEquivalent = TOKEN_CONVERTER.convertViaWETH(address(this), USDT, amount);
if (_BUSDEquivalent > 0) require(_BUSDEquivalent <= buyLimitBUSD, "BUY limit exceeded");
}
if (swapback.enabled && (balanceOf[address(this)] >= swapback.amount) && !_isTradingOperation) {
_sellAndDistributeAccumulatedTKNFee();
}
if (launchedAt == 0 && isPair[recipient]) {
require(balanceOf[sender] > 0);
launchedAt = block.timestamp;
}
uint256 amountReceived = amount;
if (!isFeeExempt[sender] && !isFeeExempt[recipient] && !_isTemporaryTaxFreeBuy) {
if (fees.total > 0) {
uint256 feeAmount = (amount * fees.total) / fees._denominator;
balanceOf[address(this)] += feeAmount;
emit Transfer(sender, address(this), feeAmount);
amountReceived -= feeAmount;
}
if (fees._burn > 0) {
uint256 burnAmount = (amount * fees._burn) / fees._denominator;
balanceOf[DEAD] += burnAmount;
emit Transfer(sender, DEAD, burnAmount);
amountReceived -= burnAmount;
}
}
balanceOf[recipient] += amountReceived;
emit Transfer(sender, recipient, amountReceived);
return true;
}
| 6,817,698
|
pragma solidity ^0.4.24;
contract SafeMath {
function safeMul(uint a, uint b) pure internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) pure internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) pure internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ErrorReporter {
/**
* @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);
enum Error {
NO_ERROR,
INVALIDE_ADMIN,
WITHDRAW_TOKEN_AMOUNT_ERROR,
WITHDRAW_TOKEN_TRANSER_ERROR,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TRANSFER_FROM_ERROR,
LENDER_INSUFFICIENT_BORROW_ALLOWANCE,
LENDER_INSUFFICIENT_BORROWER_BALANCE,
LENDER_TRANSFER_FROM_BORROW_ERROR,
LENDER_INSUFFICIENT_ADMIN_ALLOWANCE,
LENDER_INSUFFICIENT_ADMIN_BALANCE,
LENDER_TRANSFER_FROM_ADMIN_ERROR,
CALL_MARGIN_ALLOWANCE_ERROR,
CALL_MARGIN_BALANCE_ERROR,
CALL_MARGIN_TRANSFER_ERROR,
REPAY_ALLOWANCE_ERROR,
REPAY_BALANCE_ERROR,
REPAY_TX_ERROR,
FORCE_REPAY_ALLOWANCE_ERROR,
FORCE_REPAY_BALANCE_ERROR,
FORCE_REPAY_TX_ERROR,
CLOSE_POSITION_ALLOWANCE_ERROR,
CLOSE_POSITION_TX_ERROR,
CLOSE_POSITION_MUST_ADMIN_BEFORE_DEADLINE,
CLOSE_POSITION_MUST_ADMIN_OR_LENDER_AFTER_DEADLINE,
LENDER_TEST_TRANSFER_ADMIN_ERROR,
LENDER_TEST_TRANSFER_BORROWR_ERROR,
LENDER_TEST_TRANSFERFROM_ADMIN_ERROR,
LENDER_TEST_TRANSFERFROM_BORROWR_ERROR,
SEND_TOKEN_AMOUNT_ERROR,
SEND_TOKEN_TRANSER_ERROR
}
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err) internal returns (uint) {
emit Failure(uint(err));
return uint(err);
}
}
library ERC20AsmFn {
function isContract(address addr) internal {
assembly {
if iszero(extcodesize(addr)) { revert(0, 0) }
}
}
function handleReturnData() internal returns (bool result) {
assembly {
switch returndatasize()
case 0 { // not a std erc20
result := 1
}
case 32 { // std erc20
returndatacopy(0, 0, 32)
result := mload(0)
}
default { // anything else, should revert for safety
revert(0, 0)
}
}
}
function asmTransfer(address _erc20Addr, address _to, uint256 _value) internal returns (bool result) {
// Must be a contract addr first!
isContract(_erc20Addr);
// call return false when something wrong
require(_erc20Addr.call(bytes4(keccak256("transfer(address,uint256)")), _to, _value), "asmTransfer error");
// handle returndata
return handleReturnData();
}
function asmTransferFrom(address _erc20Addr, address _from, address _to, uint256 _value) internal returns (bool result) {
// Must be a contract addr first!
isContract(_erc20Addr);
// call return false when something wrong
require(_erc20Addr.call(bytes4(keccak256("transferFrom(address,address,uint256)")), _from, _to, _value), "asmTransferFrom error");
// handle returndata
return handleReturnData();
}
// function asmApprove(address _erc20Addr, address _spender, uint256 _value) internal returns (bool result) {
// // Must be a contract addr first!
// isContract(_erc20Addr);
// // call return false when something wrong
// require(_erc20Addr.call(bytes4(keccak256("approve(address,uint256)")), _spender, _value), "asmApprove error");
// // handle returndata
// return handleReturnData();
// }
}
contract TheForceLending is SafeMath, ErrorReporter {
using ERC20AsmFn for EIP20Interface;
enum OrderState {
ORDER_STATUS_PENDING,
ORDER_STATUS_ACCEPTED
}
struct Order_t {
bytes32 partner_id;
uint deadline;
OrderState state;
address borrower;
address lender;
uint lending_cycle;
address token_get;
uint amount_get;
address token_pledge;//tokenGive
uint amount_pledge;//amountGive
uint _nonce;
uint pledge_rate;
uint interest_rate;
uint fee_rate;
}
address public admin; //the admin address
address public offcialFeeAccount; //the account that will receive fees
mapping (bytes32 => address) public partnerAccounts;// bytes32-> address, eg: platformA->0xa{40}, platfromB->0xb{40}
mapping (bytes32 => mapping (address => mapping (address => uint))) public partnerTokens;// platform->tokenContract->address->balance
mapping (bytes32 => mapping (address => mapping (bytes32 => Order_t))) public partnerOrderBook;// platform->address->hash->order_t
event Borrow(bytes32 partnerId,
address tokenGet,
uint amountGet,
address tokenGive,
uint amountGive,
uint nonce,
uint lendingCycle,
uint pledgeRate,
uint interestRate,
uint feeRate,
address user,
bytes32 hash,
uint status);
event Lend(bytes32 partnerId, address borrower, bytes32 txId, address token, uint amount, address give, uint status);//txIdไธบๅๆฌพๅtxId
event CancelOrder(bytes32 partnerId, address borrower, bytes32 txId, address by, uint status);//ๅๆถๅๆฌพๅ๏ผๅช่ฝ่ขซborrowerๆ่
ๅ็บฆๅๆถ
event Callmargin(bytes32 partnerId, address borrower, bytes32 txId, address token, uint amount, address by, uint status);
event Repay(bytes32 partnerId, address borrower, bytes32 txId, address token, uint amount, address by, uint status);
event Closepstion(bytes32 partnerId, address borrower, bytes32 txId, address token, address by, uint status);
event Forcerepay(bytes32 partnerId, address borrower, bytes32 txId, address token, address by, uint status);
event Deposit(address token, address user, uint amount, uint balance);
event Withdraw(address token, address user, uint amount, uint balance);
event Send(address token, address user, address to, uint amount, uint balance);
constructor(address admin_, address offcialFeeAccount_) public {
admin = admin_;
offcialFeeAccount = offcialFeeAccount_;
}
function() public payable {
revert("fallback can't be payable");
}
modifier onlyAdmin() {
require(msg.sender == admin, "only admin can do this!");
_;
}
function changeAdmin(address admin_) public onlyAdmin {
admin = admin_;
}
function changeFeeAccount(address offcialFeeAccount_) public onlyAdmin {
offcialFeeAccount = offcialFeeAccount_;
}
//ๅข
function addPartner(bytes32 partnerId, address partner) public onlyAdmin {
require(partnerAccounts[partnerId] == address(0), "already exists!");
partnerAccounts[partnerId] = partner;
}
//ๅ
function delPartner(bytes32 partnerId) public onlyAdmin {
delete partnerAccounts[partnerId];
}
//ๆน
function modPartner(bytes32 partnerId, address partner) public onlyAdmin {
require(partnerAccounts[partnerId] != address(0), "not exists!");
partnerAccounts[partnerId] = partner;
}
//ๆฅ
function getPartner(bytes32 partnerId) public view returns (address) {
return partnerAccounts[partnerId];
}
function depositToken(bytes32 partnerId, address token, uint amount) internal returns (uint){
//remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf.
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
if (token == 0) revert("invalid token address!");
if (EIP20Interface(token).allowance(msg.sender, address(this)) < amount) {
return fail(Error.TOKEN_INSUFFICIENT_ALLOWANCE);
}
if (EIP20Interface(token).balanceOf(msg.sender) < amount) {
return fail(Error.TOKEN_INSUFFICIENT_ALLOWANCE);
}
if (!EIP20Interface(token).asmTransferFrom(msg.sender, address(this), amount)) {
return fail(Error.TRANSFER_FROM_ERROR);
}
partnerTokens[partnerId][token][msg.sender] = safeAdd(partnerTokens[partnerId][token][msg.sender], amount);
return 0;
}
function withdrawToken(bytes32 partnerId, address token, uint amount) internal returns (uint) {
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
if (token == 0) revert("invalid token address");
if (partnerTokens[partnerId][token][msg.sender] < amount) {
return fail(Error.WITHDRAW_TOKEN_AMOUNT_ERROR);
}
partnerTokens[partnerId][token][msg.sender] = safeSub(partnerTokens[partnerId][token][msg.sender], amount);
if (!EIP20Interface(token).asmTransfer(msg.sender, amount)) {
return fail(Error.WITHDRAW_TOKEN_TRANSER_ERROR);
}
return 0;
}
function sendToken(bytes32 partnerId, address token, address to, uint amount) internal returns (uint) {
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
if (token==0 || to == 0 || amount == 0) revert("invalid token address or amount");
if (partnerTokens[partnerId][token][to] < amount) {
return fail(Error.SEND_TOKEN_AMOUNT_ERROR);
}
partnerTokens[partnerId][token][to] = safeSub(partnerTokens[partnerId][token][to], amount);
if (!EIP20Interface(token).asmTransfer(to, amount)) {
return fail(Error.SEND_TOKEN_TRANSER_ERROR);
}
return 0;
}
function balanceOf(bytes32 partnerId, address token, address user) public view returns (uint) {
return partnerTokens[partnerId][token][user];
}
function borrow(bytes32 partnerId,//ๅนณๅฐๆ ่ฎฐ
address tokenGet, //ๅๅบๅธ็งๅฐๅ
uint amountGet, //ๅๅบๅธ็งๆฐ้
address tokenGive, //ๆตๆผๅธ็งๅฐๅ
uint amountGive,//ๆตๆผๅธ็งๆฐ้
uint nonce,
uint lendingCycle,
uint pledgeRate,
uint interestRate,
uint feeRate) public returns (bytes32 txId){
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
bytes32 txid = hash(partnerId, tokenGet, amountGet, tokenGive, amountGive, nonce, lendingCycle, pledgeRate, interestRate, feeRate);
uint status = 0;
partnerOrderBook[partnerId][msg.sender][txid] = Order_t({
partner_id: partnerId,
deadline: 0,
state: OrderState.ORDER_STATUS_PENDING,
borrower: msg.sender,
lender: address(0),
lending_cycle: lendingCycle,
token_get: tokenGet,
amount_get: amountGet,
token_pledge: tokenGive,
amount_pledge: amountGive,
_nonce: nonce,
pledge_rate: pledgeRate,
interest_rate: interestRate,
fee_rate: feeRate
});
status = depositToken(partnerId, tokenGive, amountGive);
emit Borrow(partnerId, tokenGet, amountGet, tokenGive, amountGive, nonce, lendingCycle, pledgeRate, interestRate, feeRate, msg.sender, txid, status);
return txid;
}
//Aๅๆฌพ๏ผBๅบๅ๏ผAๅฐ่ดฆๆฐ้ไธบ็ณ่ฏทๆฐ้๏ผๆ ็ ๅคดๆฏ๏ผBๅบๅ็ๆฐ้ๅ
ๆฌA็็ณ่ฏทๆฐ้+ๆ็ปญ่ดน(้กน็ฎๆนๆ็ปญ่ดน+ๅนณๅฐๅไฝๆนๆ็ปญ่ดน๏ผๆ็ปญ่ดนๅฏ่ฝไธบ0)
function lend(bytes32 partnerId, address borrower, bytes32 hash, address token, uint lenderAmount, uint offcialFeeAmount, uint partnerFeeAmount) public returns (uint) {
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");//order not found
require(partnerOrderBook[partnerId][borrower][hash].borrower != msg.sender, "cannot lend to self");//cannot lend to self
require(partnerOrderBook[partnerId][borrower][hash].token_get == token, "attempt to use an invalid type of token");//attempt to use an invalid type of token
require(partnerOrderBook[partnerId][borrower][hash].amount_get == lenderAmount - offcialFeeAmount - partnerFeeAmount, "amount_get != amount - offcialFeeAmount - partnerFeeAmount");//ๅไธชๅบๅ้้ขไธ่ถณ๏ผๅ็ปญๅฏไปฅ่่ๅคไธชๅบๅไบบ๏ผ็ฐๅจๅช่่ไธไธชๅบๅไบบ
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_PENDING, "state != OrderState.ORDER_STATUS_PENDING");
uint status = 0;
if (EIP20Interface(token).allowance(msg.sender, address(this)) < lenderAmount) {
status = uint(Error.TOKEN_INSUFFICIENT_ALLOWANCE);
}
if (status == 0 && EIP20Interface(token).balanceOf(msg.sender) < lenderAmount) {
status = uint(Error.LENDER_INSUFFICIENT_BORROWER_BALANCE);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, partnerOrderBook[partnerId][borrower][hash].borrower, partnerOrderBook[partnerId][borrower][hash].amount_get)) {
status = uint(Error.LENDER_TRANSFER_FROM_BORROW_ERROR);
}
if (offcialFeeAmount != 0) {
if (status == 0 && EIP20Interface(token).allowance(msg.sender, address(this)) < offcialFeeAmount) {
status = uint(Error.LENDER_INSUFFICIENT_ADMIN_ALLOWANCE);
}
if (status == 0 && EIP20Interface(token).balanceOf(msg.sender) < offcialFeeAmount) {
status = uint(Error.LENDER_INSUFFICIENT_ADMIN_BALANCE);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, offcialFeeAccount, offcialFeeAmount)) {
status = uint(Error.LENDER_TRANSFER_FROM_ADMIN_ERROR);
}
}
if (partnerFeeAmount != 0) {
if (status == 0 && EIP20Interface(token).allowance(msg.sender, address(this)) < partnerFeeAmount) {
status = uint(Error.LENDER_INSUFFICIENT_ADMIN_ALLOWANCE);
}
if (status == 0 && EIP20Interface(token).balanceOf(msg.sender) < partnerFeeAmount) {
status = uint(Error.LENDER_INSUFFICIENT_ADMIN_BALANCE);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, partnerAccounts[partnerId], partnerFeeAmount)) {
status = uint(Error.LENDER_TRANSFER_FROM_ADMIN_ERROR);
}
}
if (status == 0) {
partnerOrderBook[partnerId][borrower][hash].deadline = now + partnerOrderBook[partnerId][borrower][hash].lending_cycle * (1 minutes);
partnerOrderBook[partnerId][borrower][hash].lender = msg.sender;
partnerOrderBook[partnerId][borrower][hash].state = OrderState.ORDER_STATUS_ACCEPTED;
}
emit Lend(partnerId, borrower, hash, token, lenderAmount, msg.sender, status);
return 0;
}
function cancelOrder(bytes32 partnerId, address borrower, bytes32 hash) public {
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");//order not found
require(partnerOrderBook[partnerId][borrower][hash].borrower == msg.sender || msg.sender == admin,
"only borrower or admin can do this operation");//only borrower or contract can do this operation
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_PENDING, "state != OrderState.ORDER_STATUS_PENDING");
uint status = 0;
status = sendToken(partnerId, partnerOrderBook[partnerId][borrower][hash].token_pledge, partnerOrderBook[partnerId][borrower][hash].borrower, partnerOrderBook[partnerId][borrower][hash].amount_pledge);
if (status == 0) {
delete partnerOrderBook[partnerId][borrower][hash];
}
emit CancelOrder(partnerId, borrower, hash, msg.sender, status);
}
function callmargin(bytes32 partnerId, address borrower, bytes32 hash, address token, uint amount) public returns (uint){
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");
require(amount > 0, "amount must >0");
require(token != address(0), "invalid token");
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_ACCEPTED, "state != OrderState.ORDER_STATUS_ACCEPTED");
require(partnerOrderBook[partnerId][borrower][hash].token_pledge == token, "invalid pledge token");
uint status = 0;
if (status == 0 && EIP20Interface(token).allowance(msg.sender, address(this)) < amount) {
status = uint(Error.CALL_MARGIN_ALLOWANCE_ERROR);
}
if (status == 0) {
partnerOrderBook[partnerId][borrower][hash].amount_pledge += amount;
partnerTokens[partnerId][token][borrower] = safeAdd(partnerTokens[partnerId][token][borrower], amount);
}
if (status == 0 && EIP20Interface(token).balanceOf(msg.sender) < amount) {
status = uint(Error.CALL_MARGIN_BALANCE_ERROR);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, address(this), amount)) {
status = uint(Error.CALL_MARGIN_TRANSFER_ERROR);
}
emit Callmargin(partnerId, borrower, hash, token, amount, msg.sender, status);
return 0;
}
//A่ฟๆฌพ๏ผ้่ฆๆฏไปๆฌ้+ๅฉๆฏ็ปๅบๅๆน๏ผ็ป้กน็ฎๆนๅๅนณๅฐๅไฝๆนๆ็ปญ่ดน
function repay(bytes32 partnerId, address borrower, bytes32 hash, address token, uint repayAmount, uint lenderAmount, uint offcialFeeAmount, uint partnerFeeAmount) public returns (uint){
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_ACCEPTED, "state != OrderState.ORDER_STATUS_ACCEPTED");
require(token != address(0), "invalid token");
require(token == partnerOrderBook[partnerId][borrower][hash].token_get, "invalid repay token");
//่ฟๆฌพๆฐ้๏ผไธบๅๆฌพๆฐ้ๅ ไธๅฉๆฏๅ ไธ้กน็ฎๆนๆ็ปญ่ดน+ๅไฝๆนๆ็ปญ่ดน
require(repayAmount == lenderAmount + offcialFeeAmount + partnerFeeAmount, "invalid repay amount");
require(lenderAmount >= partnerOrderBook[partnerId][borrower][hash].amount_get, "invalid lender amount");
require(msg.sender == partnerOrderBook[partnerId][borrower][hash].borrower, "invalid repayer, must be borrower");
uint status = 0;
//ๅ
่ฎธcontract่ฑ่ดนๅๆฌพ่
็ๆๅ็token+ๅฉๆฏtoken
if (status == 0 && EIP20Interface(token).allowance(msg.sender, address(this)) < repayAmount) {
status = uint(Error.REPAY_ALLOWANCE_ERROR);
}
if (status == 0 && EIP20Interface(token).balanceOf(msg.sender) < repayAmount) {
status = uint(Error.REPAY_BALANCE_ERROR);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, partnerOrderBook[partnerId][borrower][hash].lender, lenderAmount)) {
status = uint(Error.REPAY_TX_ERROR);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, offcialFeeAccount, offcialFeeAmount)) {
status = uint(Error.REPAY_TX_ERROR);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, partnerAccounts[partnerId], partnerFeeAmount)) {
status = uint(Error.REPAY_TX_ERROR);
}
if (status == 0) {
status = withdrawToken(partnerId, partnerOrderBook[partnerId][borrower][hash].token_pledge, partnerOrderBook[partnerId][borrower][hash].amount_pledge);
}
if (status == 0) {
delete partnerOrderBook[partnerId][borrower][hash];
}
emit Repay(partnerId, borrower, hash, token, repayAmount, msg.sender, status);
return status;
}
//้พๆๅผบๅถๅฝ่ฟ๏ผ็ฑๅ็บฆ็ฎก็่
่ฐ็จ๏ผ้borrower๏ผ้lender่ฐ็จ๏ผborrower้่ฆๆฏไปๆตๆผ่ตไบง็ปๅบๅไบบ๏ผๆฌ้+ๅฉๆฏ๏ผ๏ผๅนณๅฐๅไฝๆน๏ผๆ็ปญ่ดน๏ผๅ้กน็ฎๆน๏ผๆ็ปญ่ดน๏ผ๏ผๅฆๆ่ฟๆๅฉไฝ๏ผๅฉไฝ้จๅๅฝ่ฟ็ปA
function forcerepay(bytes32 partnerId, address borrower, bytes32 hash, address token, uint lenderAmount, uint offcialFeeAmount, uint partnerFeeAmount) public returns (uint){
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");
require(token != address(0), "invalid forcerepay token address");
require(token == partnerOrderBook[partnerId][borrower][hash].token_pledge, "invalid forcerepay token");
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_ACCEPTED, "state != OrderState.ORDER_STATUS_ACCEPTED");
require(msg.sender == admin, "forcerepay must be admin");
require(now > partnerOrderBook[partnerId][borrower][hash].deadline, "cannot forcerepay before deadline");
uint status = 0;
//ๅ็บฆ็ฎก็ๅๅ้ๆตๆผ่ตไบงๅฐๅบๅไบบ,ๆฐ้็ฑไธๅฑไผ ๅ
ฅ
partnerTokens[partnerId][token][borrower] = safeSub(partnerTokens[partnerId][token][borrower], lenderAmount);
if (!EIP20Interface(token).asmTransfer(partnerOrderBook[partnerId][borrower][hash].lender, lenderAmount)) {
status = uint(Error.FORCE_REPAY_TX_ERROR);
}
//ๅ็บฆ็ฎก็ๅๅ้ๆตๆผ่ตไบงๅฐๅนณๅฐๅไฝๆน,ๆฐ้็ฑไธๅฑไผ ๅ
ฅ
partnerTokens[partnerId][token][borrower] = safeSub(partnerTokens[partnerId][token][borrower], partnerFeeAmount);
if (!EIP20Interface(token).asmTransfer(partnerAccounts[partnerId], partnerFeeAmount)) {
status = uint(Error.FORCE_REPAY_TX_ERROR);
}
//ๅ็บฆ็ฎก็ๅๅ้ๆตๆผ่ตไบงๅฐ้กน็ฎๆน,ๆฐ้็ฑไธๅฑไผ ๅ
ฅ
partnerTokens[partnerId][token][borrower] = safeSub(partnerTokens[partnerId][token][borrower], offcialFeeAmount);
if (!EIP20Interface(token).asmTransfer(offcialFeeAccount, offcialFeeAmount)) {
status = uint(Error.FORCE_REPAY_TX_ERROR);
}
//ๅ็บฆ็ฎก็ๅๅ้ๅฉไฝๆตๆผ่ตไบงๅฐๅๆฌพๆน,ๆฐ้็ฑไธๅฑไผ ๅ
ฅ
if (partnerTokens[partnerId][token][borrower] > 0) {
if (!EIP20Interface(token).asmTransfer(borrower, partnerTokens[partnerId][token][borrower])) {
status = uint(Error.FORCE_REPAY_TX_ERROR);
} else {
partnerTokens[partnerId][token][borrower] = 0;
}
}
if (status == 0) {
delete partnerOrderBook[partnerId][borrower][hash];
}
emit Forcerepay(partnerId, borrower, hash, token, msg.sender, status);
return status;
}
//ไปทๆ ผๆณขๅจๅนณไป๏ผborrower้่ฆๆฏไปๆตๆผ่ตไบง็ปๅบๅไบบ๏ผๆฌ้+ๅฉๆฏ๏ผ๏ผ้กน็ฎๆน๏ผๆ็ปญ่ดน๏ผๅๅนณๅฐๅไฝๆน๏ผๆ็ปญ่ดน๏ผ๏ผๅฆๆ่ฟๆๅฉไฝ๏ผๅฉไฝ้จๅๅฝ่ฟ็ปA
function closepstion(bytes32 partnerId, address borrower, bytes32 hash, address token, uint lenderAmount, uint offcialFeeAmount, uint partnerFeeAmount) public returns (uint){
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");
require(token != address(0), "invalid token");
require(token == partnerOrderBook[partnerId][borrower][hash].token_pledge, "invalid token");
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_ACCEPTED, "state != OrderState.ORDER_STATUS_ACCEPTED");
require(msg.sender == admin, "closepstion must be admin");
uint status = 0;
//ๆช้พๆ
if (partnerOrderBook[partnerId][borrower][hash].deadline > now) {
if (msg.sender != admin) {
//only admin of this contract can do this operation before deadline
status = uint(Error.CLOSE_POSITION_MUST_ADMIN_BEFORE_DEADLINE);
}
} else {
if (!(msg.sender == admin || msg.sender == partnerOrderBook[partnerId][borrower][hash].lender)) {
//only lender or admin of this contract can do this operation
status = uint(Error.CLOSE_POSITION_MUST_ADMIN_OR_LENDER_AFTER_DEADLINE);
}
}
if (status == 0) {
//ๅ็บฆ็ฎก็ๅๅ้ๆตๆผ่ตไบงๅฐๅบๅไบบ,ๆฐ้็ฑไธๅฑไผ ๅ
ฅ
partnerTokens[partnerId][token][borrower] = safeSub(partnerTokens[partnerId][token][borrower], lenderAmount);
if (!EIP20Interface(token).asmTransfer(partnerOrderBook[partnerId][borrower][hash].lender, lenderAmount)) {
status = uint(Error.CLOSE_POSITION_TX_ERROR);
}
//ๅ็บฆ็ฎก็ๅๅ้ๆตๆผ่ตไบงๅฐๅนณๅฐๅไฝๆน,ๆฐ้็ฑไธๅฑไผ ๅ
ฅ
partnerTokens[partnerId][token][borrower] = safeSub(partnerTokens[partnerId][token][borrower], partnerFeeAmount);
if (!EIP20Interface(token).asmTransfer(partnerAccounts[partnerId], partnerFeeAmount)) {
status = uint(Error.CLOSE_POSITION_TX_ERROR);
}
//ๅ็บฆ็ฎก็ๅๅ้ๆตๆผ่ตไบงๅฐ้กน็ฎๆน,ๆฐ้็ฑไธๅฑไผ ๅ
ฅ
partnerTokens[partnerId][token][borrower] = safeSub(partnerTokens[partnerId][token][borrower], offcialFeeAmount);
if (!EIP20Interface(token).asmTransfer(offcialFeeAccount, offcialFeeAmount)) {
status = uint(Error.CLOSE_POSITION_TX_ERROR);
}
//ๅ็บฆ็ฎก็ๅๅ้ๅฉไฝๆตๆผ่ตไบงๅฐๅๆฌพๆน,ๆฐ้็ฑไธๅฑไผ ๅ
ฅ
if (partnerTokens[partnerId][token][borrower] > 0) {
if (!EIP20Interface(token).asmTransfer(borrower, partnerTokens[partnerId][token][borrower])) {
status = uint(Error.CLOSE_POSITION_TX_ERROR);
} else {
partnerTokens[partnerId][token][borrower] = 0;
}
}
if (status == 0) {
delete partnerOrderBook[partnerId][borrower][hash];
}
}
emit Closepstion(partnerId, borrower, hash, token, address(this), status);
return status;
}
//ADDITIONAL HELPERS ADDED FOR TESTING
function hash(
bytes32 partnerId,
address tokenGet,
uint amountGet,
address tokenGive,
uint amountGive,
uint nonce,
uint lendingCycle,
uint pledgeRate,
uint interestRate,
uint feeRate
)
public
view
returns (bytes32)
{
//return sha256(this, tokenGet, amountGet, tokenGive, amountGive, nonce, lendingCycle, pledgeRate, interestRate, feeRate);
return sha256(abi.encodePacked(address(this), partnerId, tokenGet, amountGet, tokenGive, amountGive, nonce, lendingCycle, pledgeRate, interestRate, feeRate));
}
}
|
้พๆๅผบๅถๅฝ่ฟ๏ผ็ฑๅ็บฆ็ฎก็่
่ฐ็จ๏ผ้borrower๏ผ้lender่ฐ็จ๏ผborrower้่ฆๆฏไปๆตๆผ่ตไบง็ปๅบๅไบบ๏ผๆฌ้+ๅฉๆฏ๏ผ๏ผๅนณๅฐๅไฝๆน๏ผๆ็ปญ่ดน๏ผๅ้กน็ฎๆน๏ผๆ็ปญ่ดน๏ผ๏ผๅฆๆ่ฟๆๅฉไฝ๏ผๅฉไฝ้จๅๅฝ่ฟ็ปAๅ็บฆ็ฎก็ๅๅ้ๆตๆผ่ตไบงๅฐๅบๅไบบ,ๆฐ้็ฑไธๅฑไผ ๅ
ฅๅ็บฆ็ฎก็ๅๅ้ๅฉไฝๆตๆผ่ตไบงๅฐๅๆฌพๆน,ๆฐ้็ฑไธๅฑไผ ๅ
ฅ
|
function forcerepay(bytes32 partnerId, address borrower, bytes32 hash, address token, uint lenderAmount, uint offcialFeeAmount, uint partnerFeeAmount) public returns (uint){
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");
require(token != address(0), "invalid forcerepay token address");
require(token == partnerOrderBook[partnerId][borrower][hash].token_pledge, "invalid forcerepay token");
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_ACCEPTED, "state != OrderState.ORDER_STATUS_ACCEPTED");
require(msg.sender == admin, "forcerepay must be admin");
require(now > partnerOrderBook[partnerId][borrower][hash].deadline, "cannot forcerepay before deadline");
uint status = 0;
partnerTokens[partnerId][token][borrower] = safeSub(partnerTokens[partnerId][token][borrower], lenderAmount);
if (!EIP20Interface(token).asmTransfer(partnerOrderBook[partnerId][borrower][hash].lender, lenderAmount)) {
status = uint(Error.FORCE_REPAY_TX_ERROR);
}
if (!EIP20Interface(token).asmTransfer(partnerAccounts[partnerId], partnerFeeAmount)) {
status = uint(Error.FORCE_REPAY_TX_ERROR);
}
if (!EIP20Interface(token).asmTransfer(offcialFeeAccount, offcialFeeAmount)) {
status = uint(Error.FORCE_REPAY_TX_ERROR);
}
if (partnerTokens[partnerId][token][borrower] > 0) {
if (!EIP20Interface(token).asmTransfer(borrower, partnerTokens[partnerId][token][borrower])) {
status = uint(Error.FORCE_REPAY_TX_ERROR);
partnerTokens[partnerId][token][borrower] = 0;
}
}
if (status == 0) {
delete partnerOrderBook[partnerId][borrower][hash];
}
emit Forcerepay(partnerId, borrower, hash, token, msg.sender, status);
return status;
}
| 12,533,678
|
/**
*Submitted for verification at Etherscan.io on 2021-10-21
*/
/**
*Submitted for verification at polygonscan.com on 2021-09-14
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
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;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), 'Ownable: caller is not the owner');
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_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;
}
}
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
// function name() external view returns (string memory);
// function symbol() external view returns (string memory);
// function decimals() external view returns (uint8);
// function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
// function allowance(address owner, address spender) external view returns (uint);
// function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
contract ETHPool is Ownable{
using SafeMath for uint256;
mapping(address=>bool) public supportedTokens;
uint256 supportedTokensCount = 0;
address[] public tokenAddresses;
address public walletAddress;
constructor () {
walletAddress = msg.sender;
}
event Deposit(address indexed from, address indexed to, address token_address, uint256 value);
event Withdraw(address indexed from, address indexed to, address token_address, uint256 value);
function updateWalletAddress(address addr) public onlyOwner {
walletAddress = addr;
}
function checkTokenAddressExists(address token_address) internal view returns (bool) {
for (uint i = 0 ; i < tokenAddresses.length ; i ++ ) {
if (tokenAddresses[i] == token_address ) {
return true;
}
}
return false;
}
function setToken(address token) public onlyOwner {
require(checkTokenAddressExists(token) == false, "Token already set");
supportedTokens[token] = true;
tokenAddresses.push(token);
supportedTokensCount = supportedTokensCount + 1;
}
function enableToken(address token) public onlyOwner {
require(checkTokenAddressExists(token) == true, "Token not yet exists");
require(supportedTokens[token] == false, "Token is already enabled");
supportedTokens[token] = true;
if ( ! checkTokenAddressExists(token) ) {
tokenAddresses.push(token);
}
supportedTokensCount = supportedTokensCount + 1;
}
function disableToken(address token) public onlyOwner {
(checkTokenAddressExists(token) == true, "Token not yet exists");
require(supportedTokens[token] == true, "Token is already disabled");
supportedTokens[token] = false;
supportedTokensCount = supportedTokensCount - 1;
}
// get the tokens that we supports
function getSupportedTokenAddresses() public view returns (address[] memory){
address[] memory supportedTokenAddresses = new address[](supportedTokensCount);
uint16 count = 0;
for ( uint256 i = 0 ; i < tokenAddresses.length ; i ++ ){
if (supportedTokens[tokenAddresses[i]]) {
supportedTokenAddresses[count] = tokenAddresses[i];
count = count + 1;
}
}
return supportedTokenAddresses;
}
function deposit(address token, uint256 amount) public {
require(supportedTokens[token], "TOKEN ADDRESS IS NOT SUPPORTED");
uint256 balance = IERC20(token).balanceOf(address(msg.sender));
require(balance >= amount, "Pool: INSUFFICIENT_INPUT_AMOUNT");
IERC20(token).transferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, address(this), token, amount);
}
function depositNative() public payable {
require(supportedTokens[address(0)], "NATIVE TOKEN IS NOT SUPPORTED");
emit Deposit(msg.sender, address(this), address(0), msg.value);
}
function withdrawToken(address token) public onlyOwner {
uint256 balance = IERC20(token).balanceOf(address(this));
IERC20(token).transfer(walletAddress, balance);
emit Withdraw(address(this), walletAddress, token, balance);
}
function withdrawNativeToken() public onlyOwner {
uint256 balance = address(this).balance;
payable(walletAddress).transfer(balance);
emit Withdraw(address(this), walletAddress, address(0), balance);
}
function balanceOfToken(address token) public view onlyOwner returns (uint256 amount) {
uint256 balance = IERC20(token).balanceOf(address(this));
return balance;
}
function balanceOfNativeToken() public view onlyOwner returns (uint256 amount) {
uint256 balance = address(this).balance;
return balance;
}
}
|
get the tokens that we supports
|
function getSupportedTokenAddresses() public view returns (address[] memory){
address[] memory supportedTokenAddresses = new address[](supportedTokensCount);
uint16 count = 0;
for ( uint256 i = 0 ; i < tokenAddresses.length ; i ++ ){
if (supportedTokens[tokenAddresses[i]]) {
supportedTokenAddresses[count] = tokenAddresses[i];
count = count + 1;
}
}
return supportedTokenAddresses;
}
| 2,296,579
|
./full_match/1/0xfFC91F7088BF40F0419B451fB9D85718D8903628/sources/Synthetix.sol
|
Set the beneficiary address of this contract. Only the contract owner may call this. The provided beneficiary must be non-null. _beneficiary The address to pay any eth contained in this contract to upon self-destruction./
|
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0), "Beneficiary must not be zero");
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
| 9,721,953
|
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
import "../contracts/IToken.sol";
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/MatryxPlatform.sol";
import "../contracts/LibPlatform.sol";
import "../contracts/LibTournament.sol";
contract TestLibTournament2 {
MatryxPlatform.Info info;
MatryxPlatform.Data data;
bool transferHappened;
uint256 transferAmount;
function transfer(address to, uint256 value) public returns (bool)
{
transferHappened = true;
transferAmount = value;
return transferHappened;
}
function transferFrom(address from, address to, uint256 value) public view returns (bool)
{
return true;
}
function allowance(address owner, address spender) public returns (uint256)
{
return 1 ether;
}
function testCreateRound() public
{
data.tournamentBalance[address(this)] = 100;
LibTournament.RoundDetails memory rDetails;
rDetails.start = 0;
rDetails.duration = 100;
rDetails.review = 100;
rDetails.bounty = 50;
LibTournament.createRound(address(this), address(this), info, data, rDetails);
Assert.equal(data.tournaments[address(this)].rounds.length, 1, "Should be one round");
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
Assert.equal(roundZero.details.start, now, "Start should be now.");
Assert.equal(roundZero.details.duration, 100, "Round duration should be 100.");
Assert.equal(roundZero.details.review, 100, "Round review should be 100.");
Assert.equal(roundZero.details.bounty, 50, "Round bounty should be 50.");
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
}
function testCreateSubmission() public
{
// sender can use matryx
data.whitelist[msg.sender] = true;
// tournament entry fee paid
data.tournaments[address(this)].entryFeePaid[msg.sender].exists = true;
// commit has owner
bytes32 commitHash = keccak256("commit");
data.commits[commitHash].owner = msg.sender;
// current round is Open
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 1;
roundZero.details.duration = 61;
roundZero.details.bounty = 10;
LibTournament.createSubmission(address(this), msg.sender, info, data, "QmSubmissionStuff", commitHash);
bytes32 submissionHash = keccak256(abi.encodePacked(address(this), commitHash, uint256(0)));
Assert.equal(data.commitToSubmissions[commitHash][0], submissionHash, "Commit hash should be linked to submission hash.");
Assert.equal(roundZero.info.submissions[0], submissionHash, "Submission should be in round's submissions array.");
Assert.isTrue(roundZero.hasSubmitted[msg.sender], "hasSubmitted flag should be true for sender.");
Assert.equal(roundZero.info.submitterCount, 1, "Round should have 1 submitter.");
delete data.whitelist[msg.sender];
delete data.tournaments[address(this)].entryFeePaid[msg.sender];
delete data.tournaments[address(this)];
delete data.submissions[submissionHash];
delete data.commitToSubmissions[commitHash];
delete data.commits[commitHash];
}
function testUpdateDetails() public
{
data.tournaments[address(this)].info.owner = msg.sender;
LibTournament.TournamentDetails memory tDetails;
tDetails.content = "QmTournamentDetails";
tDetails.entryFee = 10;
LibTournament.updateDetails(address(this), msg.sender, data, tDetails);
Assert.equal(data.tournaments[address(this)].details.content, tDetails.content, "Tournament content incorrect.");
Assert.equal(data.tournaments[address(this)].details.entryFee, tDetails.entryFee, "Tournament entryFee incorrect.");
delete data.tournaments[address(this)];
}
function testAddToBounty() public
{
// set token
info.token = address(this);
// current round is Open
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 1;
roundZero.details.duration = 61;
roundZero.details.bounty = 10;
// total balance is 10
data.totalBalance = 10;
// tournamentBalance is 10
data.tournamentBalance[address(this)] = 10;
data.tournaments[address(this)].details.bounty = 10;
LibTournament.addToBounty(address(this), msg.sender, info, data, 10);
Assert.equal(data.totalBalance, 20, "Total platform balance should be 20.");
Assert.equal(data.tournamentBalance[address(this)], 20, "Tournament balance should be 20.");
Assert.equal(data.tournaments[address(this)].details.bounty, 20, "Tournament bounty should be 20.");
delete info.token;
delete data.tournaments[address(this)];
delete data.totalBalance;
delete data.tournamentBalance[address(this)];
}
function testTransferToRound() public
{
// Must be owner
data.tournaments[address(this)].info.owner = msg.sender;
// current round is Open
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 1;
roundZero.details.duration = 61;
roundZero.details.bounty = 10;
// total balance is 10
data.totalBalance = 20;
data.tournamentBalance[address(this)] = 20;
LibTournament.transferToRound(address(this), msg.sender, data, 10);
Assert.equal(roundZero.details.bounty, 20, "Round bounty should be 20.");
delete data.tournaments[address(this)];
delete data.totalBalance;
delete data.tournamentBalance[address(this)];
}
function testSelectWinnersDoNothing() public
{
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// create wData
bytes32 winner = keccak256("winner");
bytes32 commitHash = keccak256("commit");
LibTournament.WinnersData memory wData;
bytes32[] memory subs = new bytes32[](1);
subs[0] = winner;
uint256[] memory dist = new uint256[](1);
dist[0] = 1;
wData.submissions = subs;
wData.distribution = dist;
// create rDetails
LibTournament.RoundDetails memory rDetails;
// current round is in review
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
roundZero.info.submissions.length = 1;
roundZero.info.submissions[0] = winner;
// submission must exist on platform
data.submissions[winner].tournament = address(this);
data.submissions[winner].commitHash = commitHash;
LibTournament.selectWinners(address(this), msg.sender, info, data, wData, rDetails);
Assert.equal(roundZero.info.winners.submissions[0], winner, "First round winner incorrect.");
Assert.equal(data.submissions[winner].reward, 10, "Full bounty not awarded to sole round winner.");
Assert.equal(data.commitBalance[commitHash], 10, "Full bounty not allocated to sole round winner's commit.");
Assert.equal(data.tournamentBalance[address(this)], 10, "Tournament balance should have decreased to 10.");
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
delete data.submissions[winner];
delete data.commitBalance[commitHash];
}
function testSelectWinnersStartNextRound() public
{
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// create wData
bytes32 winner = keccak256("winner");
bytes32 commitHash = keccak256("commit");
LibTournament.WinnersData memory wData;
bytes32[] memory subs = new bytes32[](1);
subs[0] = winner;
uint256[] memory dist = new uint256[](1);
dist[0] = 1;
wData.submissions = subs;
wData.distribution = dist;
wData.action = 1;
// create rDetails
LibTournament.RoundDetails memory rDetails;
rDetails.duration = 60;
rDetails.bounty = 10;
// current round is in review
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
roundZero.info.submissions.length = 1;
roundZero.info.submissions[0] = winner;
// submission must exist on platform
data.submissions[winner].tournament = address(this);
data.submissions[winner].commitHash = commitHash;
LibTournament.selectWinners(address(this), msg.sender, info, data, wData, rDetails);
Assert.equal(roundZero.info.winners.submissions[0], winner, "First round winner incorrect.");
Assert.equal(data.submissions[winner].reward, 10, "Full bounty not awarded to sole round winner.");
Assert.equal(data.commitBalance[commitHash], 10, "Full bounty not allocated to sole round winner's commit.");
Assert.equal(data.tournamentBalance[address(this)], 10, "Tournament balance should have decreased to 10.");
Assert.isTrue(roundZero.info.closed, "Old round is closed");
Assert.equal(data.tournaments[address(this)].rounds[1].details.duration, 60, "New round duration is incorrect.");
Assert.equal(data.tournaments[address(this)].rounds[1].details.bounty, 10, "New round bounty is incorrect.");
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
delete data.submissions[winner];
delete data.commitBalance[commitHash];
}
function testSelectWinnersCloseTournament() public
{
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// create wData
bytes32 winner = keccak256("winner");
bytes32 commitHash = keccak256("commit");
LibTournament.WinnersData memory wData;
bytes32[] memory subs = new bytes32[](1);
subs[0] = winner;
uint256[] memory dist = new uint256[](1);
dist[0] = 1;
wData.submissions = subs;
wData.distribution = dist;
wData.action = 2;
// create rDetails
LibTournament.RoundDetails memory rDetails;
rDetails.duration = 60;
rDetails.bounty = 10;
// current round is InReview
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
roundZero.info.submissions.length = 1;
roundZero.info.submissions[0] = winner;
// submission must exist on platform
data.submissions[winner].tournament = address(this);
data.submissions[winner].commitHash = commitHash;
Assert.equal(data.submissions[winner].reward, 0, "Reward for submission should be 0 initially.");
LibTournament.selectWinners(address(this), msg.sender, info, data, wData, rDetails);
Assert.equal(roundZero.info.winners.submissions[0], winner, "First round winner incorrect.");
Assert.equal(data.submissions[winner].reward, 20, "Full bounty not awarded to sole round winner.");
Assert.equal(data.commitBalance[commitHash], 20, "Full bounty not allocated to sole round winner's commit.");
Assert.equal(data.tournamentBalance[address(this)], 0, "Tournament balance should have been depleted.");
Assert.isTrue(roundZero.info.closed, "Old round is closed");
Assert.equal(roundZero.details.bounty, 20, "Last round bounty not remaining tournament balance.");
Assert.equal(data.tournaments[address(this)].rounds.length, 1, "Total number of rounds incorrect.");
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
delete data.submissions[winner];
delete data.commitBalance[commitHash];
}
function testUpdateNextRound() public
{
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// round not yet open
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now + 60;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
LibTournament.RoundDetails memory rDetails;
rDetails.start = now;
rDetails.duration = 40;
rDetails.review = 30;
rDetails.bounty = 20;
LibTournament.updateNextRound(address(this), msg.sender, data, rDetails);
Assert.equal(roundZero.details.start, now, "Round should be starting now.");
Assert.equal(roundZero.details.duration, 40, "Round duration should be 40.");
Assert.equal(roundZero.details.review, 30, "Round review should be 30.");
Assert.equal(roundZero.details.bounty, 20, "Round bounty should be 20.");
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
}
function testStartNextRound() public
{
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// round setup, first HasWinners, second is OnHold
data.tournaments[address(this)].rounds.length = 2;
bytes32 sHash = keccak256(abi.encodePacked("submission"));
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
roundZero.info.submissions.push(sHash);
roundZero.info.winners.submissions.push(sHash);
data.tournaments[address(this)].rounds[1].details.start = now + 60;
data.tournaments[address(this)].rounds[1].details.duration = 1000;
LibTournament.startNextRound(address(this), msg.sender, data);
Assert.isTrue(roundZero.info.closed, "Round 0 should be closed.");
Assert.equal(data.tournaments[address(this)].rounds[1].details.start, now, "Round 1 should start now.");
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
}
function testWithdrawFromAbandoned() public
{
// set token
info.token = address(this);
// set total balance
data.totalBalance = 20;
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// current round is Abandoned
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
// sender and someone else have submitted to round
roundZero.hasSubmitted[msg.sender] = true;
roundZero.hasSubmitted[address(uint256(msg.sender) + 1)] = true;
roundZero.info.submitterCount = 2;
// sender must be entrant to exit
data.tournaments[address(this)].entryFeePaid[msg.sender].exists = true;
LibTournament.withdrawFromAbandoned(address(this), msg.sender, info, data);
Assert.isTrue(roundZero.info.closed, "Round should have closed.");
Assert.isTrue(data.tournaments[address(this)].hasWithdrawn[msg.sender], "Sender should have withdrawn.");
Assert.equal(data.tournaments[address(this)].numWithdrawn, 1, "Number of users who've withdrawn should be 1.");
Assert.equal(data.totalBalance, 10, "Total balance should have been 10.");
Assert.equal(data.tournamentBalance[address(this)], 10, "Tournament balance should have been 10.");
Assert.isTrue(transferHappened, "Transfer should have happened.");
Assert.equal(transferAmount, 10, "Transfer amount should have been 10.");
delete info.token;
delete data.totalBalance;
delete data.tournamentBalance[address(this)];
delete roundZero.hasSubmitted[msg.sender];
delete roundZero.hasSubmitted[address(uint256(msg.sender) + 1)];
delete data.tournaments[address(this)].entryFeePaid[msg.sender];
delete data.tournaments[address(this)];
delete transferHappened;
delete transferAmount;
}
function testCloseTournament() public
{
// set total balance
data.totalBalance = 20;
// set tournament balance
data.tournamentBalance[address(this)] = 10;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// create wData
bytes32 winner = keccak256("winner");
bytes32 commitHash = keccak256("commit");
LibTournament.WinnersData memory wData;
bytes32[] memory subs = new bytes32[](1);
subs[0] = winner;
uint256[] memory dist = new uint256[](1);
dist[0] = 1;
wData.submissions = subs;
wData.distribution = dist;
// round setup: first HasWinners, second is ghost
data.tournaments[address(this)].rounds.length = 2;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
roundZero.info.winners = wData;
roundZero.info.submissions.push(winner);
LibTournament.RoundData storage roundOne = data.tournaments[address(this)].rounds[1];
roundOne.details.start = roundZero.details.start + roundZero.details.duration + roundZero.details.review;
// submission setup
data.submissions[winner].tournament = address(this);
data.submissions[winner].commitHash = commitHash;
data.submissions[winner].reward = 10;
data.commitBalance[commitHash] = 10;
LibTournament.closeTournament(address(this), msg.sender, data);
Assert.equal(data.commitBalance[commitHash], 20, "Commit balance should be 20.");
Assert.equal(data.submissions[winner].reward, 20, "Submission reward should be 20.");
Assert.equal(data.tournamentBalance[address(this)], 0, "Tournament balance should be 0.");
Assert.equal(data.tournaments[address(this)].rounds.length, 1, "Ghost round should be gone.");
delete data.totalBalance;
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
delete data.submissions[winner];
delete data.commitBalance[commitHash];
}
function testRecoverBounty() public
{
// set token
info.token = address(this);
// set total balance
data.totalBalance = 20;
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// current round Abandoned
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
LibTournament.recoverBounty(address(this), msg.sender, info, data);
Assert.isTrue(roundZero.info.closed, "Round should have closed.");
Assert.equal(data.tournaments[address(this)].numWithdrawn, 1, "Number of users who've withdrawn should be 1.");
Assert.isZero(data.totalBalance, "Total balance should be 0.");
Assert.isZero(data.tournamentBalance[address(this)], "Tournament balance should be 0.");
Assert.isTrue(transferHappened, "Token transfer should have happen.");
Assert.equal(transferAmount, 20, "Transfer amount should be 20.");
delete info.token;
delete data.totalBalance;
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
}
}
|
set tournament balance set tournament owner round not yet open
|
function testUpdateNextRound() public
{
data.tournamentBalance[address(this)] = 20;
data.tournaments[address(this)].info.owner = msg.sender;
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now + 60;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
LibTournament.RoundDetails memory rDetails;
rDetails.start = now;
rDetails.duration = 40;
rDetails.review = 30;
rDetails.bounty = 20;
LibTournament.updateNextRound(address(this), msg.sender, data, rDetails);
Assert.equal(roundZero.details.start, now, "Round should be starting now.");
Assert.equal(roundZero.details.duration, 40, "Round duration should be 40.");
Assert.equal(roundZero.details.review, 30, "Round review should be 30.");
Assert.equal(roundZero.details.bounty, 20, "Round bounty should be 20.");
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
}
| 12,733,567
|
./partial_match/97/0x550121E4dCea1FCa281c239E078993e86Eb5f7B1/sources/Tinenanmen_Square.sol
|
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), "BEP20: fucker, do you even crypto bro?");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount, "You minted some new TANKs you oppressor communist!");
}
| 11,397,727
|
./full_match/1285/0x517f5D5f94d2F6FAa48AD889467cCF470064Ba43/sources/src/Facets/NXTPFacet.sol
|
This function starts a cross-chain transaction using the NXTP protocol _lifiData data used purely for tracking and analytics _nxtpData data needed to complete an NXTP cross-chain transaction/ Ensure sender has enough to complete the bridge transaction
|
function startBridgeTokensViaNXTP(LiFiData memory _lifiData, ITransactionManager.PrepareArgs memory _nxtpData)
public
payable
{
address sendingAssetId = _nxtpData.invariantData.sendingAssetId;
if (sendingAssetId == address(0)) require(msg.value == _nxtpData.amount, "ERR_INVALID_AMOUNT");
else {
uint256 _sendingAssetIdBalance = LibAsset.getOwnBalance(sendingAssetId);
LibAsset.transferFromERC20(sendingAssetId, msg.sender, address(this), _nxtpData.amount);
require(
LibAsset.getOwnBalance(sendingAssetId) - _sendingAssetIdBalance == _nxtpData.amount,
"ERR_INVALID_AMOUNT"
);
}
emit LiFiTransferStarted(
_lifiData.transactionId,
_lifiData.integrator,
_lifiData.referrer,
_lifiData.sendingAssetId,
_lifiData.receivingAssetId,
_lifiData.receiver,
_lifiData.amount,
_lifiData.destinationChainId,
block.timestamp
);
}
| 833,926
|
/*
https://powerpool.finance/
wrrrw r wrr
ppwr rrr wppr0 prwwwrp prwwwrp wr0
rr 0rrrwrrprpwp0 pp pr prrrr0 pp 0r prrrr0 0rwrrr pp pr prrrr0 prrrr0 r0
rrp pr wr00rrp prwww0 pp wr pp w00r prwwwpr 0rw prwww0 pp wr pp wr r0
r0rprprwrrrp pr0 pp wr pr pp rwwr wr 0r pp wr pr wr pr r0
prwr wrr0wpwr 00 www0 0w0ww www0 0w 00 www0 www0 0www0
wrr ww0rrrr
*/
// SPDX-License-Identifier: GPL-3.0
// File: @powerpool/poweroracle/contracts/interfaces/IPowerPoke.sol
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
interface IPowerPoke {
/*** CLIENT'S CONTRACT INTERFACE ***/
function authorizeReporter(uint256 userId_, address pokerKey_) external view;
function authorizeNonReporter(uint256 userId_, address pokerKey_) external view;
function authorizeNonReporterWithDeposit(
uint256 userId_,
address pokerKey_,
uint256 overrideMinDeposit_
) external view;
function authorizePoker(uint256 userId_, address pokerKey_) external view;
function authorizePokerWithDeposit(
uint256 userId_,
address pokerKey_,
uint256 overrideMinStake_
) external view;
function slashReporter(uint256 slasherId_, uint256 times_) external;
function reward(
uint256 userId_,
uint256 gasUsed_,
uint256 compensationPlan_,
bytes calldata pokeOptions_
) external;
/*** CLIENT OWNER INTERFACE ***/
function transferClientOwnership(address client_, address to_) external;
function addCredit(address client_, uint256 amount_) external;
function withdrawCredit(
address client_,
address to_,
uint256 amount_
) external;
function setReportIntervals(
address client_,
uint256 minReportInterval_,
uint256 maxReportInterval_
) external;
function setSlasherHeartbeat(address client_, uint256 slasherHeartbeat_) external;
function setGasPriceLimit(address client_, uint256 gasPriceLimit_) external;
function setFixedCompensations(
address client_,
uint256 eth_,
uint256 cvp_
) external;
function setBonusPlan(
address client_,
uint256 planId_,
bool active_,
uint64 bonusNominator_,
uint64 bonusDenominator_,
uint64 perGas_
) external;
function setMinimalDeposit(address client_, uint256 defaultMinDeposit_) external;
/*** POKER INTERFACE ***/
function withdrawRewards(uint256 userId_, address to_) external;
function setPokerKeyRewardWithdrawAllowance(uint256 userId_, bool allow_) external;
/*** OWNER INTERFACE ***/
function addClient(
address client_,
address owner_,
bool canSlash_,
uint256 gasPriceLimit_,
uint256 minReportInterval_,
uint256 maxReportInterval_
) external;
function setClientActiveFlag(address client_, bool active_) external;
function setCanSlashFlag(address client_, bool canSlash) external;
function setOracle(address oracle_) external;
function pause() external;
function unpause() external;
/*** GETTERS ***/
function creditOf(address client_) external view returns (uint256);
function ownerOf(address client_) external view returns (address);
function getMinMaxReportIntervals(address client_) external view returns (uint256 min, uint256 max);
function getSlasherHeartbeat(address client_) external view returns (uint256);
function getGasPriceLimit(address client_) external view returns (uint256);
function getPokerBonus(
address client_,
uint256 bonusPlanId_,
uint256 gasUsed_,
uint256 userDeposit_
) external view returns (uint256);
function getGasPriceFor(address client_) external view returns (uint256);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol
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;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
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;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File: contracts/interfaces/IPowerOracle.sol
pragma solidity 0.6.12;
interface IPowerOracle {
function assetPrices(address _token) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/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, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/interfaces/BMathInterface.sol
pragma solidity 0.6.12;
interface BMathInterface {
function calcInGivenOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 tokenAmountOut,
uint256 swapFee
) external pure returns (uint256 tokenAmountIn);
function calcSingleInGivenPoolOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountOut,
uint256 swapFee
) external pure returns (uint256 tokenAmountIn);
}
// File: contracts/interfaces/BPoolInterface.sol
pragma solidity 0.6.12;
interface BPoolInterface is IERC20, BMathInterface {
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external;
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external;
function swapExactAmountIn(
address,
uint256,
address,
uint256,
uint256
) external returns (uint256, uint256);
function swapExactAmountOut(
address,
uint256,
address,
uint256,
uint256
) external returns (uint256, uint256);
function joinswapExternAmountIn(
address,
uint256,
uint256
) external returns (uint256);
function joinswapPoolAmountOut(
address,
uint256,
uint256
) external returns (uint256);
function exitswapPoolAmountIn(
address,
uint256,
uint256
) external returns (uint256);
function exitswapExternAmountOut(
address,
uint256,
uint256
) external returns (uint256);
function getDenormalizedWeight(address) external view returns (uint256);
function getBalance(address) external view returns (uint256);
function getSwapFee() external view returns (uint256);
function getTotalDenormalizedWeight() external view returns (uint256);
function getCommunityFee()
external
view
returns (
uint256,
uint256,
uint256,
address
);
function calcAmountWithCommunityFee(
uint256,
uint256,
address
) external view returns (uint256, uint256);
function getRestrictions() external view returns (address);
function isPublicSwap() external view returns (bool);
function isFinalized() external view returns (bool);
function isBound(address t) external view returns (bool);
function getCurrentTokens() external view returns (address[] memory tokens);
function getFinalTokens() external view returns (address[] memory tokens);
function setSwapFee(uint256) external;
function setCommunityFeeAndReceiver(
uint256,
uint256,
uint256,
address
) external;
function setController(address) external;
function setPublicSwap(bool) external;
function finalize() external;
function bind(
address,
uint256,
uint256
) external;
function rebind(
address,
uint256,
uint256
) external;
function unbind(address) external;
function gulp(address) external;
function callVoting(
address voting,
bytes4 signature,
bytes calldata args,
uint256 value
) external;
function getMinWeight() external view returns (uint256);
function getMaxBoundTokens() external view returns (uint256);
}
// File: contracts/interfaces/PowerIndexPoolInterface.sol
pragma solidity 0.6.12;
interface PowerIndexPoolInterface is BPoolInterface {
function initialize(
string calldata name,
string calldata symbol,
uint256 minWeightPerSecond,
uint256 maxWeightPerSecond
) external;
function bind(
address,
uint256,
uint256,
uint256,
uint256
) external;
function setDynamicWeight(
address token,
uint256 targetDenorm,
uint256 fromTimestamp,
uint256 targetTimestamp
) external;
function getDynamicWeightSettings(address token)
external
view
returns (
uint256 fromTimestamp,
uint256 targetTimestamp,
uint256 fromDenorm,
uint256 targetDenorm
);
function getMinWeight() external view override returns (uint256);
function getWeightPerSecondBounds() external view returns (uint256, uint256);
function setWeightPerSecondBounds(uint256, uint256) external;
function setWrapper(address, bool) external;
function getWrapperMode() external view returns (bool);
}
// File: contracts/interfaces/IPoolRestrictions.sol
pragma solidity 0.6.12;
interface IPoolRestrictions {
function getMaxTotalSupply(address _pool) external view returns (uint256);
function isVotingSignatureAllowed(address _votingAddress, bytes4 _signature) external view returns (bool);
function isVotingSenderAllowed(address _votingAddress, address _sender) external view returns (bool);
function isWithoutFee(address _addr) external view returns (bool);
}
// File: contracts/PowerIndexAbstractController.sol
pragma solidity 0.6.12;
contract PowerIndexAbstractController is Ownable {
using SafeMath for uint256;
bytes4 public constant CALL_VOTING_SIG = bytes4(keccak256(bytes("callVoting(address,bytes4,bytes,uint256)")));
event CallPool(bool indexed success, bytes4 indexed inputSig, bytes inputData, bytes outputData);
PowerIndexPoolInterface public immutable pool;
constructor(address _pool) public {
pool = PowerIndexPoolInterface(_pool);
}
/**
* @notice Call any function from pool, except prohibited signatures.
* @param signature Method signature
* @param args Encoded method inputs
*/
function callPool(bytes4 signature, bytes calldata args) external onlyOwner {
_checkSignature(signature);
(bool success, bytes memory data) = address(pool).call(abi.encodePacked(signature, args));
require(success, "NOT_SUCCESS");
emit CallPool(success, signature, args, data);
}
/**
* @notice Call voting by pool
* @param voting Voting address
* @param signature Method signature
* @param args Encoded method inputs
* @param value Send value to pool
*/
function callVotingByPool(
address voting,
bytes4 signature,
bytes calldata args,
uint256 value
) external {
require(_restrictions().isVotingSenderAllowed(voting, msg.sender), "SENDER_NOT_ALLOWED");
pool.callVoting(voting, signature, args, value);
}
/**
* @notice Migrate several contracts with setController method to new controller address
* @param newController New controller to migrate
* @param addressesToMigrate Address to call setController method
*/
function migrateController(address newController, address[] calldata addressesToMigrate) external onlyOwner {
uint256 len = addressesToMigrate.length;
for (uint256 i = 0; i < len; i++) {
PowerIndexPoolInterface(addressesToMigrate[i]).setController(newController);
}
}
function _restrictions() internal view returns (IPoolRestrictions) {
return IPoolRestrictions(pool.getRestrictions());
}
function _checkSignature(bytes4 signature) internal pure virtual {
require(signature != CALL_VOTING_SIG, "SIGNATURE_NOT_ALLOWED");
}
}
// File: contracts/interfaces/PowerIndexWrapperInterface.sol
pragma solidity 0.6.12;
interface PowerIndexWrapperInterface {
function getFinalTokens() external view returns (address[] memory tokens);
function getCurrentTokens() external view returns (address[] memory tokens);
function getBalance(address _token) external view returns (uint256);
function setPiTokenForUnderlyingsMultiple(address[] calldata _underlyingTokens, address[] calldata _piTokens)
external;
function setPiTokenForUnderlying(address _underlyingTokens, address _piToken) external;
function updatePiTokenEthFees(address[] calldata _underlyingTokens) external;
function withdrawOddEthFee(address payable _recipient) external;
function calcEthFeeForTokens(address[] memory tokens) external view returns (uint256 feeSum);
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external payable;
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external payable;
function swapExactAmountIn(
address,
uint256,
address,
uint256,
uint256
) external payable returns (uint256, uint256);
function swapExactAmountOut(
address,
uint256,
address,
uint256,
uint256
) external payable returns (uint256, uint256);
function joinswapExternAmountIn(
address,
uint256,
uint256
) external payable returns (uint256);
function joinswapPoolAmountOut(
address,
uint256,
uint256
) external payable returns (uint256);
function exitswapPoolAmountIn(
address,
uint256,
uint256
) external payable returns (uint256);
function exitswapExternAmountOut(
address,
uint256,
uint256
) external payable returns (uint256);
}
// File: contracts/interfaces/WrappedPiErc20Interface.sol
pragma solidity 0.6.12;
interface WrappedPiErc20Interface is IERC20 {
function deposit(uint256 _amount) external payable returns (uint256);
function withdraw(uint256 _amount) external payable returns (uint256);
function changeRouter(address _newRouter) external;
function setEthFee(uint256 _newEthFee) external;
function approveUnderlying(address _to, uint256 _amount) external;
function callExternal(
address voting,
bytes4 signature,
bytes calldata args,
uint256 value
) external;
struct ExternalCallData {
address destination;
bytes4 signature;
bytes args;
uint256 value;
}
function callExternalMultiple(ExternalCallData[] calldata calls) external;
function getUnderlyingBalance() external view returns (uint256);
}
// File: contracts/interfaces/WrappedPiErc20FactoryInterface.sol
pragma solidity 0.6.12;
interface WrappedPiErc20FactoryInterface {
event NewWrappedPiErc20(address indexed token, address indexed wrappedToken, address indexed creator);
function build(
address _token,
address _router,
string calldata _name,
string calldata _symbol
) external returns (WrappedPiErc20Interface);
}
// File: contracts/interfaces/IPiRouterFactory.sol
pragma solidity 0.6.12;
interface IPiRouterFactory {
function buildRouter(address _piToken, bytes calldata _args) external returns (address);
}
// File: contracts/powerindex-router/PowerIndexWrappedController.sol
pragma solidity 0.6.12;
contract PowerIndexWrappedController is PowerIndexAbstractController {
/* ========== EVENTS ========== */
/** @dev Emitted on replacing underlying token with exists piToken. */
event ReplacePoolTokenWithPiToken(
address indexed underlyingToken,
address indexed piToken,
uint256 balance,
uint256 denormalizedWeight
);
/** @dev Emitted on replacing underlying token with new version of token. */
event ReplacePoolTokenWithNewVersion(
address indexed oldToken,
address indexed newToken,
address indexed migrator,
uint256 balance,
uint256 denormalizedWeight
);
/** @dev Emitted on finishing pool replacing. */
event ReplacePoolTokenFinish();
/** @dev Emitted on poolWrapper update. */
event SetPoolWrapper(address indexed poolWrapper);
/** @dev Emitted on piTokenFactory update. */
event SetPiTokenFactory(address indexed piTokenFactory);
/** @dev Emitted on creating piToken. */
event CreatePiToken(address indexed underlyingToken, address indexed piToken, address indexed router);
/* ========== Storage ========== */
/** @dev Address of poolWrapper contract. */
PowerIndexWrapperInterface public poolWrapper;
/** @dev Address of piToken factory contract. */
WrappedPiErc20FactoryInterface public piTokenFactory;
constructor(
address _pool,
address _poolWrapper,
address _piTokenFactory
) public PowerIndexAbstractController(_pool) {
poolWrapper = PowerIndexWrapperInterface(_poolWrapper);
piTokenFactory = WrappedPiErc20FactoryInterface(_piTokenFactory);
}
/**
* @dev Set poolWrapper contract address.
* @param _poolWrapper Address of pool wrapper.
*/
function setPoolWrapper(address _poolWrapper) external onlyOwner {
poolWrapper = PowerIndexWrapperInterface(_poolWrapper);
emit SetPoolWrapper(_poolWrapper);
}
/**
* @dev Set piTokenFactory contract address.
* @param _piTokenFactory Address of PiToken factory.
*/
function setPiTokenFactory(address _piTokenFactory) external onlyOwner {
piTokenFactory = WrappedPiErc20FactoryInterface(_piTokenFactory);
emit SetPiTokenFactory(_piTokenFactory);
}
/**
* @dev Creating piToken using underling token and router factory.
* @param _underlyingToken Token, which will be wrapped by piToken.
* @param _routerFactory Router factory, to creating router by buildRouter function.
* @param _routerArgs Router args, depends on router implementation.
* @param _name Name of piToken.
* @param _name Symbol of piToken.
*/
function createPiToken(
address _underlyingToken,
address _routerFactory,
bytes memory _routerArgs,
string calldata _name,
string calldata _symbol
) external onlyOwner {
_createPiToken(_underlyingToken, _routerFactory, _routerArgs, _name, _symbol);
}
/**
* @dev Creating piToken and replacing pool token with it.
* @param _underlyingToken Token, which will be wrapped by piToken.
* @param _routerFactory Router factory, to creating router by buildRouter function.
* @param _routerArgs Router args, depends on router implementation.
* @param _name Name of piToken.
* @param _name Symbol of piToken.
*/
function replacePoolTokenWithNewPiToken(
address _underlyingToken,
address _routerFactory,
bytes calldata _routerArgs,
string calldata _name,
string calldata _symbol
) external payable onlyOwner {
WrappedPiErc20Interface piToken = _createPiToken(_underlyingToken, _routerFactory, _routerArgs, _name, _symbol);
_replacePoolTokenWithPiToken(_underlyingToken, piToken);
}
/**
* @dev Replacing pool token with existing piToken.
* @param _underlyingToken Token, which will be wrapped by piToken.
* @param _piToken Address of piToken.
*/
function replacePoolTokenWithExistingPiToken(address _underlyingToken, WrappedPiErc20Interface _piToken)
external
payable
onlyOwner
{
_replacePoolTokenWithPiToken(_underlyingToken, _piToken);
}
/**
* @dev Replacing pool token with new token version and calling migrator.
* Warning! All balance of poll token will be approved to _migrator for exchange to new token.
*
* @param _oldToken Pool token ti replace with new version.
* @param _newToken New version of token to bind to pool instead of the old.
* @param _migrator Address of contract to migrate from old token to new. Do not use untrusted contract!
* @param _migratorData Data for executing migrator.
*/
function replacePoolTokenWithNewVersion(
address _oldToken,
address _newToken,
address _migrator,
bytes calldata _migratorData
) external onlyOwner {
uint256 denormalizedWeight = pool.getDenormalizedWeight(_oldToken);
uint256 balance = pool.getBalance(_oldToken);
pool.unbind(_oldToken);
IERC20(_oldToken).approve(_migrator, balance);
(bool success, ) = _migrator.call(_migratorData);
require(success, "NOT_SUCCESS");
require(
IERC20(_newToken).balanceOf(address(this)) >= balance,
"PiBPoolController:newVersion: insufficient newToken balance"
);
IERC20(_newToken).approve(address(pool), balance);
_bindNewToken(_newToken, balance, denormalizedWeight);
emit ReplacePoolTokenWithNewVersion(_oldToken, _newToken, _migrator, balance, denormalizedWeight);
}
/*** Internal Functions ***/
function _replacePoolTokenWithPiToken(address _underlyingToken, WrappedPiErc20Interface _piToken) internal {
uint256 denormalizedWeight = pool.getDenormalizedWeight(_underlyingToken);
uint256 balance = pool.getBalance(_underlyingToken);
pool.unbind(_underlyingToken);
IERC20(_underlyingToken).approve(address(_piToken), balance);
_piToken.deposit{ value: msg.value }(balance);
_piToken.approve(address(pool), balance);
_bindNewToken(address(_piToken), balance, denormalizedWeight);
if (address(poolWrapper) != address(0)) {
poolWrapper.setPiTokenForUnderlying(_underlyingToken, address(_piToken));
}
emit ReplacePoolTokenWithPiToken(_underlyingToken, address(_piToken), balance, denormalizedWeight);
}
function _bindNewToken(
address _piToken,
uint256 _balance,
uint256 _denormalizedWeight
) internal virtual {
pool.bind(_piToken, _balance, _denormalizedWeight);
}
function _createPiToken(
address _underlyingToken,
address _routerFactory,
bytes memory _routerArgs,
string calldata _name,
string calldata _symbol
) internal returns (WrappedPiErc20Interface) {
WrappedPiErc20Interface piToken = piTokenFactory.build(_underlyingToken, address(this), _name, _symbol);
address router = IPiRouterFactory(_routerFactory).buildRouter(address(piToken), _routerArgs);
Ownable(router).transferOwnership(msg.sender);
piToken.changeRouter(router);
emit CreatePiToken(_underlyingToken, address(piToken), router);
return piToken;
}
}
// File: contracts/PowerIndexPoolController.sol
pragma solidity 0.6.12;
contract PowerIndexPoolController is PowerIndexWrappedController {
using SafeERC20 for IERC20;
/* ========== Storage ========== */
/** @dev Signature to execute bind in pool. */
bytes4 public constant BIND_SIG = bytes4(keccak256(bytes("bind(address,uint256,uint256,uint256,uint256)")));
/** @dev Signature to execute unbind in pool. */
bytes4 public constant UNBIND_SIG = bytes4(keccak256(bytes("unbind(address)")));
struct DynamicWeightInput {
address token;
uint256 targetDenorm;
uint256 fromTimestamp;
uint256 targetTimestamp;
}
/** @dev Emitted on setting new weights strategy. */
event SetWeightsStrategy(address indexed weightsStrategy);
/** @dev Weights strategy contract address. */
address public weightsStrategy;
modifier onlyWeightsStrategy() {
require(msg.sender == weightsStrategy, "ONLY_WEIGHTS_STRATEGY");
_;
}
constructor(
address _pool,
address _poolWrapper,
address _wrapperFactory,
address _weightsStrategy
) public PowerIndexWrappedController(_pool, _poolWrapper, _wrapperFactory) {
weightsStrategy = _weightsStrategy;
}
/* ========== Configuration Actions ========== */
/**
* @notice Call bind in pool.
* @param token Token to bind.
* @param balance Initial token balance.
* @param targetDenorm Target weight.
* @param fromTimestamp Start timestamp to change weight.
* @param targetTimestamp Target timestamp to change weight.
*/
function bind(
address token,
uint256 balance,
uint256 targetDenorm,
uint256 fromTimestamp,
uint256 targetTimestamp
) external onlyOwner {
_validateNewTokenBind();
IERC20(token).safeTransferFrom(msg.sender, address(this), balance);
IERC20(token).approve(address(pool), balance);
pool.bind(token, balance, targetDenorm, fromTimestamp, targetTimestamp);
}
/**
* @notice Set the old token's target weight to MIN_WEIGHT and add a new token
* with a previous weight of the old token.
* @param oldToken Token to replace.
* @param newToken New token.
* @param balance Initial new token balance.
* @param fromTimestamp Start timestamp to change weight.
* @param targetTimestamp Target timestamp to change weight.
*/
function replaceTokenWithNew(
address oldToken,
address newToken,
uint256 balance,
uint256 fromTimestamp,
uint256 targetTimestamp
) external onlyOwner {
_replaceTokenWithNew(oldToken, newToken, balance, fromTimestamp, targetTimestamp);
}
/**
* @notice The same as replaceTokenWithNew, but sets fromTimestamp with block.timestamp
* and uses durationFromNow to set targetTimestamp.
* @param oldToken Token to replace
* @param newToken New token
* @param balance Initial new token balance
* @param durationFromNow Duration to set targetTimestamp.
*/
function replaceTokenWithNewFromNow(
address oldToken,
address newToken,
uint256 balance,
uint256 durationFromNow
) external onlyOwner {
uint256 now = block.timestamp.add(1);
_replaceTokenWithNew(oldToken, newToken, balance, now, now.add(durationFromNow));
}
/**
* @notice Call setDynamicWeight for several tokens.
* @param _dynamicWeights Tokens dynamic weights configs.
*/
function setDynamicWeightList(DynamicWeightInput[] memory _dynamicWeights) external onlyOwner {
uint256 len = _dynamicWeights.length;
for (uint256 i = 0; i < len; i++) {
pool.setDynamicWeight(
_dynamicWeights[i].token,
_dynamicWeights[i].targetDenorm,
_dynamicWeights[i].fromTimestamp,
_dynamicWeights[i].targetTimestamp
);
}
}
/**
* @notice Set _weightsStrategy address.
* @param _weightsStrategy Contract for weights management.
*/
function setWeightsStrategy(address _weightsStrategy) external onlyOwner {
weightsStrategy = _weightsStrategy;
emit SetWeightsStrategy(_weightsStrategy);
}
/**
* @notice Call setDynamicWeight for several tokens, can be called only by weightsStrategy address.
* @param _dynamicWeights Tokens dynamic weights configs.
*/
function setDynamicWeightListByStrategy(DynamicWeightInput[] memory _dynamicWeights) external onlyWeightsStrategy {
uint256 len = _dynamicWeights.length;
for (uint256 i = 0; i < len; i++) {
pool.setDynamicWeight(
_dynamicWeights[i].token,
_dynamicWeights[i].targetDenorm,
_dynamicWeights[i].fromTimestamp,
_dynamicWeights[i].targetTimestamp
);
}
}
/**
* @notice Permissionless function to unbind tokens with MIN_WEIGHT.
* @param _token Token to unbind.
*/
function unbindNotActualToken(address _token) external {
require(pool.getDenormalizedWeight(_token) == pool.getMinWeight(), "DENORM_MIN");
(, uint256 targetTimestamp, , ) = pool.getDynamicWeightSettings(_token);
require(block.timestamp > targetTimestamp, "TIMESTAMP_MORE_THEN_TARGET");
uint256 tokenBalance = pool.getBalance(_token);
pool.unbind(_token);
(, , , address communityWallet) = pool.getCommunityFee();
IERC20(_token).safeTransfer(communityWallet, tokenBalance);
}
function _checkSignature(bytes4 signature) internal pure override {
require(signature != BIND_SIG && signature != UNBIND_SIG && signature != CALL_VOTING_SIG, "SIGNATURE_NOT_ALLOWED");
}
/*** Internal Functions ***/
/**
* @notice Set the old token's target weight to MIN_WEIGHT and
* add a new token with a previous weight of the old token.
* @param oldToken Token to replace
* @param newToken New token
* @param balance Initial new token balance
* @param fromTimestamp Start timestamp to change weight.
* @param targetTimestamp Target timestamp to change weight.
*/
function _replaceTokenWithNew(
address oldToken,
address newToken,
uint256 balance,
uint256 fromTimestamp,
uint256 targetTimestamp
) internal {
uint256 minWeight = pool.getMinWeight();
(, , , uint256 targetDenorm) = pool.getDynamicWeightSettings(oldToken);
pool.setDynamicWeight(oldToken, minWeight, fromTimestamp, targetTimestamp);
IERC20(newToken).safeTransferFrom(msg.sender, address(this), balance);
IERC20(newToken).approve(address(pool), balance);
pool.bind(newToken, balance, targetDenorm.sub(minWeight), fromTimestamp, targetTimestamp);
}
/**
* @notice Check that pool doesn't have the maximum number of bound tokens.
* If there is a max number of bound tokens, one should have a minimum weight.
*/
function _validateNewTokenBind() internal {
address[] memory tokens = pool.getCurrentTokens();
uint256 tokensLen = tokens.length;
uint256 minWeight = pool.getMinWeight();
if (tokensLen == pool.getMaxBoundTokens() - 1) {
for (uint256 i = 0; i < tokensLen; i++) {
(, , , uint256 targetDenorm) = pool.getDynamicWeightSettings(tokens[i]);
if (targetDenorm == minWeight) {
return;
}
}
revert("NEW_TOKEN_NOT_ALLOWED"); // If there is no tokens with target MIN_WEIGHT
}
}
}
// File: contracts/balancer-core/BConst.sol
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.6.12;
contract BConst {
uint public constant BONE = 10**18;
// Minimum number of tokens in the pool
uint public constant MIN_BOUND_TOKENS = 2;
// Maximum number of tokens in the pool
uint public constant MAX_BOUND_TOKENS = 9;
// Minimum swap fee
uint public constant MIN_FEE = BONE / 10**6;
// Maximum swap fee
uint public constant MAX_FEE = BONE / 10;
// Minimum weight for token
uint public constant MIN_WEIGHT = 1000000000;
// Maximum weight for token
uint public constant MAX_WEIGHT = BONE * 50;
// Maximum total weight
uint public constant MAX_TOTAL_WEIGHT = BONE * 50;
// Minimum balance for a token
uint public constant MIN_BALANCE = BONE / 10**12;
// Initial pool tokens supply
uint public constant INIT_POOL_SUPPLY = BONE * 100;
uint public constant MIN_BPOW_BASE = 1 wei;
uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint public constant BPOW_PRECISION = BONE / 10**10;
// Maximum input tokens balance ratio for swaps.
uint public constant MAX_IN_RATIO = BONE / 2;
// Maximum output tokens balance ratio for swaps.
uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
}
// File: contracts/balancer-core/BNum.sol
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.6.12;
contract BNum is BConst {
function btoi(uint a)
internal pure
returns (uint)
{
return a / BONE;
}
function bfloor(uint a)
internal pure
returns (uint)
{
return btoi(a) * BONE;
}
function badd(uint a, uint b)
internal pure
returns (uint)
{
uint c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
function bsub(uint a, uint b)
internal pure
returns (uint)
{
(uint c, bool flag) = bsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
function bsubSign(uint a, uint b)
internal pure
returns (uint, bool)
{
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
function bmul(uint a, uint b)
internal pure
returns (uint)
{
uint c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
uint c2 = c1 / BONE;
return c2;
}
function bdiv(uint a, uint b)
internal pure
returns (uint)
{
require(b != 0, "ERR_DIV_ZERO");
uint c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow
uint c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require
uint c2 = c1 / b;
return c2;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "ERR_DIV_ZERO");
return a / b;
}
// DSMath.wpow
function bpowi(uint a, uint n)
internal pure
returns (uint)
{
uint z = n % 2 != 0 ? a : BONE;
for (n /= 2; n != 0; n /= 2) {
a = bmul(a, a);
if (n % 2 != 0) {
z = bmul(z, a);
}
}
return z;
}
// Compute b^(e.w) by splitting it into (b^e)*(b^0.w).
// Use `bpowi` for `b^e` and `bpowK` for k iterations
// of approximation of b^0.w
function bpow(uint base, uint exp)
internal pure
returns (uint)
{
require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW");
require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH");
uint whole = bfloor(exp);
uint remain = bsub(exp, whole);
uint wholePow = bpowi(base, btoi(whole));
if (remain == 0) {
return wholePow;
}
uint partialResult = bpowApprox(base, remain, BPOW_PRECISION);
return bmul(wholePow, partialResult);
}
function bpowApprox(uint base, uint exp, uint precision)
internal pure
returns (uint)
{
// term 0:
uint a = exp;
(uint x, bool xneg) = bsubSign(base, BONE);
uint term = BONE;
uint sum = term;
bool negative = false;
// term(k) = numer / denom
// = (product(a - i - 1, i=1-->k) * x^k) / (k!)
// each iteration, multiply previous term by (a-(k-1)) * x / k
// continue until term is less than precision
for (uint i = 1; term >= precision; i++) {
uint bigK = i * BONE;
(uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE));
term = bmul(term, bmul(c, x));
term = bdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = bsub(sum, term);
} else {
sum = badd(sum, term);
}
}
return sum;
}
}
// File: contracts/weight-strategies/MCapWeightAbstract.sol
pragma solidity 0.6.12;
contract MCapWeightAbstract is BNum, OwnableUpgradeSafe {
event SetExcludeTokenBalances(address indexed token, address[] excludeTokenBalances);
event FetchTokenMCap(address indexed pool, address indexed token, uint256 mCap);
event UpdatePoolWeights(
address indexed pool,
uint256 indexed timestamp,
address[] tokens,
uint256[3][] weightsChange,
uint256[] newMCaps
);
struct TokenConfigItem {
address token;
address[] excludeTokenBalances;
}
IPowerOracle public oracle;
mapping(address => address[]) public excludeTokenBalances;
constructor(address _oracle) public OwnableUpgradeSafe() {
if (_oracle != address(0)) {
__Ownable_init();
oracle = IPowerOracle(_oracle);
}
}
function setExcludeTokenBalances(address _token, address[] calldata _excludeTokenBalances) external onlyOwner {
excludeTokenBalances[_token] = _excludeTokenBalances;
emit SetExcludeTokenBalances(_token, _excludeTokenBalances);
}
function setExcludeTokenBalancesList(TokenConfigItem[] calldata _tokenConfigItems) external onlyOwner {
uint256 len = _tokenConfigItems.length;
for (uint256 i = 0; i < len; i++) {
excludeTokenBalances[_tokenConfigItems[i].token] = _tokenConfigItems[i].excludeTokenBalances;
emit SetExcludeTokenBalances(_tokenConfigItems[i].token, _tokenConfigItems[i].excludeTokenBalances);
}
}
function getTokenMarketCap(address _token) public view returns (uint256) {
uint256 totalSupply = IERC20(_token).totalSupply();
uint256 len = excludeTokenBalances[_token].length;
for (uint256 i = 0; i < len; i++) {
totalSupply = bsub(totalSupply, IERC20(_token).balanceOf(excludeTokenBalances[_token][i]));
}
return bdiv(bmul(totalSupply, oracle.assetPrices(_token)), 1 ether);
}
function getExcludeTokenBalancesLength(address _token) external view returns (uint256) {
return excludeTokenBalances[_token].length;
}
function getExcludeTokenBalancesList(address _token) external view returns (address[] memory) {
return excludeTokenBalances[_token];
}
function _computeWeightsChangeWithEvent(
PowerIndexPoolInterface _pool,
address[] memory _tokens,
address[] memory _piTokens,
uint256 _minWPS,
uint256 _maxWPS,
uint256 fromTimestamp,
uint256 toTimestamp
) internal returns (uint256[3][] memory weightsChange, uint256 lenToPush) {
uint256[] memory newMCaps;
(weightsChange, lenToPush, newMCaps) = computeWeightsChange(
_pool,
_tokens,
_piTokens,
_minWPS,
_maxWPS,
fromTimestamp,
toTimestamp
);
emit UpdatePoolWeights(address(_pool), block.timestamp, _tokens, weightsChange, newMCaps);
}
function computeWeightsChange(
PowerIndexPoolInterface _pool,
address[] memory _tokens,
address[] memory _piTokens,
uint256 _minWPS,
uint256 _maxWPS,
uint256 fromTimestamp,
uint256 toTimestamp
)
public
view
returns (
uint256[3][] memory weightsChange,
uint256 lenToPush,
uint256[] memory newMCaps
)
{
uint256 len = _tokens.length;
newMCaps = new uint256[](len);
uint256 newMarketCapSum;
for (uint256 i = 0; i < len; i++) {
newMCaps[i] = getTokenMarketCap(_tokens[i]);
newMarketCapSum = badd(newMarketCapSum, newMCaps[i]);
}
weightsChange = new uint256[3][](len);
for (uint256 i = 0; i < len; i++) {
uint256 oldWeight;
if (_piTokens.length == _tokens.length) {
oldWeight = _pool.getDenormalizedWeight(_piTokens[i]);
} else {
oldWeight = _pool.getDenormalizedWeight(_tokens[i]);
}
uint256 newWeight = bmul(bdiv(newMCaps[i], newMarketCapSum), 25 * BONE);
weightsChange[i] = [i, oldWeight, newWeight];
}
for (uint256 i = 0; i < len; i++) {
uint256 wps = getWeightPerSecond(weightsChange[i][1], weightsChange[i][2], fromTimestamp, toTimestamp);
if (wps >= _minWPS) {
lenToPush++;
}
}
if (lenToPush > 1) {
_sort(weightsChange);
}
}
function getWeightPerSecond(
uint256 fromDenorm,
uint256 targetDenorm,
uint256 fromTimestamp,
uint256 targetTimestamp
) public pure returns (uint256) {
uint256 delta = targetDenorm > fromDenorm ? bsub(targetDenorm, fromDenorm) : bsub(fromDenorm, targetDenorm);
return div(delta, bsub(targetTimestamp, fromTimestamp));
}
function _quickSort(
uint256[3][] memory wightsChange,
int256 left,
int256 right
) internal pure {
int256 i = left;
int256 j = right;
if (i == j) return;
uint256[3] memory pivot = wightsChange[uint256(left + (right - left) / 2)];
int256 pDiff = int256(pivot[2]) - int256(pivot[1]);
while (i <= j) {
while (int256(wightsChange[uint256(i)][2]) - int256(wightsChange[uint256(i)][1]) < pDiff) i++;
while (pDiff < int256(wightsChange[uint256(j)][2]) - int256(wightsChange[uint256(j)][1])) j--;
if (i <= j) {
(wightsChange[uint256(i)], wightsChange[uint256(j)]) = (wightsChange[uint256(j)], wightsChange[uint256(i)]);
i++;
j--;
}
}
if (left < j) _quickSort(wightsChange, left, j);
if (i < right) _quickSort(wightsChange, i, right);
}
function _sort(uint256[3][] memory weightsChange) internal pure {
_quickSort(weightsChange, int256(0), int256(weightsChange.length - 1));
}
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;
}
}
// File: contracts/weight-strategies/MCapWeightStrategy.sol
pragma solidity 0.6.12;
contract MCapWeightStrategy is MCapWeightAbstract {
event AddPool(address indexed pool, address indexed poolController);
event SetPool(address indexed pool, address indexed poolController, bool indexed active);
event SetWeightsChangeDuration(uint256 weightsChangeDuration);
struct PokeVars {
PowerIndexPoolInterface pool;
uint256 minWPS;
uint256 maxWPS;
address[] tokens;
address[] piTokens;
uint256 tokensLen;
uint256 fromTimestamp;
uint256 iToPush;
}
struct Pool {
PowerIndexPoolController controller;
PowerIndexWrapperInterface wrapper;
uint256 lastWeightsUpdate;
bool active;
}
uint256 internal constant COMPENSATION_PLAN_1_ID = 1;
address[] public pools;
mapping(address => Pool) public poolsData;
uint256 weightsChangeDuration;
IPowerPoke public powerPoke;
modifier onlyReporter(uint256 _reporterId, bytes calldata _rewardOpts) {
uint256 gasStart = gasleft();
powerPoke.authorizeReporter(_reporterId, msg.sender);
_;
_reward(_reporterId, gasStart, COMPENSATION_PLAN_1_ID, _rewardOpts);
}
modifier onlyNonReporter(uint256 _reporterId, bytes calldata _rewardOpts) {
uint256 gasStart = gasleft();
powerPoke.authorizeNonReporter(_reporterId, msg.sender);
_;
_reward(_reporterId, gasStart, COMPENSATION_PLAN_1_ID, _rewardOpts);
}
modifier denyContract() {
require(msg.sender == tx.origin, "CONTRACT_CALL");
_;
}
constructor() public MCapWeightAbstract(address(0)) {}
function initialize(
address _oracle,
address _powerPoke,
uint256 _weightsChangeDuration
) external initializer {
__Ownable_init();
oracle = IPowerOracle(_oracle);
powerPoke = IPowerPoke(_powerPoke);
weightsChangeDuration = _weightsChangeDuration;
}
function setWeightsChangeDuration(uint256 _weightsChangeDuration) external onlyOwner {
weightsChangeDuration = _weightsChangeDuration;
emit SetWeightsChangeDuration(_weightsChangeDuration);
}
function addPool(
address _poolAddress,
address _controller,
address _wrapper
) external onlyOwner {
require(address(poolsData[_poolAddress].controller) == address(0), "ALREADY_EXIST");
require(_controller != address(0), "CONTROLLER_CANT_BE_NULL");
pools.push(_poolAddress);
poolsData[_poolAddress].controller = PowerIndexPoolController(_controller);
poolsData[_poolAddress].wrapper = PowerIndexWrapperInterface(_wrapper);
poolsData[_poolAddress].active = true;
emit AddPool(_poolAddress, _controller);
}
function setPool(
address _poolAddress,
address _controller,
address _wrapper,
bool _active
) external onlyOwner {
require(_controller != address(0), "CONTROLLER_CANT_BE_NULL");
poolsData[_poolAddress].controller = PowerIndexPoolController(_controller);
poolsData[_poolAddress].wrapper = PowerIndexWrapperInterface(_wrapper);
poolsData[_poolAddress].active = _active;
emit SetPool(_poolAddress, _controller, _active);
}
function pausePool(address _poolAddress) external onlyOwner {
poolsData[_poolAddress].active = false;
PowerIndexPoolInterface pool = PowerIndexPoolInterface(_poolAddress);
address[] memory tokens = pool.getCurrentTokens();
uint256 len = tokens.length;
PowerIndexPoolController.DynamicWeightInput[] memory dws;
dws = new PowerIndexPoolController.DynamicWeightInput[](len);
for (uint256 i = 0; i < len; i++) {
dws[i].token = tokens[i];
dws[i].fromTimestamp = block.timestamp + 1;
dws[i].targetTimestamp = block.timestamp + 2;
dws[i].targetDenorm = pool.getDenormalizedWeight(tokens[i]);
}
poolsData[_poolAddress].controller.setDynamicWeightListByStrategy(dws);
}
function pokeFromReporter(
uint256 _reporterId,
address[] memory _pools,
bytes calldata _rewardOpts
) external onlyReporter(_reporterId, _rewardOpts) denyContract {
_poke(_pools, false);
}
function pokeFromSlasher(
uint256 _reporterId,
address[] memory _pools,
bytes calldata _rewardOpts
) external onlyNonReporter(_reporterId, _rewardOpts) denyContract {
_poke(_pools, true);
}
function getPoolsList() external view returns (address[] memory) {
return pools;
}
function getPoolsLength() external view returns (uint256) {
return pools.length;
}
function getActivePoolsList() external view returns (address[] memory output) {
uint256 len = pools.length;
uint256 activeLen = 0;
for (uint256 i; i < len; i++) {
if (poolsData[pools[i]].active) {
activeLen++;
}
}
output = new address[](activeLen);
uint256 ai;
for (uint256 i; i < len; i++) {
if (poolsData[pools[i]].active) {
output[ai++] = pools[i];
}
}
}
function _poke(address[] memory _pools, bool _bySlasher) internal {
require(_pools.length != 0, "NULL_LENGTH");
(uint256 minInterval, uint256 maxInterval) = _getMinMaxReportInterval();
for (uint256 pi = 0; pi < _pools.length; pi++) {
PokeVars memory pv;
pv.pool = PowerIndexPoolInterface(_pools[pi]);
Pool storage pd = poolsData[address(pv.pool)];
require(pd.active, "NOT_ACTIVE");
require(pd.lastWeightsUpdate + minInterval < block.timestamp, "MIN_INTERVAL_NOT_REACHED");
if (_bySlasher) {
require(pd.lastWeightsUpdate + maxInterval < block.timestamp, "MAX_INTERVAL_NOT_REACHED");
}
(pv.minWPS, pv.maxWPS) = pv.pool.getWeightPerSecondBounds();
if (address(pd.wrapper) == address(0)) {
pv.tokens = pv.pool.getCurrentTokens();
} else {
pv.tokens = pd.wrapper.getCurrentTokens();
pv.piTokens = pv.pool.getCurrentTokens();
}
pv.tokensLen = pv.tokens.length;
pv.fromTimestamp = block.timestamp + 1;
(uint256[3][] memory weightsChange, uint256 lenToPush) =
_computeWeightsChangeWithEvent(
pv.pool,
pv.tokens,
pv.piTokens,
pv.minWPS,
pv.maxWPS,
pv.fromTimestamp,
pv.fromTimestamp + weightsChangeDuration
);
PowerIndexPoolController.DynamicWeightInput[] memory dws;
dws = new PowerIndexPoolController.DynamicWeightInput[](lenToPush);
for (uint256 i = 0; i < pv.tokensLen; i++) {
uint256 wps =
getWeightPerSecond(
weightsChange[i][1],
weightsChange[i][2],
pv.fromTimestamp,
pv.fromTimestamp + weightsChangeDuration
);
if (wps > pv.maxWPS) {
if (weightsChange[i][1] > weightsChange[i][2]) {
weightsChange[i][2] = bsub(weightsChange[i][1], mul(weightsChangeDuration, pv.maxWPS));
} else {
weightsChange[i][2] = badd(weightsChange[i][1], mul(weightsChangeDuration, pv.maxWPS));
}
}
if (wps >= pv.minWPS) {
if (address(pd.wrapper) == address(0)) {
dws[pv.iToPush].token = pv.tokens[weightsChange[i][0]];
} else {
dws[pv.iToPush].token = pv.piTokens[weightsChange[i][0]];
}
dws[pv.iToPush].fromTimestamp = pv.fromTimestamp;
dws[pv.iToPush].targetTimestamp = pv.fromTimestamp + weightsChangeDuration;
dws[pv.iToPush].targetDenorm = weightsChange[i][2];
pv.iToPush++;
}
}
if (dws.length > 0) {
pd.controller.setDynamicWeightListByStrategy(dws);
}
pd.lastWeightsUpdate = block.timestamp;
}
}
function _reward(
uint256 _reporterId,
uint256 _gasStart,
uint256 _compensationPlan,
bytes calldata _rewardOpts
) internal {
powerPoke.reward(_reporterId, bsub(_gasStart, gasleft()), _compensationPlan, _rewardOpts);
}
function _getMinMaxReportInterval() internal view returns (uint256 min, uint256 max) {
return powerPoke.getMinMaxReportIntervals(address(this));
}
}
|
Creating piToken and replacing pool token with it. _underlyingToken Token, which will be wrapped by piToken. _routerFactory Router factory, to creating router by buildRouter function. _routerArgs Router args, depends on router implementation. _name Name of piToken. _name Symbol of piToken./
|
function replacePoolTokenWithNewPiToken(
address _underlyingToken,
address _routerFactory,
bytes calldata _routerArgs,
string calldata _name,
string calldata _symbol
) external payable onlyOwner {
WrappedPiErc20Interface piToken = _createPiToken(_underlyingToken, _routerFactory, _routerArgs, _name, _symbol);
_replacePoolTokenWithPiToken(_underlyingToken, piToken);
}
| 105,955
|
pragma solidity ^0.4.21;
contract controlled{
address public owner;
uint256 public tokenFrozenUntilBlock;
uint256 public tokenFrozenSinceBlock;
uint256 public blockLock;
mapping (address => bool) restrictedAddresses;
// @dev Constructor function that sets freeze parameters so they don't unintentionally hinder operations.
function controlled() public{
owner = 0x24bF9FeCA8894A78d231f525c054048F5932dc6B;
tokenFrozenSinceBlock = (2 ** 256) - 1;
tokenFrozenUntilBlock = 0;
blockLock = 5571500;
}
/*
* @dev Transfers ownership rights to current owner to the new owner.
* @param newOwner address Address to become the new SC owner.
*/
function transferOwnership (address newOwner) onlyOwner public{
owner = newOwner;
}
/*
* @dev Allows owner to restrict or reenable addresses to use the token.
* @param _restrictedAddress address Address of the user whose state we are planning to modify.
* @param _restrict bool Restricts uder from using token. true restricts the address while false enables it.
*/
function editRestrictedAddress(address _restrictedAddress, bool _restrict) public onlyOwner{
if(!restrictedAddresses[_restrictedAddress] && _restrict){
restrictedAddresses[_restrictedAddress] = _restrict;
}
else if(restrictedAddresses[_restrictedAddress] && !_restrict){
restrictedAddresses[_restrictedAddress] = _restrict;
}
else{
revert();
}
}
/************ Modifiers to restrict access to functions. ************/
// @dev Modifier to make sure the owner's functions are only called by the owner.
modifier onlyOwner{
require(msg.sender == owner);
_;
}
/*
* @dev Modifier to check whether destination of sender aren't forbidden from using the token.
* @param _to address Address of the transfer destination.
*/
modifier instForbiddenAddress(address _to){
require(_to != 0x0);
require(_to != address(this));
require(!restrictedAddresses[_to]);
require(!restrictedAddresses[msg.sender]);
_;
}
// @dev Modifier to check if the token is operational at the moment.
modifier unfrozenToken{
require(block.number >= blockLock || msg.sender == owner);
require(block.number >= tokenFrozenUntilBlock);
require(block.number <= tokenFrozenSinceBlock);
_;
}
}
contract blocktrade is controlled{
string public name = "blocktrade.com";
string public symbol = "BTT";
uint8 public decimals = 18;
uint256 public initialSupply = 57746762*(10**18);
uint256 public supply;
string public tokenFrozenUntilNotice;
string public tokenFrozenSinceNotice;
bool public airDropFinished;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowances;
event Transfer(address indexed from, address indexed to, uint256 value);
event TokenFrozenUntil(uint256 _frozenUntilBlock, string _reason);
event TokenFrozenSince(uint256 _frozenSinceBlock, string _reason);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed from, uint256 value);
/*
* @dev Constructor function.
*/
function blocktrade() public{
supply = 57746762*(10**18);
airDropFinished = false;
balances[owner] = 57746762*(10**18);
}
/************ Constant return functions ************/
//@dev Returns the name of the token.
function tokenName() constant public returns(string _tokenName){
return name;
}
//@dev Returns the symbol of the token.
function tokenSymbol() constant public returns(string _tokenSymbol){
return symbol;
}
//@dev Returns the number of decimals the token uses - e.g. 8, means to divide the token amount by 100000000 to get its user representation.
function tokenDecimals() constant public returns(uint8 _tokenDecimals){
return decimals;
}
//@dev Returns the total supply of the token
function totalSupply() constant public returns(uint256 _totalSupply){
return supply;
}
/*
* @dev Allows us to view the token balance of the account.
* @param _tokenOwner address Address of the user whose token balance we are trying to view.
*/
function balanceOf(address _tokenOwner) constant public returns(uint256 accountBalance){
return balances[_tokenOwner];
}
/*
* @dev Allows us to view the token balance of the account.
* @param _owner address Address of the user whose token we are allowed to spend from sender address.
* @param _spender address Address of the user allowed to spend owner's tokens.
*/
function allowance(address _owner, address _spender) constant public returns(uint256 remaining) {
return allowances[_owner][_spender];
}
// @dev Returns when will the token become operational again and why it was frozen.
function getFreezeUntilDetails() constant public returns(uint256 frozenUntilBlock, string notice){
return(tokenFrozenUntilBlock, tokenFrozenUntilNotice);
}
//@dev Returns when will the operations of token stop and why.
function getFreezeSinceDetails() constant public returns(uint frozenSinceBlock, string notice){
return(tokenFrozenSinceBlock, tokenFrozenSinceNotice);
}
/*
* @dev Returns info whether address can use the token or not.
* @param _queryAddress address Address of the account we want to check.
*/
function isRestrictedAddress(address _queryAddress) constant public returns(bool answer){
return restrictedAddresses[_queryAddress];
}
/************ Operational functions ************/
/*
* @dev Used for sending own tokens to other addresses. Keep in mind that you have to take decimals into account. Multiply the value in tokens with 10^tokenDecimals.
* @param _to address Destination where we want to send the tokens to.
* @param _value uint256 Amount of tokens we want to sender.
*/
function transfer(address _to, uint256 _value) unfrozenToken instForbiddenAddress(_to) public returns(bool success){
require(balances[msg.sender] >= _value); // Check if the sender has enough
require(balances[_to] + _value >= balances[_to]) ; // Check for overflows
balances[msg.sender] -= _value; // Subtract from the sender
balances[_to] += _value; // Add the same to the recipient
emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/*
* @dev Sets allowance to the spender from our address.
* @param _spender address Address of the spender we are giving permissions to.
* @param _value uint256 Amount of tokens the spender is allowed to spend from owner's accoun. Note the decimal spaces.
*/
function approve(address _spender, uint256 _value) unfrozenToken public returns (bool success){
allowances[msg.sender][_spender] = _value; // Set allowance
emit Approval(msg.sender, _spender, _value); // Raise Approval event
return true;
}
/*
* @dev Used by spender to transfer some one else's tokens.
* @param _form address Address of the owner of the tokens.
* @param _to address Address where we want to transfer tokens to.
* @param _value uint256 Amount of tokens we want to transfer. Note the decimal spaces.
*/
function transferFrom(address _from, address _to, uint256 _value) unfrozenToken instForbiddenAddress(_to) public returns(bool success){
require(balances[_from] >= _value); // Check if the sender has enough
require(balances[_to] + _value >= balances[_to]); // Check for overflows
require(_value <= allowances[_from][msg.sender]); // Check allowance
balances[_from] -= _value; // Subtract from the sender
balances[_to] += _value; // Add the same to the recipient
allowances[_from][msg.sender] -= _value; // Deduct allowance for this address
emit Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/*
* @dev Ireversibly destroy the specified amount of tokens.
* @param _value uint256 Amount of tokens we want to destroy.
*/
function burn(uint256 _value) onlyOwner public returns(bool success){
require(balances[msg.sender] >= _value); // Check if the sender has enough
balances[msg.sender] -= _value; // Subtract from the sender
supply -= _value;
emit Burn(msg.sender, _value);
return true;
}
/*
* @dev Freezes transfers untill the specified block. Afterwards all of the operations are carried on as normal.
* @param _frozenUntilBlock uint256 Number of block untill which all of the transfers are frozen.
* @param _freezeNotice string Reason fot the freeze of operations.
*/
function freezeTransfersUntil(uint256 _frozenUntilBlock, string _freezeNotice) onlyOwner public returns(bool success){
tokenFrozenUntilBlock = _frozenUntilBlock;
tokenFrozenUntilNotice = _freezeNotice;
emit TokenFrozenUntil(_frozenUntilBlock, _freezeNotice);
return true;
}
/*
* @dev Freezes all of the transfers after specified block.
* @param _frozenSinceBlock uint256 Number of block after which all of the transfers are frozen.
* @param _freezeNotice string Reason for the freeze.
*/
function freezeTransfersSince(uint256 _frozenSinceBlock, string _freezeNotice) onlyOwner public returns(bool success){
tokenFrozenSinceBlock = _frozenSinceBlock;
tokenFrozenSinceNotice = _freezeNotice;
emit TokenFrozenSince(_frozenSinceBlock, _freezeNotice);
return true;
}
/*
* @dev Reenables the operation before the specified block was reached.
* @param _unfreezeNotice string Reason for the unfreeze or explanation of solution.
*/
function unfreezeTransfersUntil(string _unfreezeNotice) onlyOwner public returns(bool success){
tokenFrozenUntilBlock = 0;
tokenFrozenUntilNotice = _unfreezeNotice;
emit TokenFrozenUntil(0, _unfreezeNotice);
return true;
}
/*
* @dev Reenabling after the freeze since was initiated.
* @param _unfreezeNotice string Reason for the unfreeze or the explanation of solution.
*/
function unfreezeTransfersSince(string _unfreezeNotice) onlyOwner public returns(bool success){
tokenFrozenSinceBlock = (2 ** 256) - 1;
tokenFrozenSinceNotice = _unfreezeNotice;
emit TokenFrozenSince((2 ** 256) - 1, _unfreezeNotice);
return true;
}
/************ AirDrop part of the SC. ************/
/*
* @dev Allocates the specified amount of tokens to the address.
* @param _beneficiary address Address of the ouser that receives the tokens.
* @param _tokens uint256 Amount of tokens to allocate.
*/
function airDrop(address _beneficiary, uint256 _tokens) onlyOwner public returns(bool success){
require(!airDropFinished);
balances[owner] -= _tokens;
balances[_beneficiary] += _tokens;
return true;
}
// @dev Function that irreversively disables airDrop and should be called right after airDrop is completed.
function endAirDrop() onlyOwner public returns(bool success){
require(!airDropFinished);
airDropFinished = true;
return true;
}
}
//JA
|
Returns when will the token become operational again and why it was frozen.
|
function getFreezeUntilDetails() constant public returns(uint256 frozenUntilBlock, string notice){
return(tokenFrozenUntilBlock, tokenFrozenUntilNotice);
}
| 1,537,825
|
//Address: 0xc8af1ed873a5c2aafce10fe4e67124876c50e239
//Contract name: P2PFuturesTrading
//Balance: 0 Ether
//Verification Date: 6/23/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.11;
/*
P2PFuturesTrading
Trustless trading of not already transferable tokens between two people
Author: thestral.eth
*/
// ERC20 Interface: ethereum/EIPs#20
contract ERC20 {
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
}
contract P2PFuturesTrading {
struct Trade{
address tokenAddress;
uint tokenAmount;
uint etherAmount;
uint etherCollateralAmount;
uint endTradeBlock;
bool initialized;
bool finalized;
}
// Store the open trades
mapping (address => mapping(address => Trade)) public trades;
// The developer address.
address developerAddress = 0x335854eF79Fff47F9050ca853c7f3bA53eeEEE93;
function startTrade(address tokenSellerAddress, address tokenAddress, uint tokenAmount, uint etherCollateralAmount, uint endTradeBlock) payable{
//Variable validation. The endTradeBlock can't be smaller than the current one plus 220 (around 1 hour)
if(msg.value == 0 || tokenAmount == 0 || endTradeBlock <= block.number + 220){
throw;
}
Trade t1 = trades[msg.sender][tokenSellerAddress];
Trade t2 = trades[tokenSellerAddress][msg.sender];
//You can't have more than one trade at a time between the same two people. To close a non finalized trade and have you ether back, you need to call the function cancelTrade
if(t1.initialized || t2.initialized){
throw;
}
trades[msg.sender][tokenSellerAddress] = Trade(tokenAddress, tokenAmount, msg.value, etherCollateralAmount, endTradeBlock, true, false);
}
function finalizeTrade(address tokenBuyerAddress, uint etherAmount, address tokenAddress, uint tokenAmount, uint endTradeBlock) payable{
Trade t = trades[tokenBuyerAddress][msg.sender];
//It needs to exist already a trade between the two people and it hasn't have to be already finalized
if(!t.initialized || t.finalized){
throw;
}
//The trade condition specified by the two people must concide
if(!(t.tokenAddress == tokenAddress && t.tokenAmount == tokenAmount && t.etherAmount == etherAmount && t.etherCollateralAmount == msg.value && t.endTradeBlock == endTradeBlock)){
throw;
}
t.finalized = true;
}
function completeTrade(address otherPersonAddress){
Trade t;
address tokenBuyerAddress;
address tokenSellerAddress;
Trade tokenBuyerTrade = trades[msg.sender][otherPersonAddress];
Trade tokenSellerTrade = trades[otherPersonAddress][msg.sender];
//It needs to exist already a trade between the two people and it has to be already finalized.
if(tokenBuyerTrade.initialized && tokenBuyerTrade.finalized){
t = tokenBuyerTrade;
tokenBuyerAddress = msg.sender;
tokenSellerAddress = otherPersonAddress;
}
else if(tokenSellerTrade.initialized && tokenSellerTrade.finalized){
t = tokenSellerTrade;
tokenBuyerAddress = otherPersonAddress;
tokenSellerAddress = msg.sender;
}
else{
throw;
}
ERC20 token = ERC20(t.tokenAddress);
//1% developer fee, 0.5% from the tokenSeller (in tokens) and 0.5% from the tokenBuyer (in ethers). In case the trade doesn't complete the fee is of 1% of the collateral.
uint tokenSellerFee = t.tokenAmount * 5 / 1000;
uint tokenBuyerFee = t.etherAmount * 5 / 1000;
uint collateralFee = t.etherCollateralAmount / 100;
t.initialized = false;
t.finalized = false;
//If the tokenSeller didn't allow this contract of the needed amount, one of the two following functions will return false
if(!token.transferFrom(tokenSellerAddress, tokenBuyerAddress, t.tokenAmount - tokenSellerFee) || !token.transferFrom(tokenSellerAddress, developerAddress, tokenSellerFee)){
//If the maximum time has passed, and the trade coudldn't be completed, the tokenBuyer will receive his ether plus the collateral. Otherwise no action is taken.
if(t.endTradeBlock < block.number){
tokenBuyerAddress.transfer(t.etherAmount + t.etherCollateralAmount - collateralFee);
developerAddress.transfer(collateralFee);
return;
}
else{
throw;
}
}
//Transfer to the tokenSeller the etherAmount plus his collateral
tokenSellerAddress.transfer(t.etherAmount + t.etherCollateralAmount - tokenBuyerFee);
developerAddress.transfer(tokenBuyerFee);
}
function cancelTrade(address tokenSellerAddress){
Trade t = trades[msg.sender][tokenSellerAddress];
//It needs to exist already a trade between the two people and it hasn't have to be already finalized
if(!t.initialized || t.finalized){
throw;
}
//Cancel the trade and give the sender his ether back
t.initialized = false;
msg.sender.transfer(t.etherAmount);
}
}
|
It needs to exist already a trade between the two people and it hasn't have to be already finalizedThe trade condition specified by the two people must concide
|
function finalizeTrade(address tokenBuyerAddress, uint etherAmount, address tokenAddress, uint tokenAmount, uint endTradeBlock) payable{
Trade t = trades[tokenBuyerAddress][msg.sender];
if(!t.initialized || t.finalized){
throw;
}
if(!(t.tokenAddress == tokenAddress && t.tokenAmount == tokenAmount && t.etherAmount == etherAmount && t.etherCollateralAmount == msg.value && t.endTradeBlock == endTradeBlock)){
throw;
}
t.finalized = true;
}
| 5,418,209
|
// SPDX-License-Identifier: BUSL
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@plasma-fi/contracts/utils/GasStationRecipient.sol";
import "@plasma-fi/contracts/interfaces/ITokensApprover.sol";
import "./interfaces/IHyperDex.sol";
import "./packages/LibBytesV06.sol";
import "./packages/LibProxyRichErrors.sol";
import "./packages/Ownable.sol";
/// @title Plasma Finance proxy contract for 0x proxy
/// @dev A generic proxy contract which extracts a fee before delegation
contract HyperDexRouter is GasStationRecipient, Ownable {
using LibBytesV06 for bytes;
using SafeERC20 for IERC20;
// Native currency address (ETH - 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, MATIC - 0x0000000000000000000000000000000000001010)
address private nativeAddress;
address payable public beneficiary;
address payable public allowanceTarget;
IHyperDex public hyperDex;
ITokensApprover public approver;
uint256 public feeBeneficiary = 5; // 0.05%
uint256[4] public feeReferrals = [4, 3, 2, 1]; // 0.05%, 0.03%, 0.02%, 0.01%
event BeneficiaryChanged(address indexed beneficiary);
event AllowanceTargetChanged(address indexed allowanceTarget);
event HyperDexChanged(address indexed hyperDex);
event TokensApproverChanged(address indexed approver);
event FeePayment(address indexed recipient, address token, uint256 amount);
/// @dev Construct this contract and specify a fee beneficiary, 0x proxy contract address, and allowance target
constructor(address _nativeAddress, IHyperDex _hyperDex, address payable _allowanceTarget, address payable _beneficiary, address _gasStation, ITokensApprover _approver) {
nativeAddress = _nativeAddress;
hyperDex = _hyperDex;
allowanceTarget = _allowanceTarget;
beneficiary = _beneficiary;
approver = _approver;
_setGasStation(_gasStation);
}
/// @dev Fallback for just receiving ether.
receive() external payable {}
/// @dev Set a new MultiSwap proxy contract address
/// @param _hyperDex New Exchange proxy address
function setHyperDex(IHyperDex _hyperDex) public onlyOwner {
require(address(_hyperDex) != address(0), "Invalid HyperDex address");
hyperDex = _hyperDex;
emit HyperDexChanged(address(hyperDex));
}
/// @dev Set a new new allowance target address
/// @param _allowanceTarget New allowance target address
function setAllowanceTarget(address payable _allowanceTarget) public onlyOwner {
require(_allowanceTarget != address(0), "Invalid allowance target");
allowanceTarget = _allowanceTarget;
emit AllowanceTargetChanged(allowanceTarget);
}
/// @dev Set a new beneficiary address
/// @param _beneficiary New beneficiary target address
function setBeneficiary(address payable _beneficiary) public onlyOwner {
require(_beneficiary != address(0), "Invalid beneficiary");
beneficiary = _beneficiary;
emit BeneficiaryChanged(beneficiary);
}
/// @dev Set a new trusted gas station address
/// @param _gasStation New gas station address
function setGasStation(address _gasStation) external onlyOwner {
_setGasStation(_gasStation);
}
/// @dev Set a new tokens approver contract address
/// @param _approver New approver address
function setApprover(ITokensApprover _approver) external onlyOwner {
require(address(_approver) != address(0), "Invalid beneficiary");
approver = _approver;
emit TokensApproverChanged(address(approver));
}
/// @dev Set a referrals fees
/// @param _feeReferrals New referrals fees values
function setFeeReferrals(uint256[4] memory _feeReferrals) public onlyOwner {
feeReferrals = _feeReferrals;
}
/// @dev Set a beneficiary fees
/// @param _feeBeneficiary New beneficiary fees value
function setFeeBeneficiary(uint256 _feeBeneficiary) public onlyOwner {
feeBeneficiary = _feeBeneficiary;
}
/// @dev Forwards calls to the HyperDex contract and extracts a fee based on provided arguments
/// @param msgData The byte data representing a swap using the original HyperDex contract. This is either recieved from the Multiswap API directly or we construct it in order to perform a single swap trade
/// @param inputToken The ERC20 the user is selling. If this is ETH it should be the standard 0xeee ETH address
/// @param inputAmount The amount of inputToken being sold, without fees
/// @param outputToken The ERC20 the user is buying. If this is ETH it should be the standard 0xeee ETH address
/// @param referrals Referral addresses for which interest will be accrued from each exchange.
function multiRoute(
bytes calldata msgData,
address inputToken,
uint256 inputAmount,
address outputToken,
address[4] memory referrals
) external payable returns (bytes memory) {
return _multiRoute(msgData, inputToken, inputAmount, outputToken, referrals);
}
function multiRouteWithPermit(
bytes calldata msgData,
address inputToken,
uint256 inputAmount,
address outputToken,
address[4] memory referrals,
bytes calldata approvalData
) external payable returns (bytes memory) {
_permit(inputToken, approvalData);
return _multiRoute(msgData, inputToken, inputAmount, outputToken, referrals);
}
function _multiRoute(
bytes calldata msgData,
address inputToken,
uint256 inputAmount,
address outputToken,
address[4] memory referrals
) internal returns (bytes memory) {
// Calculate total fees and send to beneficiary.
uint256 inputAmountPercent = inputAmount / 10000;
uint256 fee = inputAmountPercent * feeBeneficiary;
_payFees(inputToken, fee, beneficiary);
for (uint256 i = 0; i < referrals.length; i++) {
if (referrals[i] != address(0) && feeReferrals[i] != 0) {
uint256 feeReferral = inputAmountPercent * feeReferrals[i];
fee = fee + feeReferral;
_payFees(inputToken, feeReferral, payable(referrals[i]));
}
}
// Checking the ETH balance and approve for token transfer
uint256 value = 0;
if (inputToken == nativeAddress) {
require(msg.value == inputAmount + fee, "Insufficient value with fee");
value = inputAmount;
} else {
_sendERC20(IERC20(inputToken), _msgSender(), address(this), inputAmount);
uint256 allowedAmount = IERC20(inputToken).allowance(address(this), allowanceTarget);
if (allowedAmount < inputAmount) {
IERC20(inputToken).safeIncreaseAllowance(allowanceTarget, inputAmount - allowedAmount);
}
}
// Call HyperDex multi swap
(bool success, bytes memory resultData) = address(hyperDex).call{value : value}(msgData);
if (!success) {
_revertWithData(resultData);
}
// We send the received tokens back to the sender
if (outputToken == nativeAddress) {
if (address(this).balance > 0) {
_sendETH(payable(_msgSender()), address(this).balance);
} else {
_revertWithData(resultData);
}
} else {
uint256 tokenBalance = IERC20(outputToken).balanceOf(address(this));
if (tokenBalance > 0) {
IERC20(outputToken).safeTransfer(_msgSender(), tokenBalance);
} else {
_revertWithData(resultData);
}
}
_returnWithData(resultData);
}
function _permit(address token, bytes calldata approvalData) internal {
if (approvalData.length > 0 && approver.hasConfigured(token)) {
(bool success,) = approver.callPermit(token, approvalData);
require(success, "Permit Method Call Error");
}
}
/// @dev Pay fee to beneficiary
/// @param token token address to pay fee in, can be ETH
/// @param amount fee amount to pay
function _payFees(address token, uint256 amount, address payable recipient) private {
if (token == nativeAddress) {
_sendETH(recipient, amount);
} else {
_sendERC20(IERC20(token), _msgSender(), recipient, amount);
}
emit FeePayment(recipient, token, amount);
}
function _sendETH(address payable toAddress, uint256 amount) private {
if (amount > 0) {
(bool success,) = toAddress.call{value : amount}("");
require(success, "Unable to send ETH");
}
}
function _sendERC20(IERC20 token, address fromAddress, address toAddress, uint256 amount) private {
if (amount > 0) {
token.safeTransferFrom(fromAddress, toAddress, amount);
}
}
/// @dev Revert with arbitrary bytes.
/// @param data Revert data.
function _revertWithData(bytes memory data) private pure {
assembly {revert(add(data, 32), mload(data))}
}
/// @dev Return with arbitrary bytes.
/// @param data Return data.
function _returnWithData(bytes memory data) private pure {
assembly {
return (add(data, 32), mload(data))
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "../interfaces/IGasStationRecipient.sol";
abstract contract GasStationRecipient is IGasStationRecipient {
/*
* Allowed Gas Station Contract for accept calls from
*/
address private _gasStation;
function isOwnGasStation(address addressToCheck) external view returns(bool) {
return _gasStation == addressToCheck;
}
function gasStation() external view returns (address) {
return _gasStation;
}
function _setGasStation(address newGasStation) internal {
require(newGasStation != address(0), "Invalid new gas station address");
_gasStation = newGasStation;
emit GasStationChanged(_gasStation);
}
/**
* 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 view returns (address ret) {
if (msg.data.length >= 20 && this.isOwnGasStation(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 {
ret = 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 (if the call was made directly and not through the forwarder), return `msg.data`
* should be used in the contract instead of msg.data, where this difference matters.
*/
function _msgData() internal view returns (bytes calldata ret) {
if (msg.data.length >= 20 && this.isOwnGasStation(msg.sender)) {
return msg.data[0:msg.data.length-20];
} else {
return msg.data;
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
interface ITokensApprover {
/**
* @notice Data for issuing permissions for the token
*/
struct ApproveConfig {
string name;
string version;
string domainType;
string primaryType;
string noncesMethod;
string permitMethod;
bytes4 permitMethodSelector;
}
event TokensApproverConfigAdded(uint256 indexed id);
event TokensApproverConfigUpdated(uint256 indexed id);
event TokensApproverTokenAdded(address indexed token, uint256 id);
event TokensApproverTokenRemoved(address indexed token);
function addConfig(ApproveConfig calldata config) external returns (uint256);
function updateConfig(uint256 id, ApproveConfig calldata config) external returns (uint256);
function setToken(uint256 id, address token) external;
function removeToken(address token) external;
function getConfig(address token) view external returns (ApproveConfig memory);
function getConfigById(uint256 id) view external returns (ApproveConfig memory);
function configsLength() view external returns (uint256);
function hasConfigured(address token) view external returns (bool);
function callPermit(address token, bytes calldata permitCallData) external returns (bool, bytes memory);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
interface IHyperDex {
function getFunctionImplementation(bytes4 _signature) external returns (address);
}
//SPDX-License-Identifier: BUSL
pragma solidity 0.8.10;
import "./LibBytesRichErrorsV06.sol";
import "./LibRichErrorsV06.sol";
library LibBytesV06 {
using LibBytesV06 for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// When `from == 0`, the original array will match the slice.
/// In other cases its state will be corrupted.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return result The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
if (b.length == 0) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired,
b.length,
0
));
}
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return equal True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return result address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
if (b.length < index + 20) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
if (b.length < index + 20) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return result bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
if (b.length < index + 32) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
if (b.length < index + 32) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return result uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return result bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
if (b.length < index + 4) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
b.length,
index + 4
));
}
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Writes a new length to a byte array.
/// Decreasing length will lead to removing the corresponding lower order bytes from the byte array.
/// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array.
/// @param b Bytes array to write new length to.
/// @param length New length of byte array.
function writeLength(bytes memory b, uint256 length)
internal
pure
{
assembly {
mstore(b, length)
}
}
}
//SPDX-License-Identifier: BUSL
pragma solidity 0.8.10;
library LibProxyRichErrors {
// solhint-disable func-name-mixedcase
function NotImplementedError(bytes4 selector)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("NotImplementedError(bytes4)")),
selector
);
}
function InvalidBootstrapCallerError(address actual, address expected)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidBootstrapCallerError(address,address)")),
actual,
expected
);
}
function InvalidDieCallerError(address actual, address expected)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidDieCallerError(address,address)")),
actual,
expected
);
}
function BootstrapCallFailedError(address target, bytes memory resultData)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("BootstrapCallFailedError(address,bytes)")),
target,
resultData
);
}
}
//SPDX-License-Identifier: BUSL
pragma solidity 0.8.10;
import "./Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSenderContext();
_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() == _msgSenderContext(), "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
// 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
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
interface IGasStationRecipient {
event GasStationChanged(address indexed gasStation);
function isOwnGasStation(address addressToCheck) external view returns(bool);
}
//SPDX-License-Identifier: BUSL
pragma solidity 0.8.10;
library LibBytesRichErrorsV06 {
enum InvalidByteOperationErrorCodes {
FromLessThanOrEqualsToRequired,
ToLessThanOrEqualsLengthRequired,
LengthGreaterThanZeroRequired,
LengthGreaterThanOrEqualsFourRequired,
LengthGreaterThanOrEqualsTwentyRequired,
LengthGreaterThanOrEqualsThirtyTwoRequired,
LengthGreaterThanOrEqualsNestedBytesLengthRequired,
DestinationLengthGreaterThanOrEqualSourceLengthRequired
}
// bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
0x28006595;
// solhint-disable func-name-mixedcase
function InvalidByteOperationError(
InvalidByteOperationErrorCodes errorCode,
uint256 offset,
uint256 required
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_BYTE_OPERATION_ERROR_SELECTOR,
errorCode,
offset,
required
);
}
}
//SPDX-License-Identifier: BUSL
pragma solidity 0.8.10;
library LibRichErrorsV06 {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(string memory message)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
//SPDX-License-Identifier: BUSL
pragma solidity 0.8.10;
/*
* @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 _msgSenderContext() internal view virtual returns (address) {
return msg.sender;
}
function _msgDataContext() 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;
}
}
|
return the msg.data of this call. if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes of the msg.data - so this method will strip those 20 bytes off. otherwise (if the call was made directly and not through the forwarder), return `msg.data` should be used in the contract instead of msg.data, where this difference matters./
|
function _msgData() internal view returns (bytes calldata ret) {
if (msg.data.length >= 20 && this.isOwnGasStation(msg.sender)) {
return msg.data[0:msg.data.length-20];
return msg.data;
}
}
| 155,198
|
./partial_match/1/0xE5fEB62FB34aDbA661B7c8256887a8B9a21C2278/sources/lib/solady/src/utils/LibString.sol
|
@solidity memory-safe-assembly Whether the first `searchLength % 32` bytes of `subject` and `search` matches.
|
function slice(string memory subject, uint256 start)
internal
pure
returns (string memory result)
}
function indicesOf(string memory subject, string memory search)
internal
pure
returns (uint256[] memory result)
assembly {
let subjectLength := mload(subject)
let searchLength := mload(search)
if iszero(gt(searchLength, subjectLength)) {
subject := add(subject, 0x20)
search := add(search, 0x20)
result := add(mload(0x40), 0x20)
let subjectStart := subject
let subjectSearchEnd := add(sub(add(subject, subjectLength), searchLength), 1)
let h := 0
let m := shl(3, sub(32, and(searchLength, 31)))
let s := mload(search)
let t := mload(subject)
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(subject, searchLength), h)) {
subject := add(subject, 1)
continue
}
}
result := add(result, 0x20)
if searchLength {
continue
}
}
subject := add(subject, 1)
}
let resultEnd := result
}
| 3,644,795
|
./full_match/1/0xE22020F47B7378dfedcedd2C81d4137c22fE1152/sources/contracts/Token.sol
|
Must revert to deny access.
|
function protectionAdminCheck() internal view override onlyRole(ADMIN_ROLE) {}
| 2,962,638
|
./partial_match/42/0xeeb0c120bF35fB0793b1c7d0D93230e552020398/sources/FlashBorrower.sol
|
Use this to pack arbitrary data to `onFlashLoan`
|
function flashBorrowAndSteal(address lender, address token, uint256 value) public {
bytes memory data = abi.encode(Action.STEAL);
IERC3156FlashLender(lender).flashLoan(address(this), token, value, data);
}
| 8,846,953
|
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @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 OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @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-solidity/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below
int256 c = a * b;
require(c / a == b);
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); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == INT256_MIN)); // This is the only case of 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));
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));
return c;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token 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) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
// The functionality that all derivative contracts expose to the admin.
interface AdminInterface {
// Initiates the shutdown process, in case of an emergency.
function emergencyShutdown() external;
// A core contract method called immediately before or after any financial transaction. It pays fees and moves money
// between margin accounts to make sure they reflect the NAV of the contract.
function remargin() external;
}
contract ExpandedIERC20 is IERC20 {
// Burns a specific amount of tokens. Burns the sender's tokens, so it is safe to leave this method permissionless.
function burn(uint value) external;
// Mints tokens and adds them to the balance of the `to` address.
// Note: this method should be permissioned to only allow designated parties to mint tokens.
function mint(address to, uint value) external;
}
// This interface allows derivative contracts to pay Oracle fees for their use of the system.
interface StoreInterface {
// Pays Oracle fees in ETH to the store. To be used by contracts whose margin currency is ETH.
function payOracleFees() external payable;
// Pays Oracle fees in the margin currency, erc20Address, to the store. To be used if the margin currency is an
// ERC20 token rather than ETH. All approved tokens are transfered.
function payOracleFeesErc20(address erc20Address) external;
// Computes the Oracle fees that a contract should pay for a period. `pfc` is the "profit from corruption", or the
// maximum amount of margin currency that a token sponsor could extract from the contract through corrupting the
// price feed in their favor.
function computeOracleFees(uint startTime, uint endTime, uint pfc) external view returns (uint feeAmount);
}
interface ReturnCalculatorInterface {
// Computes the return between oldPrice and newPrice.
function computeReturn(int oldPrice, int newPrice) external view returns (int assetReturn);
// Gets the effective leverage for the return calculator.
// Note: if this parameter doesn't exist for this calculator, this method should return 1.
function leverage() external view returns (int _leverage);
}
// This interface allows contracts to query unverified prices.
interface PriceFeedInterface {
// Whether this PriceFeeds provides prices for the given identifier.
function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported);
// Gets the latest time-price pair at which a price was published. The transaction will revert if no prices have
// been published for this identifier.
function latestPrice(bytes32 identifier) external view returns (uint publishTime, int price);
// An event fired when a price is published.
event PriceUpdated(bytes32 indexed identifier, uint indexed time, int price);
}
contract AddressWhitelist is Ownable {
enum Status { None, In, Out }
mapping(address => Status) private whitelist;
address[] private whitelistIndices;
// Adds an address to the whitelist
function addToWhitelist(address newElement) external onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddToWhitelist(newElement);
}
// Removes an address from the whitelist.
function removeFromWhitelist(address elementToRemove) external onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemoveFromWhitelist(elementToRemove);
}
}
// Checks whether an address is on the whitelist.
function isOnWhitelist(address elementToCheck) external view returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
// Gets all addresses that are currently included in the whitelist
// Note: This method skips over, but still iterates through addresses.
// It is possible for this call to run out of gas if a large number of
// addresses have been removed. To prevent this unlikely scenario, we can
// modify the implementation so that when addresses are removed, the last addresses
// in the array is moved to the empty index.
function getWhitelist() external view returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint activeCount = 0;
for (uint i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
event AddToWhitelist(address indexed addedAddress);
event RemoveFromWhitelist(address indexed removedAddress);
}
contract Withdrawable is Ownable {
// Withdraws ETH from the contract.
function withdraw(uint amount) external onlyOwner {
msg.sender.transfer(amount);
}
// Withdraws ERC20 tokens from the contract.
function withdrawErc20(address erc20Address, uint amount) external onlyOwner {
IERC20 erc20 = IERC20(erc20Address);
require(erc20.transfer(msg.sender, amount));
}
}
// This interface allows contracts to query a verified, trusted price.
interface OracleInterface {
// Requests the Oracle price for an identifier at a time. Returns the time at which a price will be available.
// Returns 0 is the price is available now, and returns 2^256-1 if the price will never be available. Reverts if
// the Oracle doesn't support this identifier. Only contracts registered in the Registry are authorized to call this
// method.
function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime);
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint time) external view returns (bool hasPriceAvailable);
// Returns the Oracle price for identifier at a time. Reverts if the Oracle doesn't support this identifier or if
// the Oracle doesn't have a price for this time. Only contracts registered in the Registry are authorized to call
// this method.
function getPrice(bytes32 identifier, uint time) external view returns (int price);
// Returns whether the Oracle provides verified prices for the given identifier.
function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported);
// An event fired when a request for a (identifier, time) pair is made.
event VerifiedPriceRequested(bytes32 indexed identifier, uint indexed time);
// An event fired when a verified price is available for a (identifier, time) pair.
event VerifiedPriceAvailable(bytes32 indexed identifier, uint indexed time, int price);
}
interface RegistryInterface {
struct RegisteredDerivative {
address derivativeAddress;
address derivativeCreator;
}
// Registers a new derivative. Only authorized derivative creators can call this method.
function registerDerivative(address[] calldata counterparties, address derivativeAddress) external;
// Adds a new derivative creator to this list of authorized creators. Only the owner of this contract can call
// this method.
function addDerivativeCreator(address derivativeCreator) external;
// Removes a derivative creator to this list of authorized creators. Only the owner of this contract can call this
// method.
function removeDerivativeCreator(address derivativeCreator) external;
// Returns whether the derivative has been registered with the registry (and is therefore an authorized participant
// in the UMA system).
function isDerivativeRegistered(address derivative) external view returns (bool isRegistered);
// Returns a list of all derivatives that are associated with a particular party.
function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives);
// Returns all registered derivatives.
function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives);
// Returns whether an address is authorized to register new derivatives.
function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized);
}
contract Registry is RegistryInterface, Withdrawable {
using SafeMath for uint;
// Array of all registeredDerivatives that are approved to use the UMA Oracle.
RegisteredDerivative[] private registeredDerivatives;
// This enum is required because a WasValid state is required to ensure that derivatives cannot be re-registered.
enum PointerValidity {
Invalid,
Valid,
WasValid
}
struct Pointer {
PointerValidity valid;
uint128 index;
}
// Maps from derivative address to a pointer that refers to that RegisteredDerivative in registeredDerivatives.
mapping(address => Pointer) private derivativePointers;
// Note: this must be stored outside of the RegisteredDerivative because mappings cannot be deleted and copied
// like normal data. This could be stored in the Pointer struct, but storing it there would muddy the purpose
// of the Pointer struct and break separation of concern between referential data and data.
struct PartiesMap {
mapping(address => bool) parties;
}
// Maps from derivative address to the set of parties that are involved in that derivative.
mapping(address => PartiesMap) private derivativesToParties;
// Maps from derivative creator address to whether that derivative creator has been approved to register contracts.
mapping(address => bool) private derivativeCreators;
modifier onlyApprovedDerivativeCreator {
require(derivativeCreators[msg.sender]);
_;
}
function registerDerivative(address[] calldata parties, address derivativeAddress)
external
onlyApprovedDerivativeCreator
{
// Create derivative pointer.
Pointer storage pointer = derivativePointers[derivativeAddress];
// Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double
// registered).
require(pointer.valid == PointerValidity.Invalid);
pointer.valid = PointerValidity.Valid;
registeredDerivatives.push(RegisteredDerivative(derivativeAddress, msg.sender));
// No length check necessary because we should never hit (2^127 - 1) derivatives.
pointer.index = uint128(registeredDerivatives.length.sub(1));
// Set up PartiesMap for this derivative.
PartiesMap storage partiesMap = derivativesToParties[derivativeAddress];
for (uint i = 0; i < parties.length; i = i.add(1)) {
partiesMap.parties[parties[i]] = true;
}
address[] memory partiesForEvent = parties;
emit RegisterDerivative(derivativeAddress, partiesForEvent);
}
function addDerivativeCreator(address derivativeCreator) external onlyOwner {
if (!derivativeCreators[derivativeCreator]) {
derivativeCreators[derivativeCreator] = true;
emit AddDerivativeCreator(derivativeCreator);
}
}
function removeDerivativeCreator(address derivativeCreator) external onlyOwner {
if (derivativeCreators[derivativeCreator]) {
derivativeCreators[derivativeCreator] = false;
emit RemoveDerivativeCreator(derivativeCreator);
}
}
function isDerivativeRegistered(address derivative) external view returns (bool isRegistered) {
return derivativePointers[derivative].valid == PointerValidity.Valid;
}
function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives) {
// This is not ideal - we must statically allocate memory arrays. To be safe, we make a temporary array as long
// as registeredDerivatives. We populate it with any derivatives that involve the provided party. Then, we copy
// the array over to the return array, which is allocated using the correct size. Note: this is done by double
// copying each value rather than storing some referential info (like indices) in memory to reduce the number
// of storage reads. This is because storage reads are far more expensive than extra memory space (~100:1).
RegisteredDerivative[] memory tmpDerivativeArray = new RegisteredDerivative[](registeredDerivatives.length);
uint outputIndex = 0;
for (uint i = 0; i < registeredDerivatives.length; i = i.add(1)) {
RegisteredDerivative storage derivative = registeredDerivatives[i];
if (derivativesToParties[derivative.derivativeAddress].parties[party]) {
// Copy selected derivative to the temporary array.
tmpDerivativeArray[outputIndex] = derivative;
outputIndex = outputIndex.add(1);
}
}
// Copy the temp array to the return array that is set to the correct size.
derivatives = new RegisteredDerivative[](outputIndex);
for (uint j = 0; j < outputIndex; j = j.add(1)) {
derivatives[j] = tmpDerivativeArray[j];
}
}
function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives) {
return registeredDerivatives;
}
function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized) {
return derivativeCreators[derivativeCreator];
}
event RegisterDerivative(address indexed derivativeAddress, address[] parties);
event AddDerivativeCreator(address indexed addedDerivativeCreator);
event RemoveDerivativeCreator(address indexed removedDerivativeCreator);
}
contract Testable is Ownable {
// Is the contract being run on the test network. Note: this variable should be set on construction and never
// modified.
bool public isTest;
uint private currentTime;
constructor(bool _isTest) internal {
isTest = _isTest;
if (_isTest) {
currentTime = now; // solhint-disable-line not-rely-on-time
}
}
modifier onlyIfTest {
require(isTest);
_;
}
function setCurrentTime(uint _time) external onlyOwner onlyIfTest {
currentTime = _time;
}
function getCurrentTime() public view returns (uint) {
if (isTest) {
return currentTime;
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
contract ContractCreator is Withdrawable {
Registry internal registry;
address internal oracleAddress;
address internal storeAddress;
address internal priceFeedAddress;
constructor(address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress)
public
{
registry = Registry(registryAddress);
oracleAddress = _oracleAddress;
storeAddress = _storeAddress;
priceFeedAddress = _priceFeedAddress;
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
registry.registerDerivative(parties, contractToRegister);
}
}
library TokenizedDerivativeParams {
enum ReturnType {
Linear,
Compound
}
struct ConstructorParams {
address sponsor;
address admin;
address oracle;
address store;
address priceFeed;
uint defaultPenalty; // Percentage of margin requirement * 10^18
uint supportedMove; // Expected percentage move in the underlying price that the long is protected against.
bytes32 product;
uint fixedYearlyFee; // Percentage of nav * 10^18
uint disputeDeposit; // Percentage of margin requirement * 10^18
address returnCalculator;
uint startingTokenPrice;
uint expiry;
address marginCurrency;
uint withdrawLimit; // Percentage of derivativeStorage.shortBalance * 10^18
ReturnType returnType;
uint startingUnderlyingPrice;
uint creationTime;
}
}
// TokenizedDerivativeStorage: this library name is shortened due to it being used so often.
library TDS {
enum State {
// The contract is active, and tokens can be created and redeemed. Margin can be added and withdrawn (as long as
// it exceeds required levels). Remargining is allowed. Created contracts immediately begin in this state.
// Possible state transitions: Disputed, Expired, Defaulted.
Live,
// Disputed, Expired, Defaulted, and Emergency are Frozen states. In a Frozen state, the contract is frozen in
// time awaiting a resolution by the Oracle. No tokens can be created or redeemed. Margin cannot be withdrawn.
// The resolution of these states moves the contract to the Settled state. Remargining is not allowed.
// The derivativeStorage.externalAddresses.sponsor has disputed the price feed output. If the dispute is valid (i.e., the NAV calculated from the
// Oracle price differs from the NAV calculated from the price feed), the dispute fee is added to the short
// account. Otherwise, the dispute fee is added to the long margin account.
// Possible state transitions: Settled.
Disputed,
// Contract expiration has been reached.
// Possible state transitions: Settled.
Expired,
// The short margin account is below its margin requirement. The derivativeStorage.externalAddresses.sponsor can choose to confirm the default and
// move to Settle without waiting for the Oracle. Default penalties will be assessed when the contract moves to
// Settled.
// Possible state transitions: Settled.
Defaulted,
// UMA has manually triggered a shutdown of the account.
// Possible state transitions: Settled.
Emergency,
// Token price is fixed. Tokens can be redeemed by anyone. All short margin can be withdrawn. Tokens can't be
// created, and contract can't remargin.
// Possible state transitions: None.
Settled
}
// The state of the token at a particular time. The state gets updated on remargin.
struct TokenState {
int underlyingPrice;
int tokenPrice;
uint time;
}
// The information in the following struct is only valid if in the midst of a Dispute.
struct Dispute {
int disputedNav;
uint deposit;
}
struct WithdrawThrottle {
uint startTime;
uint remainingWithdrawal;
}
struct FixedParameters {
// Fixed contract parameters.
uint defaultPenalty; // Percentage of margin requirement * 10^18
uint supportedMove; // Expected percentage move that the long is protected against.
uint disputeDeposit; // Percentage of margin requirement * 10^18
uint fixedFeePerSecond; // Percentage of nav*10^18
uint withdrawLimit; // Percentage of derivativeStorage.shortBalance*10^18
bytes32 product;
TokenizedDerivativeParams.ReturnType returnType;
uint initialTokenUnderlyingRatio;
uint creationTime;
string symbol;
}
struct ExternalAddresses {
// Other addresses/contracts
address sponsor;
address admin;
address apDelegate;
OracleInterface oracle;
StoreInterface store;
PriceFeedInterface priceFeed;
ReturnCalculatorInterface returnCalculator;
IERC20 marginCurrency;
}
struct Storage {
FixedParameters fixedParameters;
ExternalAddresses externalAddresses;
// Balances
int shortBalance;
int longBalance;
State state;
uint endTime;
// The NAV of the contract always reflects the transition from (`prev`, `current`).
// In the case of a remargin, a `latest` price is retrieved from the price feed, and we shift `current` -> `prev`
// and `latest` -> `current` (and then recompute).
// In the case of a dispute, `current` might change (which is why we have to hold on to `prev`).
TokenState referenceTokenState;
TokenState currentTokenState;
int nav; // Net asset value is measured in Wei
Dispute disputeInfo;
// Only populated once the contract enters a frozen state.
int defaultPenaltyAmount;
WithdrawThrottle withdrawThrottle;
}
}
library TokenizedDerivativeUtils {
using TokenizedDerivativeUtils for TDS.Storage;
using SafeMath for uint;
using SignedSafeMath for int;
uint private constant SECONDS_PER_DAY = 86400;
uint private constant SECONDS_PER_YEAR = 31536000;
uint private constant INT_MAX = 2**255 - 1;
uint private constant UINT_FP_SCALING_FACTOR = 10**18;
int private constant INT_FP_SCALING_FACTOR = 10**18;
modifier onlySponsor(TDS.Storage storage s) {
require(msg.sender == s.externalAddresses.sponsor);
_;
}
modifier onlyAdmin(TDS.Storage storage s) {
require(msg.sender == s.externalAddresses.admin);
_;
}
modifier onlySponsorOrAdmin(TDS.Storage storage s) {
require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.admin);
_;
}
modifier onlySponsorOrApDelegate(TDS.Storage storage s) {
require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate);
_;
}
// Contract initializer. Should only be called at construction.
// Note: Must be a public function because structs cannot be passed as calldata (required data type for external
// functions).
function _initialize(
TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) public {
s._setFixedParameters(params, symbol);
s._setExternalAddresses(params);
// Keep the starting token price relatively close to FP_SCALING_FACTOR to prevent users from unintentionally
// creating rounding or overflow errors.
require(params.startingTokenPrice >= UINT_FP_SCALING_FACTOR.div(10**9));
require(params.startingTokenPrice <= UINT_FP_SCALING_FACTOR.mul(10**9));
// TODO(mrice32): we should have an ideal start time rather than blindly polling.
(uint latestTime, int latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product);
// If nonzero, take the user input as the starting price.
if (params.startingUnderlyingPrice != 0) {
latestUnderlyingPrice = _safeIntCast(params.startingUnderlyingPrice);
}
require(latestUnderlyingPrice > 0);
require(latestTime != 0);
// Keep the ratio in case it's needed for margin computation.
s.fixedParameters.initialTokenUnderlyingRatio = params.startingTokenPrice.mul(UINT_FP_SCALING_FACTOR).div(_safeUintCast(latestUnderlyingPrice));
require(s.fixedParameters.initialTokenUnderlyingRatio != 0);
// Set end time to max value of uint to implement no expiry.
if (params.expiry == 0) {
s.endTime = ~uint(0);
} else {
require(params.expiry >= latestTime);
s.endTime = params.expiry;
}
s.nav = s._computeInitialNav(latestUnderlyingPrice, latestTime, params.startingTokenPrice);
s.state = TDS.State.Live;
}
function _depositAndCreateTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) {
s._remarginInternal();
int newTokenNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase);
if (newTokenNav < 0) {
newTokenNav = 0;
}
uint positiveTokenNav = _safeUintCast(newTokenNav);
// Get any refund due to sending more margin than the argument indicated (should only be able to happen in the
// ETH case).
uint refund = s._pullSentMargin(marginForPurchase);
// Subtract newTokenNav from amount sent.
uint depositAmount = marginForPurchase.sub(positiveTokenNav);
// Deposit additional margin into the short account.
s._depositInternal(depositAmount);
// The _createTokensInternal call returns any refund due to the amount sent being larger than the amount
// required to purchase the tokens, so we add that to the running refund. This should be 0 in this case,
// but we leave this here in case of some refund being generated due to rounding errors or any bugs to ensure
// the sender never loses money.
refund = refund.add(s._createTokensInternal(tokensToPurchase, positiveTokenNav));
// Send the accumulated refund.
s._sendMargin(refund);
}
function _redeemTokens(TDS.Storage storage s, uint tokensToRedeem) external {
require(s.state == TDS.State.Live || s.state == TDS.State.Settled);
require(tokensToRedeem > 0);
if (s.state == TDS.State.Live) {
require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate);
s._remarginInternal();
require(s.state == TDS.State.Live);
}
ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this));
uint initialSupply = _totalSupply();
require(initialSupply > 0);
_pullAuthorizedTokens(thisErc20Token, tokensToRedeem);
thisErc20Token.burn(tokensToRedeem);
emit TokensRedeemed(s.fixedParameters.symbol, tokensToRedeem);
// Value of the tokens is just the percentage of all the tokens multiplied by the balance of the investor
// margin account.
uint tokenPercentage = tokensToRedeem.mul(UINT_FP_SCALING_FACTOR).div(initialSupply);
uint tokenMargin = _takePercentage(_safeUintCast(s.longBalance), tokenPercentage);
s.longBalance = s.longBalance.sub(_safeIntCast(tokenMargin));
assert(s.longBalance >= 0);
s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
s._sendMargin(tokenMargin);
}
function _dispute(TDS.Storage storage s, uint depositMargin) external onlySponsor(s) {
require(
s.state == TDS.State.Live,
"Contract must be Live to dispute"
);
uint requiredDeposit = _safeUintCast(_takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.disputeDeposit));
uint sendInconsistencyRefund = s._pullSentMargin(depositMargin);
require(depositMargin >= requiredDeposit);
uint overpaymentRefund = depositMargin.sub(requiredDeposit);
s.state = TDS.State.Disputed;
s.endTime = s.currentTokenState.time;
s.disputeInfo.disputedNav = s.nav;
s.disputeInfo.deposit = requiredDeposit;
// Store the default penalty in case the dispute pushes the sponsor into default.
s.defaultPenaltyAmount = s._computeDefaultPenalty();
emit Disputed(s.fixedParameters.symbol, s.endTime, s.nav);
s._requestOraclePrice(s.endTime);
// Add the two types of refunds:
// 1. The refund for ETH sent if it was > depositMargin.
// 2. The refund for depositMargin > requiredDeposit.
s._sendMargin(sendInconsistencyRefund.add(overpaymentRefund));
}
function _withdraw(TDS.Storage storage s, uint amount) external onlySponsor(s) {
// Remargin before allowing a withdrawal, but only if in the live state.
if (s.state == TDS.State.Live) {
s._remarginInternal();
}
// Make sure either in Live or Settled after any necessary remargin.
require(s.state == TDS.State.Live || s.state == TDS.State.Settled);
// If the contract has been settled or is in prefunded state then can
// withdraw up to full balance. If the contract is in live state then
// must leave at least the required margin. Not allowed to withdraw in
// other states.
int withdrawableAmount;
if (s.state == TDS.State.Settled) {
withdrawableAmount = s.shortBalance;
} else {
// Update throttling snapshot and verify that this withdrawal doesn't go past the throttle limit.
uint currentTime = s.currentTokenState.time;
if (s.withdrawThrottle.startTime <= currentTime.sub(SECONDS_PER_DAY)) {
// We've passed the previous s.withdrawThrottle window. Start new one.
s.withdrawThrottle.startTime = currentTime;
s.withdrawThrottle.remainingWithdrawal = _takePercentage(_safeUintCast(s.shortBalance), s.fixedParameters.withdrawLimit);
}
int marginMaxWithdraw = s.shortBalance.sub(s._getRequiredMargin(s.currentTokenState));
int throttleMaxWithdraw = _safeIntCast(s.withdrawThrottle.remainingWithdrawal);
// Take the smallest of the two withdrawal limits.
withdrawableAmount = throttleMaxWithdraw < marginMaxWithdraw ? throttleMaxWithdraw : marginMaxWithdraw;
// Note: this line alone implicitly ensures the withdrawal throttle is not violated, but the above
// ternary is more explicit.
s.withdrawThrottle.remainingWithdrawal = s.withdrawThrottle.remainingWithdrawal.sub(amount);
}
// Can only withdraw the allowed amount.
require(
withdrawableAmount >= _safeIntCast(amount),
"Attempting to withdraw more than allowed"
);
// Transfer amount - Note: important to `-=` before the send so that the
// function can not be called multiple times while waiting for transfer
// to return.
s.shortBalance = s.shortBalance.sub(_safeIntCast(amount));
emit Withdrawal(s.fixedParameters.symbol, amount);
s._sendMargin(amount);
}
function _acceptPriceAndSettle(TDS.Storage storage s) external onlySponsor(s) {
// Right now, only confirming prices in the defaulted state.
require(s.state == TDS.State.Defaulted);
// Remargin on agreed upon price.
s._settleAgreedPrice();
}
function _setApDelegate(TDS.Storage storage s, address _apDelegate) external onlySponsor(s) {
s.externalAddresses.apDelegate = _apDelegate;
}
// Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time.
function _emergencyShutdown(TDS.Storage storage s) external onlyAdmin(s) {
require(s.state == TDS.State.Live);
s.state = TDS.State.Emergency;
s.endTime = s.currentTokenState.time;
s.defaultPenaltyAmount = s._computeDefaultPenalty();
emit EmergencyShutdownTransition(s.fixedParameters.symbol, s.endTime);
s._requestOraclePrice(s.endTime);
}
function _settle(TDS.Storage storage s) external {
s._settleInternal();
}
function _createTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) {
// Returns any refund due to sending more margin than the argument indicated (should only be able to happen in
// the ETH case).
uint refund = s._pullSentMargin(marginForPurchase);
// The _createTokensInternal call returns any refund due to the amount sent being larger than the amount
// required to purchase the tokens, so we add that to the running refund.
refund = refund.add(s._createTokensInternal(tokensToPurchase, marginForPurchase));
// Send the accumulated refund.
s._sendMargin(refund);
}
function _deposit(TDS.Storage storage s, uint marginToDeposit) external onlySponsor(s) {
// Only allow the s.externalAddresses.sponsor to deposit margin.
uint refund = s._pullSentMargin(marginToDeposit);
s._depositInternal(marginToDeposit);
// Send any refund due to sending more margin than the argument indicated (should only be able to happen in the
// ETH case).
s._sendMargin(refund);
}
// Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price.
function _calcNAV(TDS.Storage storage s) external view returns (int navNew) {
(TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance();
navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply());
}
// Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed
// price.
function _calcTokenValue(TDS.Storage storage s) external view returns (int newTokenValue) {
(TDS.TokenState memory newTokenState,) = s._calcNewTokenStateAndBalance();
newTokenValue = newTokenState.tokenPrice;
}
// Returns the expected balance of the short margin account using the latest available Price Feed price.
function _calcShortMarginBalance(TDS.Storage storage s) external view returns (int newShortMarginBalance) {
(, newShortMarginBalance) = s._calcNewTokenStateAndBalance();
}
function _calcExcessMargin(TDS.Storage storage s) external view returns (int newExcessMargin) {
(TDS.TokenState memory newTokenState, int newShortMarginBalance) = s._calcNewTokenStateAndBalance();
// If the contract is in/will be moved to a settled state, the margin requirement will be 0.
int requiredMargin = newTokenState.time >= s.endTime ? 0 : s._getRequiredMargin(newTokenState);
return newShortMarginBalance.sub(requiredMargin);
}
function _getCurrentRequiredMargin(TDS.Storage storage s) external view returns (int requiredMargin) {
if (s.state == TDS.State.Settled) {
// No margin needs to be maintained when the contract is settled.
return 0;
}
return s._getRequiredMargin(s.currentTokenState);
}
function _canBeSettled(TDS.Storage storage s) external view returns (bool canBeSettled) {
TDS.State currentState = s.state;
if (currentState == TDS.State.Settled) {
return false;
}
// Technically we should also check if price will default the contract, but that isn't a normal flow of
// operations that we want to simulate: we want to discourage the sponsor remargining into a default.
(uint priceFeedTime, ) = s._getLatestPrice();
if (currentState == TDS.State.Live && (priceFeedTime < s.endTime)) {
return false;
}
return s.externalAddresses.oracle.hasPrice(s.fixedParameters.product, s.endTime);
}
function _getUpdatedUnderlyingPrice(TDS.Storage storage s) external view returns (int underlyingPrice, uint time) {
(TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance();
return (newTokenState.underlyingPrice, newTokenState.time);
}
function _calcNewTokenStateAndBalance(TDS.Storage storage s) internal view returns (TDS.TokenState memory newTokenState, int newShortMarginBalance)
{
// TODO: there's a lot of repeated logic in this method from elsewhere in the contract. It should be extracted
// so the logic can be written once and used twice. However, much of this was written post-audit, so it was
// deemed preferable not to modify any state changing code that could potentially introduce new security
// bugs. This should be done before the next contract audit.
if (s.state == TDS.State.Settled) {
// If the contract is Settled, just return the current contract state.
return (s.currentTokenState, s.shortBalance);
}
// Grab the price feed pricetime.
(uint priceFeedTime, int priceFeedPrice) = s._getLatestPrice();
bool isContractLive = s.state == TDS.State.Live;
bool isContractPostExpiry = priceFeedTime >= s.endTime;
// If the time hasn't advanced since the last remargin, short circuit and return the most recently computed values.
if (isContractLive && priceFeedTime <= s.currentTokenState.time) {
return (s.currentTokenState, s.shortBalance);
}
// Determine which previous price state to use when computing the new NAV.
// If the contract is live, we use the reference for the linear return type or if the contract will immediately
// move to expiry.
bool shouldUseReferenceTokenState = isContractLive &&
(s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear || isContractPostExpiry);
TDS.TokenState memory lastTokenState = shouldUseReferenceTokenState ? s.referenceTokenState : s.currentTokenState;
// Use the oracle settlement price/time if the contract is frozen or will move to expiry on the next remargin.
(uint recomputeTime, int recomputePrice) = !isContractLive || isContractPostExpiry ?
(s.endTime, s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime)) :
(priceFeedTime, priceFeedPrice);
// Init the returned short balance to the current short balance.
newShortMarginBalance = s.shortBalance;
// Subtract the oracle fees from the short balance.
newShortMarginBalance = isContractLive ?
newShortMarginBalance.sub(
_safeIntCast(s._computeExpectedOracleFees(s.currentTokenState.time, recomputeTime))) :
newShortMarginBalance;
// Compute the new NAV
newTokenState = s._computeNewTokenState(lastTokenState, recomputePrice, recomputeTime);
int navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply());
newShortMarginBalance = newShortMarginBalance.sub(_getLongDiff(navNew, s.longBalance, newShortMarginBalance));
// If the contract is frozen or will move into expiry, we need to settle it, which means adding the default
// penalty and dispute deposit if necessary.
if (!isContractLive || isContractPostExpiry) {
// Subtract default penalty (if necessary) from the short balance.
bool inDefault = !s._satisfiesMarginRequirement(newShortMarginBalance, newTokenState);
if (inDefault) {
int expectedDefaultPenalty = isContractLive ? s._computeDefaultPenalty() : s._getDefaultPenalty();
int defaultPenalty = (newShortMarginBalance < expectedDefaultPenalty) ?
newShortMarginBalance :
expectedDefaultPenalty;
newShortMarginBalance = newShortMarginBalance.sub(defaultPenalty);
}
// Add the dispute deposit to the short balance if necessary.
if (s.state == TDS.State.Disputed && navNew != s.disputeInfo.disputedNav) {
int depositValue = _safeIntCast(s.disputeInfo.deposit);
newShortMarginBalance = newShortMarginBalance.add(depositValue);
}
}
}
function _computeInitialNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime, uint startingTokenPrice)
internal
returns (int navNew)
{
int unitNav = _safeIntCast(startingTokenPrice);
s.referenceTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime);
s.currentTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime);
// Starting NAV is always 0 in the TokenizedDerivative case.
navNew = 0;
}
function _remargin(TDS.Storage storage s) external onlySponsorOrAdmin(s) {
s._remarginInternal();
}
function _withdrawUnexpectedErc20(TDS.Storage storage s, address erc20Address, uint amount) external onlySponsor(s) {
if(address(s.externalAddresses.marginCurrency) == erc20Address) {
uint currentBalance = s.externalAddresses.marginCurrency.balanceOf(address(this));
int totalBalances = s.shortBalance.add(s.longBalance);
assert(totalBalances >= 0);
uint withdrawableAmount = currentBalance.sub(_safeUintCast(totalBalances)).sub(s.disputeInfo.deposit);
require(withdrawableAmount >= amount);
}
IERC20 erc20 = IERC20(erc20Address);
require(erc20.transfer(msg.sender, amount));
}
function _setExternalAddresses(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params) internal {
// Note: not all "ERC20" tokens conform exactly to this interface (BNB, OMG, etc). The most common way that
// tokens fail to conform is that they do not return a bool from certain state-changing operations. This
// contract was not designed to work with those tokens because of the additional complexity they would
// introduce.
s.externalAddresses.marginCurrency = IERC20(params.marginCurrency);
s.externalAddresses.oracle = OracleInterface(params.oracle);
s.externalAddresses.store = StoreInterface(params.store);
s.externalAddresses.priceFeed = PriceFeedInterface(params.priceFeed);
s.externalAddresses.returnCalculator = ReturnCalculatorInterface(params.returnCalculator);
// Verify that the price feed and s.externalAddresses.oracle support the given s.fixedParameters.product.
require(s.externalAddresses.oracle.isIdentifierSupported(params.product));
require(s.externalAddresses.priceFeed.isIdentifierSupported(params.product));
s.externalAddresses.sponsor = params.sponsor;
s.externalAddresses.admin = params.admin;
}
function _setFixedParameters(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) internal {
// Ensure only valid enum values are provided.
require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound
|| params.returnType == TokenizedDerivativeParams.ReturnType.Linear);
// Fee must be 0 if the returnType is linear.
require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.fixedYearlyFee == 0);
// The default penalty must be less than the required margin.
require(params.defaultPenalty <= UINT_FP_SCALING_FACTOR);
s.fixedParameters.returnType = params.returnType;
s.fixedParameters.defaultPenalty = params.defaultPenalty;
s.fixedParameters.product = params.product;
s.fixedParameters.fixedFeePerSecond = params.fixedYearlyFee.div(SECONDS_PER_YEAR);
s.fixedParameters.disputeDeposit = params.disputeDeposit;
s.fixedParameters.supportedMove = params.supportedMove;
s.fixedParameters.withdrawLimit = params.withdrawLimit;
s.fixedParameters.creationTime = params.creationTime;
s.fixedParameters.symbol = symbol;
}
// _remarginInternal() allows other functions to call remargin internally without satisfying permission checks for
// _remargin().
function _remarginInternal(TDS.Storage storage s) internal {
// If the state is not live, remargining does not make sense.
require(s.state == TDS.State.Live);
(uint latestTime, int latestPrice) = s._getLatestPrice();
// Checks whether contract has ended.
if (latestTime <= s.currentTokenState.time) {
// If the price feed hasn't advanced, remargining should be a no-op.
return;
}
// Save the penalty using the current state in case it needs to be used.
int potentialPenaltyAmount = s._computeDefaultPenalty();
if (latestTime >= s.endTime) {
s.state = TDS.State.Expired;
emit Expired(s.fixedParameters.symbol, s.endTime);
// Applies the same update a second time to effectively move the current state to the reference state.
int recomputedNav = s._computeNav(s.currentTokenState.underlyingPrice, s.currentTokenState.time);
assert(recomputedNav == s.nav);
uint feeAmount = s._deductOracleFees(s.currentTokenState.time, s.endTime);
// Save the precomputed default penalty in case the expiry price pushes the sponsor into default.
s.defaultPenaltyAmount = potentialPenaltyAmount;
// We have no idea what the price was, exactly at s.endTime, so we can't set
// s.currentTokenState, or update the nav, or do anything.
s._requestOraclePrice(s.endTime);
s._payOracleFees(feeAmount);
return;
}
uint feeAmount = s._deductOracleFees(s.currentTokenState.time, latestTime);
// Update nav of contract.
int navNew = s._computeNav(latestPrice, latestTime);
// Update the balances of the contract.
s._updateBalances(navNew);
// Make sure contract has not moved into default.
bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState);
if (inDefault) {
s.state = TDS.State.Defaulted;
s.defaultPenaltyAmount = potentialPenaltyAmount;
s.endTime = latestTime; // Change end time to moment when default occurred.
emit Default(s.fixedParameters.symbol, latestTime, s.nav);
s._requestOraclePrice(latestTime);
}
s._payOracleFees(feeAmount);
}
function _createTokensInternal(TDS.Storage storage s, uint tokensToPurchase, uint navSent) internal returns (uint refund) {
s._remarginInternal();
// Verify that remargining didn't push the contract into expiry or default.
require(s.state == TDS.State.Live);
int purchasedNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase);
if (purchasedNav < 0) {
purchasedNav = 0;
}
// Ensures that requiredNav >= navSent.
refund = navSent.sub(_safeUintCast(purchasedNav));
s.longBalance = s.longBalance.add(purchasedNav);
ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this));
thisErc20Token.mint(msg.sender, tokensToPurchase);
emit TokensCreated(s.fixedParameters.symbol, tokensToPurchase);
s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
// Make sure this still satisfies the margin requirement.
require(s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState));
}
function _depositInternal(TDS.Storage storage s, uint value) internal {
// Make sure that we are in a "depositable" state.
require(s.state == TDS.State.Live);
s.shortBalance = s.shortBalance.add(_safeIntCast(value));
emit Deposited(s.fixedParameters.symbol, value);
}
function _settleInternal(TDS.Storage storage s) internal {
TDS.State startingState = s.state;
require(startingState == TDS.State.Disputed || startingState == TDS.State.Expired
|| startingState == TDS.State.Defaulted || startingState == TDS.State.Emergency);
s._settleVerifiedPrice();
if (startingState == TDS.State.Disputed) {
int depositValue = _safeIntCast(s.disputeInfo.deposit);
if (s.nav != s.disputeInfo.disputedNav) {
s.shortBalance = s.shortBalance.add(depositValue);
} else {
s.longBalance = s.longBalance.add(depositValue);
}
}
}
// Deducts the fees from the margin account.
function _deductOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal returns (uint feeAmount) {
feeAmount = s._computeExpectedOracleFees(lastTimeOracleFeesPaid, currentTime);
s.shortBalance = s.shortBalance.sub(_safeIntCast(feeAmount));
// If paying the Oracle fee reduces the held margin below requirements, the rest of remargin() will default the
// contract.
}
// Pays out the fees to the Oracle.
function _payOracleFees(TDS.Storage storage s, uint feeAmount) internal {
if (feeAmount == 0) {
return;
}
if (address(s.externalAddresses.marginCurrency) == address(0x0)) {
s.externalAddresses.store.payOracleFees.value(feeAmount)();
} else {
require(s.externalAddresses.marginCurrency.approve(address(s.externalAddresses.store), feeAmount));
s.externalAddresses.store.payOracleFeesErc20(address(s.externalAddresses.marginCurrency));
}
}
function _computeExpectedOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime)
internal
view
returns (uint feeAmount)
{
// The profit from corruption is set as the max(longBalance, shortBalance).
int pfc = s.shortBalance < s.longBalance ? s.longBalance : s.shortBalance;
uint expectedFeeAmount = s.externalAddresses.store.computeOracleFees(lastTimeOracleFeesPaid, currentTime, _safeUintCast(pfc));
// Ensure the fee returned can actually be paid by the short margin account.
uint shortBalance = _safeUintCast(s.shortBalance);
return (shortBalance < expectedFeeAmount) ? shortBalance : expectedFeeAmount;
}
function _computeNewTokenState(TDS.Storage storage s,
TDS.TokenState memory beginningTokenState, int latestUnderlyingPrice, uint recomputeTime)
internal
view
returns (TDS.TokenState memory newTokenState)
{
int underlyingReturn = s.externalAddresses.returnCalculator.computeReturn(
beginningTokenState.underlyingPrice, latestUnderlyingPrice);
int tokenReturn = underlyingReturn.sub(
_safeIntCast(s.fixedParameters.fixedFeePerSecond.mul(recomputeTime.sub(beginningTokenState.time))));
int tokenMultiplier = tokenReturn.add(INT_FP_SCALING_FACTOR);
// In the compound case, don't allow the token price to go below 0.
if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound && tokenMultiplier < 0) {
tokenMultiplier = 0;
}
int newTokenPrice = _takePercentage(beginningTokenState.tokenPrice, tokenMultiplier);
newTokenState = TDS.TokenState(latestUnderlyingPrice, newTokenPrice, recomputeTime);
}
function _satisfiesMarginRequirement(TDS.Storage storage s, int balance, TDS.TokenState memory tokenState)
internal
view
returns (bool doesSatisfyRequirement)
{
return s._getRequiredMargin(tokenState) <= balance;
}
function _requestOraclePrice(TDS.Storage storage s, uint requestedTime) internal {
uint expectedTime = s.externalAddresses.oracle.requestPrice(s.fixedParameters.product, requestedTime);
if (expectedTime == 0) {
// The Oracle price is already available, settle the contract right away.
s._settleInternal();
}
}
function _getLatestPrice(TDS.Storage storage s) internal view returns (uint latestTime, int latestUnderlyingPrice) {
(latestTime, latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product);
require(latestTime != 0);
}
function _computeNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) {
if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound) {
navNew = s._computeCompoundNav(latestUnderlyingPrice, latestTime);
} else {
assert(s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear);
navNew = s._computeLinearNav(latestUnderlyingPrice, latestTime);
}
}
function _computeCompoundNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) {
s.referenceTokenState = s.currentTokenState;
s.currentTokenState = s._computeNewTokenState(s.currentTokenState, latestUnderlyingPrice, latestTime);
navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice);
}
function _computeLinearNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) {
// Only update the time - don't update the prices becuase all price changes are relative to the initial price.
s.referenceTokenState.time = s.currentTokenState.time;
s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, latestUnderlyingPrice, latestTime);
navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice);
}
function _recomputeNav(TDS.Storage storage s, int oraclePrice, uint recomputeTime) internal returns (int navNew) {
// We're updating `last` based on what the Oracle has told us.
assert(s.endTime == recomputeTime);
s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, oraclePrice, recomputeTime);
navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice);
}
// Function is internally only called by `_settleAgreedPrice` or `_settleVerifiedPrice`. This function handles all
// of the settlement logic including assessing penalties and then moves the state to `Settled`.
function _settleWithPrice(TDS.Storage storage s, int price) internal {
// Remargin at whatever price we're using (verified or unverified).
s._updateBalances(s._recomputeNav(price, s.endTime));
bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState);
if (inDefault) {
int expectedDefaultPenalty = s._getDefaultPenalty();
int penalty = (s.shortBalance < expectedDefaultPenalty) ?
s.shortBalance :
expectedDefaultPenalty;
s.shortBalance = s.shortBalance.sub(penalty);
s.longBalance = s.longBalance.add(penalty);
}
s.state = TDS.State.Settled;
emit Settled(s.fixedParameters.symbol, s.endTime, s.nav);
}
function _updateBalances(TDS.Storage storage s, int navNew) internal {
// Compute difference -- Add the difference to owner and subtract
// from counterparty. Then update nav state variable.
int longDiff = _getLongDiff(navNew, s.longBalance, s.shortBalance);
s.nav = navNew;
s.longBalance = s.longBalance.add(longDiff);
s.shortBalance = s.shortBalance.sub(longDiff);
}
function _getDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) {
return s.defaultPenaltyAmount;
}
function _computeDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) {
return _takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.defaultPenalty);
}
function _getRequiredMargin(TDS.Storage storage s, TDS.TokenState memory tokenState)
internal
view
returns (int requiredMargin)
{
int leverageMagnitude = _absoluteValue(s.externalAddresses.returnCalculator.leverage());
int effectiveNotional;
if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear) {
int effectiveUnitsOfUnderlying = _safeIntCast(_totalSupply().mul(s.fixedParameters.initialTokenUnderlyingRatio).div(UINT_FP_SCALING_FACTOR)).mul(leverageMagnitude);
effectiveNotional = effectiveUnitsOfUnderlying.mul(tokenState.underlyingPrice).div(INT_FP_SCALING_FACTOR);
} else {
int currentNav = _computeNavForTokens(tokenState.tokenPrice, _totalSupply());
effectiveNotional = currentNav.mul(leverageMagnitude);
}
// Take the absolute value of the notional since a negative notional has similar risk properties to a positive
// notional of the same size, and, therefore, requires the same margin.
requiredMargin = _takePercentage(_absoluteValue(effectiveNotional), s.fixedParameters.supportedMove);
}
function _pullSentMargin(TDS.Storage storage s, uint expectedMargin) internal returns (uint refund) {
if (address(s.externalAddresses.marginCurrency) == address(0x0)) {
// Refund is any amount of ETH that was sent that was above the amount that was expected.
// Note: SafeMath will force a revert if msg.value < expectedMargin.
return msg.value.sub(expectedMargin);
} else {
// If we expect an ERC20 token, no ETH should be sent.
require(msg.value == 0);
_pullAuthorizedTokens(s.externalAddresses.marginCurrency, expectedMargin);
// There is never a refund in the ERC20 case since we use the argument to determine how much to "pull".
return 0;
}
}
function _sendMargin(TDS.Storage storage s, uint amount) internal {
// There's no point in attempting a send if there's nothing to send.
if (amount == 0) {
return;
}
if (address(s.externalAddresses.marginCurrency) == address(0x0)) {
msg.sender.transfer(amount);
} else {
require(s.externalAddresses.marginCurrency.transfer(msg.sender, amount));
}
}
function _settleAgreedPrice(TDS.Storage storage s) internal {
int agreedPrice = s.currentTokenState.underlyingPrice;
s._settleWithPrice(agreedPrice);
}
function _settleVerifiedPrice(TDS.Storage storage s) internal {
int oraclePrice = s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime);
s._settleWithPrice(oraclePrice);
}
function _pullAuthorizedTokens(IERC20 erc20, uint amountToPull) private {
// If nothing is being pulled, there's no point in calling a transfer.
if (amountToPull > 0) {
require(erc20.transferFrom(msg.sender, address(this), amountToPull));
}
}
// Gets the change in balance for the long side.
// Note: there's a function for this because signage is tricky here, and it must be done the same everywhere.
function _getLongDiff(int navNew, int longBalance, int shortBalance) private pure returns (int longDiff) {
int newLongBalance = navNew;
// Long balance cannot go below zero.
if (newLongBalance < 0) {
newLongBalance = 0;
}
longDiff = newLongBalance.sub(longBalance);
// Cannot pull more margin from the short than is available.
if (longDiff > shortBalance) {
longDiff = shortBalance;
}
}
function _computeNavForTokens(int tokenPrice, uint numTokens) private pure returns (int navNew) {
int navPreDivision = _safeIntCast(numTokens).mul(tokenPrice);
navNew = navPreDivision.div(INT_FP_SCALING_FACTOR);
// The navNew division above truncates by default. Instead, we prefer to ceil this value to ensure tokens
// cannot be purchased or backed with less than their true value.
if ((navPreDivision % INT_FP_SCALING_FACTOR) != 0) {
navNew = navNew.add(1);
}
}
function _totalSupply() private view returns (uint totalSupply) {
ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this));
return thisErc20Token.totalSupply();
}
function _takePercentage(uint value, uint percentage) private pure returns (uint result) {
return value.mul(percentage).div(UINT_FP_SCALING_FACTOR);
}
function _takePercentage(int value, uint percentage) private pure returns (int result) {
return value.mul(_safeIntCast(percentage)).div(INT_FP_SCALING_FACTOR);
}
function _takePercentage(int value, int percentage) private pure returns (int result) {
return value.mul(percentage).div(INT_FP_SCALING_FACTOR);
}
function _absoluteValue(int value) private pure returns (int result) {
return value < 0 ? value.mul(-1) : value;
}
function _safeIntCast(uint value) private pure returns (int result) {
require(value <= INT_MAX);
return int(value);
}
function _safeUintCast(int value) private pure returns (uint result) {
require(value >= 0);
return uint(value);
}
// Note that we can't have the symbol parameter be `indexed` due to:
// TypeError: Indexed reference types cannot yet be used with ABIEncoderV2.
// An event emitted when the NAV of the contract changes.
event NavUpdated(string symbol, int newNav, int newTokenPrice);
// An event emitted when the contract enters the Default state on a remargin.
event Default(string symbol, uint defaultTime, int defaultNav);
// An event emitted when the contract settles.
event Settled(string symbol, uint settleTime, int finalNav);
// An event emitted when the contract expires.
event Expired(string symbol, uint expiryTime);
// An event emitted when the contract's NAV is disputed by the sponsor.
event Disputed(string symbol, uint timeDisputed, int navDisputed);
// An event emitted when the contract enters emergency shutdown.
event EmergencyShutdownTransition(string symbol, uint shutdownTime);
// An event emitted when tokens are created.
event TokensCreated(string symbol, uint numTokensCreated);
// An event emitted when tokens are redeemed.
event TokensRedeemed(string symbol, uint numTokensRedeemed);
// An event emitted when margin currency is deposited.
event Deposited(string symbol, uint amount);
// An event emitted when margin currency is withdrawn.
event Withdrawal(string symbol, uint amount);
}
// TODO(mrice32): make this and TotalReturnSwap derived classes of a single base to encap common functionality.
contract TokenizedDerivative is ERC20, AdminInterface, ExpandedIERC20 {
using TokenizedDerivativeUtils for TDS.Storage;
// Note: these variables are to give ERC20 consumers information about the token.
string public name;
string public symbol;
uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase
TDS.Storage public derivativeStorage;
constructor(
TokenizedDerivativeParams.ConstructorParams memory params,
string memory _name,
string memory _symbol
) public {
// Set token properties.
name = _name;
symbol = _symbol;
// Initialize the contract.
derivativeStorage._initialize(params, _symbol);
}
// Creates tokens with sent margin and returns additional margin.
function createTokens(uint marginForPurchase, uint tokensToPurchase) external payable {
derivativeStorage._createTokens(marginForPurchase, tokensToPurchase);
}
// Creates tokens with sent margin and deposits additional margin in short account.
function depositAndCreateTokens(uint marginForPurchase, uint tokensToPurchase) external payable {
derivativeStorage._depositAndCreateTokens(marginForPurchase, tokensToPurchase);
}
// Redeems tokens for margin currency.
function redeemTokens(uint tokensToRedeem) external {
derivativeStorage._redeemTokens(tokensToRedeem);
}
// Triggers a price dispute for the most recent remargin time.
function dispute(uint depositMargin) external payable {
derivativeStorage._dispute(depositMargin);
}
// Withdraws `amount` from short margin account.
function withdraw(uint amount) external {
derivativeStorage._withdraw(amount);
}
// Pays (Oracle and service) fees for the previous period, updates the contract NAV, moves margin between long and
// short accounts to reflect the new NAV, and checks if both accounts meet minimum requirements.
function remargin() external {
derivativeStorage._remargin();
}
// Forgo the Oracle verified price and settle the contract with last remargin price. This method is only callable on
// contracts in the `Defaulted` state, and the default penalty is always transferred from the short to the long
// account.
function acceptPriceAndSettle() external {
derivativeStorage._acceptPriceAndSettle();
}
// Assigns an address to be the contract's Delegate AP. Replaces previous value. Set to 0x0 to indicate there is no
// Delegate AP.
function setApDelegate(address apDelegate) external {
derivativeStorage._setApDelegate(apDelegate);
}
// Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time.
function emergencyShutdown() external {
derivativeStorage._emergencyShutdown();
}
// Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price.
function calcNAV() external view returns (int navNew) {
return derivativeStorage._calcNAV();
}
// Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed
// price.
function calcTokenValue() external view returns (int newTokenValue) {
return derivativeStorage._calcTokenValue();
}
// Returns the expected balance of the short margin account using the latest available Price Feed price.
function calcShortMarginBalance() external view returns (int newShortMarginBalance) {
return derivativeStorage._calcShortMarginBalance();
}
// Returns the expected short margin in excess of the margin requirement using the latest available Price Feed
// price. Value will be negative if the short margin is expected to be below the margin requirement.
function calcExcessMargin() external view returns (int excessMargin) {
return derivativeStorage._calcExcessMargin();
}
// Returns the required margin, as of the last remargin. Note that `calcExcessMargin` uses updated values using the
// latest available Price Feed price.
function getCurrentRequiredMargin() external view returns (int requiredMargin) {
return derivativeStorage._getCurrentRequiredMargin();
}
// Returns whether the contract can be settled, i.e., is it valid to call settle() now.
function canBeSettled() external view returns (bool canContractBeSettled) {
return derivativeStorage._canBeSettled();
}
// Returns the updated underlying price that was used in the calc* methods above. It will be a price feed price if
// the contract is Live and will remain Live, or an Oracle price if the contract is settled/about to be settled.
// Reverts if no Oracle price is available but an Oracle price is required.
function getUpdatedUnderlyingPrice() external view returns (int underlyingPrice, uint time) {
return derivativeStorage._getUpdatedUnderlyingPrice();
}
// When an Oracle price becomes available, performs a final remargin, assesses any penalties, and moves the contract
// into the `Settled` state.
function settle() external {
derivativeStorage._settle();
}
// Adds the margin sent along with the call (or in the case of an ERC20 margin currency, authorized before the call)
// to the short account.
function deposit(uint amountToDeposit) external payable {
derivativeStorage._deposit(amountToDeposit);
}
// Allows the sponsor to withdraw any ERC20 balance that is not the margin token.
function withdrawUnexpectedErc20(address erc20Address, uint amount) external {
derivativeStorage._withdrawUnexpectedErc20(erc20Address, amount);
}
// ExpandedIERC20 methods.
modifier onlyThis {
require(msg.sender == address(this));
_;
}
// Only allow calls from this contract or its libraries to burn tokens.
function burn(uint value) external onlyThis {
// Only allow calls from this contract or its libraries to burn tokens.
_burn(msg.sender, value);
}
// Only allow calls from this contract or its libraries to mint tokens.
function mint(address to, uint256 value) external onlyThis {
_mint(to, value);
}
// These events are actually emitted by TokenizedDerivativeUtils, but we unfortunately have to define the events
// here as well.
event NavUpdated(string symbol, int newNav, int newTokenPrice);
event Default(string symbol, uint defaultTime, int defaultNav);
event Settled(string symbol, uint settleTime, int finalNav);
event Expired(string symbol, uint expiryTime);
event Disputed(string symbol, uint timeDisputed, int navDisputed);
event EmergencyShutdownTransition(string symbol, uint shutdownTime);
event TokensCreated(string symbol, uint numTokensCreated);
event TokensRedeemed(string symbol, uint numTokensRedeemed);
event Deposited(string symbol, uint amount);
event Withdrawal(string symbol, uint amount);
}
contract TokenizedDerivativeCreator is ContractCreator, Testable {
struct Params {
uint defaultPenalty; // Percentage of mergin requirement * 10^18
uint supportedMove; // Expected percentage move in the underlying that the long is protected against.
bytes32 product;
uint fixedYearlyFee; // Percentage of nav * 10^18
uint disputeDeposit; // Percentage of mergin requirement * 10^18
address returnCalculator;
uint startingTokenPrice;
uint expiry;
address marginCurrency;
uint withdrawLimit; // Percentage of shortBalance * 10^18
TokenizedDerivativeParams.ReturnType returnType;
uint startingUnderlyingPrice;
string name;
string symbol;
}
AddressWhitelist public sponsorWhitelist;
AddressWhitelist public returnCalculatorWhitelist;
AddressWhitelist public marginCurrencyWhitelist;
constructor(
address registryAddress,
address _oracleAddress,
address _storeAddress,
address _priceFeedAddress,
address _sponsorWhitelist,
address _returnCalculatorWhitelist,
address _marginCurrencyWhitelist,
bool _isTest
)
public
ContractCreator(registryAddress, _oracleAddress, _storeAddress, _priceFeedAddress)
Testable(_isTest)
{
sponsorWhitelist = AddressWhitelist(_sponsorWhitelist);
returnCalculatorWhitelist = AddressWhitelist(_returnCalculatorWhitelist);
marginCurrencyWhitelist = AddressWhitelist(_marginCurrencyWhitelist);
}
function createTokenizedDerivative(Params memory params)
public
returns (address derivativeAddress)
{
TokenizedDerivative derivative = new TokenizedDerivative(_convertParams(params), params.name, params.symbol);
address[] memory parties = new address[](1);
parties[0] = msg.sender;
_registerContract(parties, address(derivative));
return address(derivative);
}
// Converts createTokenizedDerivative params to TokenizedDerivative constructor params.
function _convertParams(Params memory params)
private
view
returns (TokenizedDerivativeParams.ConstructorParams memory constructorParams)
{
// Copy and verify externally provided variables.
require(sponsorWhitelist.isOnWhitelist(msg.sender));
constructorParams.sponsor = msg.sender;
require(returnCalculatorWhitelist.isOnWhitelist(params.returnCalculator));
constructorParams.returnCalculator = params.returnCalculator;
require(marginCurrencyWhitelist.isOnWhitelist(params.marginCurrency));
constructorParams.marginCurrency = params.marginCurrency;
constructorParams.defaultPenalty = params.defaultPenalty;
constructorParams.supportedMove = params.supportedMove;
constructorParams.product = params.product;
constructorParams.fixedYearlyFee = params.fixedYearlyFee;
constructorParams.disputeDeposit = params.disputeDeposit;
constructorParams.startingTokenPrice = params.startingTokenPrice;
constructorParams.expiry = params.expiry;
constructorParams.withdrawLimit = params.withdrawLimit;
constructorParams.returnType = params.returnType;
constructorParams.startingUnderlyingPrice = params.startingUnderlyingPrice;
// Copy internal variables.
constructorParams.priceFeed = priceFeedAddress;
constructorParams.oracle = oracleAddress;
constructorParams.store = storeAddress;
constructorParams.admin = oracleAddress;
constructorParams.creationTime = getCurrentTime();
}
}
|
Make sure that we are in a "depositable" state.
|
function _depositInternal(TDS.Storage storage s, uint value) internal {
require(s.state == TDS.State.Live);
s.shortBalance = s.shortBalance.add(_safeIntCast(value));
emit Deposited(s.fixedParameters.symbol, value);
}
| 972,346
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "./UbiquityAlgorithmicDollarManager.sol";
import "./interfaces/IDollarMintingCalculator.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./TWAPOracle.sol";
import "./libs/ABDKMathQuad.sol";
/// @title A mock coupon calculator that always returns a constant
contract DollarMintingCalculator is IDollarMintingCalculator {
using ABDKMathQuad for uint256;
using ABDKMathQuad for bytes16;
bytes16 private immutable _one = (uint256(1 ether)).fromUInt();
UbiquityAlgorithmicDollarManager public manager;
/// @param _manager the address of the manager contract so we can fetch variables
constructor(address _manager) {
manager = UbiquityAlgorithmicDollarManager(_manager);
}
/// @notice returns (TWAP_PRICE -1) * UAD_Total_Supply
function getDollarsToMint() external view override returns (uint256) {
TWAPOracle oracle = TWAPOracle(manager.twapOracleAddress());
uint256 twapPrice = oracle.consult(manager.dollarTokenAddress());
require(twapPrice > 1, "DollarMintingCalculator: not > 1");
return
twapPrice
.fromUInt()
.sub(_one)
.mul(
(
IERC20(manager.dollarTokenAddress())
.totalSupply()
.fromUInt()
.div(_one)
)
)
.toUInt();
}
}
|
returns (TWAP_PRICE -1) UAD_Total_Supply
|
function getDollarsToMint() external view override returns (uint256) {
TWAPOracle oracle = TWAPOracle(manager.twapOracleAddress());
uint256 twapPrice = oracle.consult(manager.dollarTokenAddress());
require(twapPrice > 1, "DollarMintingCalculator: not > 1");
return
twapPrice
.fromUInt()
.sub(_one)
.mul(
(
IERC20(manager.dollarTokenAddress())
.totalSupply()
.fromUInt()
.div(_one)
)
)
.toUInt();
}
| 12,859,105
|
./full_match/5/0x525f6e07fE55dA049cAe29CdD68cCa40204D0d64/sources/contracts/CarRide.sol
|
Function to request a ride
|
function requestRide(string[] memory _pickup, string[] memory _dropoff, uint _amount) public returns (uint) {
require(bytes(riders[msg.sender].name).length != 0, "Rider not registered. Please register as a rider first.");
address payable riderAddr = payable(msg.sender);
uint newRideId = rideIdCounter++;
rides.push(Ride(newRideId, riderAddr, payable(address(0)), _pickup, _dropoff, _amount, false, false, false));
emit RequestDriverEvent(riderAddr, _pickup, _dropoff);
return newRideId;
}
| 1,899,318
|
//Address: 0xc3951d77737733174152532e8b0f27e2c4e9f0dc
//Contract name: Cloud
//Balance: 0 Ether
//Verification Date: 8/30/2017
//Transacion Count: 3353
// CODE STARTS HERE
pragma solidity ^0.4.16;
library Math {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Token {
/// total amount of tokens
uint256 public totalSupply;
uint256 public decimals;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Cloud is Token {
using Math for uint256;
bool trading=false;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function transfer(address _to, uint256 _value) canTrade returns (bool success) {
require(_value > 0);
require(!frozenAccount[msg.sender]);
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) canTrade returns (bool success) {
require(_value > 0);
require(!frozenAccount[_from]);
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value);
//require(balances[_from] >= _value);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/* Checks if tokens can be transferred from one account to another. Trading to be enabled after initial token release */
modifier canTrade {
require(trading==true ||(canRelease==true && msg.sender==owner));
_;
}
function setTrade(bool allow) onlyOwner {
trading=allow;
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
/* Public variables of the token */
event Invested(address investor, uint256 tokens);
uint256 public employeeShare=8;
// Wallets - 4 employee
address[4] employeeWallets = [0x9caeD53A6C6E91546946dD866dFD66c0aaB9f347,0xf1Df495BE71d1E5EdEbCb39D85D5F6b620aaAF47,0xa3C38bc8dD6e26eCc0D64d5B25f5ce855bb57Cd5,0x4d67a23b62399eDec07ad9c0f748D89655F0a0CB];
string public name;
string public symbol;
address public owner;
uint256 public tokensReleased=0;
bool canRelease=false;
/* Initializes contract with initial supply tokens to the owner of the contract */
function Cloud(
uint256 _initialAmount,
uint256 _decimalUnits,
string _tokenName,
string _tokenSymbol,
address ownerWallet
) {
owner=ownerWallet;
decimals = _decimalUnits; // Amount of decimals for display purposes
totalSupply = _initialAmount*(10**decimals); // Update total supply
balances[owner] = totalSupply; // Give the creator all initial tokens
name = _tokenName; // Set the name for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
/* Freezing tokens */
function freezeAccount(address target, bool freeze) onlyOwner{
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/* Authenticating owner */
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/* Allow and restrict of release of tokens */
function releaseTokens(bool allow) onlyOwner {
canRelease=allow;
}
/// @param receiver The address of the account which will receive the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the token transfer was successful or not was successful or not
function invest(address receiver, uint256 _value) onlyOwner returns (bool success) {
require(canRelease);
require(_value > 0);
uint256 numTokens = _value;
uint256 employeeTokens = 0;
uint256 employeeTokenShare=0;
// divide employee tokens by 4 shares
employeeTokens = numTokens.mul(employeeShare).div(100);
employeeTokenShare = employeeTokens.div(employeeWallets.length);
//split tokens for different wallets of employees and company
approve(owner,employeeTokens.add(numTokens));
for(uint i = 0; i < employeeWallets.length; i++)
{
require(transferFrom(owner, employeeWallets[i], employeeTokenShare));
}
require(transferFrom(owner, receiver, numTokens));
tokensReleased = tokensReleased.add(numTokens).add(employeeTokens.mul(4));
Invested(receiver,numTokens);
return true;
}
}
|
Allow and restrict of release of tokens /
|
function releaseTokens(bool allow) onlyOwner {
canRelease=allow;
}
| 12,998,250
|
//Address: 0xA4F902f57Fd9FFcedF4dE6cF7EbC86ea9F76B5d1
//Contract name: EtheraffleICO
//Balance: 7.348300000000000094 Ether
//Verification Date: 3/7/2018
//Transacion Count: 28
// CODE STARTS HERE
pragma solidity^0.4.15;
contract EtheraffleLOT {
function mint(address _to, uint _amt) external {}
function transfer(address to, uint value) public {}
function balanceOf(address who) constant public returns (uint) {}
}
contract EtheraffleICO is EtheraffleLOT {
/* Lot reward per ether in each tier */
uint public constant tier0LOT = 110000 * 10 ** 6;
uint public constant tier1LOT = 100000 * 10 ** 6;
uint public constant tier2LOT = 90000 * 10 ** 6;
uint public constant tier3LOT = 80000 * 10 ** 6;
/* Bonus tickets multiplier */
uint public constant bonusLOT = 1500 * 10 ** 6;
uint public constant bonusFreeLOT = 10;
/* Maximum amount of ether investable per tier */
uint public constant maxWeiTier0 = 700 * 10 ** 18;
uint public constant maxWeiTier1 = 2500 * 10 ** 18;
uint public constant maxWeiTier2 = 7000 * 10 ** 18;
uint public constant maxWeiTier3 = 20000 * 10 ** 18;
/* Minimum investment (0.025 Ether) */
uint public constant minWei = 25 * 10 ** 15;
/* Crowdsale open, close, withdraw & tier times (UTC Format)*/
uint public ICOStart = 1522281600;//Thur 29th March 2018
uint public tier1End = 1523491200;//Thur 12th April 2018
uint public tier2End = 1525305600;//Thur 3rd May 2018
uint public tier3End = 1527724800;//Thur 31st May 2018
uint public wdBefore = 1528934400;//Thur 14th June 2018
/* Variables to track amount of purchases in tier */
uint public tier0Total;
uint public tier1Total;
uint public tier2Total;
uint public tier3Total;
/* Etheraffle's multisig wallet & LOT token addresses */
address public etheraffle;
/* ICO status toggle */
bool public ICORunning = true;
/* Map of purchaser's ethereum addresses to their purchase amounts for calculating bonuses*/
mapping (address => uint) public tier0;
mapping (address => uint) public tier1;
mapping (address => uint) public tier2;
mapping (address => uint) public tier3;
/* Instantiate the variables to hold Etheraffle's LOT & freeLOT token contract instances */
EtheraffleLOT LOT;
EtheraffleLOT FreeLOT;
/* Event loggers */
event LogTokenDeposit(address indexed from, uint value, bytes data);
event LogRefund(address indexed toWhom, uint amountOfEther, uint atTime);
event LogEtherTransfer(address indexed toWhom, uint amount, uint atTime);
event LogBonusLOTRedemption(address indexed toWhom, uint lotAmount, uint atTime);
event LogLOTTransfer(address indexed toWhom, uint indexed inTier, uint ethAmt, uint LOTAmt, uint atTime);
/**
* @dev Modifier function to prepend to later functions in this contract in
* order to redner them only useable by the Etheraffle address.
*/
modifier onlyEtheraffle() {
require(msg.sender == etheraffle);
_;
}
/**
* @dev Modifier function to prepend to later functions rendering the method
* only callable if the crowdsale is running.
*/
modifier onlyIfRunning() {
require(ICORunning);
_;
}
/**
* @dev Modifier function to prepend to later functions rendering the method
* only callable if the crowdsale is NOT running.
*/
modifier onlyIfNotRunning() {
require(!ICORunning);
_;
}
/**
* @dev Constructor. Sets up the variables pertaining to the ICO start &
* end times, the tier start & end times, the Etheraffle MultiSig Wallet
* address & the Etheraffle LOT & FreeLOT token contracts.
*/
function EtheraffleICO() public {//address _LOT, address _freeLOT, address _msig) public {
etheraffle = 0x97f535e98cf250cdd7ff0cb9b29e4548b609a0bd;
LOT = EtheraffleLOT(0xAfD9473dfe8a49567872f93c1790b74Ee7D92A9F);
FreeLOT = EtheraffleLOT(0xc39f7bB97B31102C923DaF02bA3d1bD16424F4bb);
}
/**
* @dev Purchase LOT tokens.
* LOT are sent in accordance with how much ether is invested, and in what
* tier the investment was made. The function also stores the amount of ether
* invested for later conversion to the amount of bonus LOT owed. Once the
* crowdsale is over and the final number of tokens sold is known, the purchaser's
* bonuses can be calculated. Using the fallback function allows LOT purchasers to
* simply send ether to this address in order to purchase LOT, without having
* to call a function. The requirements also also mean that once the crowdsale is
* over, any ether sent to this address by accident will be returned to the sender
* and not lost.
*/
function () public payable onlyIfRunning {
/* Requires the crowdsale time window to be open and the function caller to send ether */
require
(
now <= tier3End &&
msg.value >= minWei
);
uint numLOT = 0;
if (now <= ICOStart) {// โด tier zero...
/* Eth investable in each tier is capped via this requirement */
require(tier0Total + msg.value <= maxWeiTier0);
/* Store purchasers purchased amount for later bonus redemption */
tier0[msg.sender] += msg.value;
/* Track total investment in tier one for later bonus calculation */
tier0Total += msg.value;
/* Number of LOT this tier's purchase results in */
numLOT = (msg.value * tier0LOT) / (1 * 10 ** 18);
/* Transfer the number of LOT bought to the purchaser */
LOT.transfer(msg.sender, numLOT);
/* Log the transfer */
LogLOTTransfer(msg.sender, 0, msg.value, numLOT, now);
return;
} else if (now <= tier1End) {// โด tier one...
require(tier1Total + msg.value <= maxWeiTier1);
tier1[msg.sender] += msg.value;
tier1Total += msg.value;
numLOT = (msg.value * tier1LOT) / (1 * 10 ** 18);
LOT.transfer(msg.sender, numLOT);
LogLOTTransfer(msg.sender, 1, msg.value, numLOT, now);
return;
} else if (now <= tier2End) {// โด tier two...
require(tier2Total + msg.value <= maxWeiTier2);
tier2[msg.sender] += msg.value;
tier2Total += msg.value;
numLOT = (msg.value * tier2LOT) / (1 * 10 ** 18);
LOT.transfer(msg.sender, numLOT);
LogLOTTransfer(msg.sender, 2, msg.value, numLOT, now);
return;
} else {// โด tier three...
require(tier3Total + msg.value <= maxWeiTier3);
tier3[msg.sender] += msg.value;
tier3Total += msg.value;
numLOT = (msg.value * tier3LOT) / (1 * 10 ** 18);
LOT.transfer(msg.sender, numLOT);
LogLOTTransfer(msg.sender, 3, msg.value, numLOT, now);
return;
}
}
/**
* @dev Redeem bonus LOT: This function cannot be called until
* the crowdsale is over, nor after the withdraw period.
* During this window, a LOT purchaser calls this function
* in order to receive their bonus LOT owed to them, as
* calculated by their share of the total amount of LOT
* sales in the tier(s) following their purchase. Once
* claimed, user's purchased amounts are set to 1 wei rather
* than zero, to allow the contract to maintain a list of
* purchasers in each. All investors, regardless of tier/amount,
* receive ten free entries into the flagship Saturday
* Etheraffle via the FreeLOT coupon.
*/
function redeemBonusLot() external onlyIfRunning { //81k gas
/* Requires crowdsale to be over and the wdBefore time to not have passed yet */
require
(
now > tier3End &&
now < wdBefore
);
/* Requires user to have a LOT purchase in at least one of the tiers. */
require
(
tier0[msg.sender] > 1 ||
tier1[msg.sender] > 1 ||
tier2[msg.sender] > 1 ||
tier3[msg.sender] > 1
);
uint bonusNumLOT;
/* If purchaser has ether in this tier, LOT tokens owed is calculated and added to LOT amount */
if(tier0[msg.sender] > 1) {
bonusNumLOT +=
/* Calculate share of bonus LOT user is entitled to, based on tier one sales */
((tier1Total * bonusLOT * tier0[msg.sender]) / (tier0Total * (1 * 10 ** 18))) +
/* Calculate share of bonus LOT user is entitled to, based on tier two sales */
((tier2Total * bonusLOT * tier0[msg.sender]) / (tier0Total * (1 * 10 ** 18))) +
/* Calculate share of bonus LOT user is entitled to, based on tier three sales */
((tier3Total * bonusLOT * tier0[msg.sender]) / (tier0Total * (1 * 10 ** 18)));
/* Set amount of ether in this tier to 1 to make further bonus redemptions impossible */
tier0[msg.sender] = 1;
}
if(tier1[msg.sender] > 1) {
bonusNumLOT +=
((tier2Total * bonusLOT * tier1[msg.sender]) / (tier1Total * (1 * 10 ** 18))) +
((tier3Total * bonusLOT * tier1[msg.sender]) / (tier1Total * (1 * 10 ** 18)));
tier1[msg.sender] = 1;
}
if(tier2[msg.sender] > 1) {
bonusNumLOT +=
((tier3Total * bonusLOT * tier2[msg.sender]) / (tier2Total * (1 * 10 ** 18)));
tier2[msg.sender] = 1;
}
if(tier3[msg.sender] > 1) {
tier3[msg.sender] = 1;
}
/* Final check that user cannot withdraw twice */
require
(
tier0[msg.sender] <= 1 &&
tier1[msg.sender] <= 1 &&
tier2[msg.sender] <= 1 &&
tier3[msg.sender] <= 1
);
/* Transfer bonus LOT to bonus redeemer */
if(bonusNumLOT > 0) {
LOT.transfer(msg.sender, bonusNumLOT);
}
/* Mint FreeLOT and give to bonus redeemer */
FreeLOT.mint(msg.sender, bonusFreeLOT);
/* Log the bonus LOT redemption */
LogBonusLOTRedemption(msg.sender, bonusNumLOT, now);
}
/**
* @dev Should crowdsale be cancelled for any reason once it has
* begun, any ether is refunded to the purchaser by calling
* this funcion. Function checks each tier in turn, totalling
* the amount whilst zeroing the balance, and finally makes
* the transfer.
*/
function refundEther() external onlyIfNotRunning {
uint amount;
if(tier0[msg.sender] > 1) {
/* Add balance of caller's address in this tier to the amount */
amount += tier0[msg.sender];
/* Zero callers balance in this tier */
tier0[msg.sender] = 0;
}
if(tier1[msg.sender] > 1) {
amount += tier1[msg.sender];
tier1[msg.sender] = 0;
}
if(tier2[msg.sender] > 1) {
amount += tier2[msg.sender];
tier2[msg.sender] = 0;
}
if(tier3[msg.sender] > 1) {
amount += tier3[msg.sender];
tier3[msg.sender] = 0;
}
/* Final check that user cannot be refunded twice */
require
(
tier0[msg.sender] == 0 &&
tier1[msg.sender] == 0 &&
tier2[msg.sender] == 0 &&
tier3[msg.sender] == 0
);
/* Transfer the ether to the caller */
msg.sender.transfer(amount);
/* Log the refund */
LogRefund(msg.sender, amount, now);
return;
}
/**
* @dev Function callable only by Etheraffle's multi-sig wallet. It
* transfers the tier's raised ether to the etheraffle multisig wallet
* once the tier is over.
*
* @param _tier The tier from which the withdrawal is being made.
*/
function transferEther(uint _tier) external onlyIfRunning onlyEtheraffle {
if(_tier == 0) {
/* Require tier zero to be over and a tier zero ether be greater than 0 */
require(now > ICOStart && tier0Total > 0);
/* Transfer the tier zero total to the etheraffle multisig */
etheraffle.transfer(tier0Total);
/* Log the transfer event */
LogEtherTransfer(msg.sender, tier0Total, now);
return;
} else if(_tier == 1) {
require(now > tier1End && tier1Total > 0);
etheraffle.transfer(tier1Total);
LogEtherTransfer(msg.sender, tier1Total, now);
return;
} else if(_tier == 2) {
require(now > tier2End && tier2Total > 0);
etheraffle.transfer(tier2Total);
LogEtherTransfer(msg.sender, tier2Total, now);
return;
} else if(_tier == 3) {
require(now > tier3End && tier3Total > 0);
etheraffle.transfer(tier3Total);
LogEtherTransfer(msg.sender, tier3Total, now);
return;
} else if(_tier == 4) {
require(now > tier3End && this.balance > 0);
etheraffle.transfer(this.balance);
LogEtherTransfer(msg.sender, this.balance, now);
return;
}
}
/**
* @dev Function callable only by Etheraffle's multi-sig wallet.
* It transfers any remaining unsold LOT tokens to the
* Etheraffle multisig wallet. Function only callable once
* the withdraw period and โด the ICO ends.
*/
function transferLOT() onlyEtheraffle onlyIfRunning external {
require(now > wdBefore);
uint amt = LOT.balanceOf(this);
LOT.transfer(etheraffle, amt);
LogLOTTransfer(msg.sender, 5, 0, amt, now);
}
/**
* @dev Toggle crowdsale status. Only callable by the Etheraffle
* mutlisig account. If set to false, the refund function
* becomes live allow purchasers to withdraw their ether
*
*/
function setCrowdSaleStatus(bool _status) external onlyEtheraffle {
ICORunning = _status;
}
/**
* @dev This function is what allows this contract to receive ERC223
* compliant tokens. Any tokens sent to this address will fire off
* an event announcing their arrival. Unlike ERC20 tokens, ERC223
* tokens cannot be sent to contracts absent this function,
* thereby preventing loss of tokens by mistakenly sending them to
* contracts not designed to accept them.
*
* @param _from From whom the transfer originated
* @param _value How many tokens were sent
* @param _data Transaction metadata
*/
function tokenFallback(address _from, uint _value, bytes _data) public {
if (_value > 0) {
LogTokenDeposit(_from, _value, _data);
}
}
/**
* @dev Housekeeping function in the event this contract is no
* longer needed. Will delete the code from the blockchain.
*/
function selfDestruct() external onlyIfNotRunning onlyEtheraffle {
selfdestruct(etheraffle);
}
}
|
Toggle crowdsale status. Only callable by the Etheraffle mutlisig account. If set to false, the refund function becomes live allow purchasers to withdraw their ether/
|
function setCrowdSaleStatus(bool _status) external onlyEtheraffle {
ICORunning = _status;
}
| 13,066,155
|
./full_match/1/0xeF6303006a994f469Ef0FBDe20b269e804adB985/sources/src/Staking/StakingV1.sol
|
use unchecked here so index can overflow, since it doesn't matter. this prevents the incredibly unlikely future problem of running into an overflow error and probably saves some gas
|
function _autoClaim() internal virtual {
if (!_autoClaimEnabled) return;
uint256 startingGas = gasleft();
uint256 iterations = 0;
while (startingGas - gasleft() < _autoClaimGasLimit && iterations++ < _totalNumStakers) {
uint64 index;
unchecked {
index = _autoClaimIndex++;
}
address autoClaimAddress = _autoClaimQueue[1 + (index % _totalNumStakers)];
if (!_stakers[autoClaimAddress].autoClaimOptOut)
_claim(autoClaimAddress);
}
}
| 16,403,975
|
pragma solidity ^0.5.0;
import "./ERC721Patronage_v0.sol";
contract WildcardSteward_v0 is Initializable {
/*
This smart contract collects patronage from current owner through a Harberger tax model and
takes stewardship of the asset token if the patron can't pay anymore.
Harberger Tax (COST):
- Asset is always on sale.
- You have to have a price set.
- Tax (Patronage) is paid to maintain ownership.
- Steward maints control over ERC721.
*/
using SafeMath for uint256;
mapping(uint256 => uint256) public price; //in wei
ERC721Patronage_v0 public assetToken; // ERC721 NFT.
mapping(uint256 => uint256) public totalCollected; // all patronage ever collected
mapping(uint256 => uint256) public currentCollected; // amount currently collected for patron
mapping(uint256 => uint256) public timeLastCollected;
mapping(address => uint256) public timeLastCollectedPatron;
mapping(address => uint256) public deposit;
mapping(address => uint256) public totalPatronOwnedTokenCost;
mapping(uint256 => address) public benefactors; // non-profit benefactor
mapping(address => uint256) public benefactorFunds;
mapping(uint256 => address) public currentPatron; // This is different to the current token owner.
mapping(uint256 => mapping(address => bool)) public patrons;
mapping(uint256 => mapping(address => uint256)) public timeHeld;
mapping(uint256 => uint256) public timeAcquired;
// 1200% patronage
mapping(uint256 => uint256) public patronageNumerator;
uint256 public patronageDenominator;
enum StewardState {Foreclosed, Owned}
mapping(uint256 => StewardState) public state;
address public admin;
event LogBuy(address indexed owner, uint256 indexed price);
event LogPriceChange(uint256 indexed newPrice);
event LogForeclosure(address indexed prevOwner);
event LogCollection(uint256 indexed collected);
event LogRemainingDepositUpdate(
address indexed tokenPatron,
uint256 indexed remainingDeposit
);
event AddToken(uint256 indexed tokenId, uint256 patronageNumerator);
modifier onlyPatron(uint256 tokenId) {
require(msg.sender == currentPatron[tokenId], "Not patron");
_;
}
// modifier onlyReceivingBenefactor(uint256 tokenId) {
// require(msg.sender == benefactors[tokenId], "Not benefactor");
// _;
// }
modifier onlyAdmin() {
require(msg.sender == admin, "Not admin");
_;
}
modifier onlyReceivingBenefactorOrAdmin(uint256 tokenId) {
require(
msg.sender == benefactors[tokenId] || msg.sender == admin,
"Not benefactor or admin"
);
_;
}
modifier collectPatronage(uint256 tokenId) {
_collectPatronage(tokenId);
_;
}
modifier collectPatronageAddress(address tokenPatron) {
_collectPatronagePatron(tokenPatron);
_;
}
function initialize(
address _assetToken,
address _admin,
uint256 _patronageDenominator
) public initializer {
assetToken = ERC721Patronage_v0(_assetToken);
admin = _admin;
patronageDenominator = _patronageDenominator;
}
// TODO:: add validation that the token that is complient with the "PatronageToken" ERC721 interface extension somehow!
function listNewTokens(
uint256[] memory tokens,
address payable[] memory _benefactors,
uint256[] memory _patronageNumerator
) public onlyAdmin {
assert(tokens.length == _benefactors.length);
for (uint8 i = 0; i < tokens.length; ++i) {
assert(_benefactors[i] != address(0));
benefactors[tokens[i]] = _benefactors[i];
state[tokens[i]] = StewardState.Foreclosed;
patronageNumerator[tokens[i]] = _patronageNumerator[i];
emit AddToken(tokens[i], _patronageNumerator[i]);
}
}
function changeReceivingBenefactor(
uint256 tokenId,
address payable _newReceivingBenefactor
) public onlyReceivingBenefactorOrAdmin(tokenId) {
address oldBenfactor = benefactors[tokenId];
benefactors[tokenId] = _newReceivingBenefactor;
benefactorFunds[_newReceivingBenefactor] = benefactorFunds[oldBenfactor];
benefactorFunds[oldBenfactor] = 0;
}
function changeAdmin(address _admin) public onlyAdmin {
admin = _admin;
}
/* public view functions */
function patronageOwed(uint256 tokenId)
public
view
returns (uint256 patronageDue)
{
if (timeLastCollected[tokenId] == 0) return 0;
return
price[tokenId]
.mul(now.sub(timeLastCollected[tokenId]))
.mul(patronageNumerator[tokenId])
.div(patronageDenominator)
.div(365 days);
}
function patronageOwedWithTimestamp(uint256 tokenId)
public
view
returns (uint256 patronageDue, uint256 timestamp)
{
return (patronageOwed(tokenId), now);
}
// TODO: make a version of this function that is for patronage owed by token rather than by tokenPatron like it is now.
function patronageOwedPatron(address tokenPatron)
public
view
returns (uint256 patronageDue)
{
if (timeLastCollectedPatron[tokenPatron] == 0) return 0;
// NOTE/TODO: to cater to different patronage rates, we should include it in the `totalPatronOwnedTokenCost` (and probably rename that variable)
return
totalPatronOwnedTokenCost[tokenPatron]
.mul(now.sub(timeLastCollectedPatron[tokenPatron]))
.div(patronageDenominator)
.div(365 days);
}
function patronageOwedPatronWithTimestamp(address tokenPatron)
public
view
returns (uint256 patronageDue, uint256 timestamp)
{
return (patronageOwedPatron(tokenPatron), now);
}
function foreclosedPatron(address tokenPatron) public view returns (bool) {
// returns whether it is in foreclosed state or not
// depending on whether deposit covers patronage due
// useful helper function when price should be zero, but contract doesn't reflect it yet.
if (patronageOwedPatron(tokenPatron) >= deposit[tokenPatron]) {
return true;
} else {
return false;
}
}
function foreclosed(uint256 tokenId) public view returns (bool) {
// returns whether it is in foreclosed state or not
// depending on whether deposit covers patronage due
// useful helper function when price should be zero, but contract doesn't reflect it yet.
address tokenPatron = currentPatron[tokenId];
return foreclosedPatron(tokenPatron);
}
// same function as above, basically
function depositAbleToWithdraw(address tokenPatron)
public
view
returns (uint256)
{
uint256 collection = patronageOwedPatron(tokenPatron);
if (collection >= deposit[tokenPatron]) {
return 0;
} else {
return deposit[tokenPatron].sub(collection);
}
}
/*
now + deposit/patronage per second
now + depositAbleToWithdraw/(price*nume/denom/365).
*/
function foreclosureTimePatron(address tokenPatron)
public
view
returns (uint256)
{
// patronage per second
uint256 pps = totalPatronOwnedTokenCost[tokenPatron]
.div(patronageDenominator)
.div(365 days);
return now.add(depositAbleToWithdraw(tokenPatron).div(pps)); // zero division if price is zero.
}
function foreclosureTime(uint256 tokenId) public view returns (uint256) {
address tokenPatron = currentPatron[tokenId];
return foreclosureTimePatron(tokenPatron);
}
/* actions */
// TODO:: think of more efficient ways for recipients to collect patronage for lots of tokens at the same time.
function _collectPatronage(uint256 tokenId) public {
// determine patronage to pay
if (state[tokenId] == StewardState.Owned) {
address tokenPatron = currentPatron[tokenId];
uint256 previousTokenCollection = timeLastCollected[tokenId];
uint256 patronageOwedByTokenPatron = patronageOwedPatron(
tokenPatron
);
uint256 collection;
// should foreclose and stake stewardship
if (patronageOwedByTokenPatron >= deposit[tokenPatron]) {
// up to when was it actually paid for?
uint256 newTimeLastCollected
= timeLastCollectedPatron[tokenPatron].add(
(
(now.sub(timeLastCollectedPatron[tokenPatron]))
.mul(deposit[tokenPatron])
.div(patronageOwedByTokenPatron)
)
);
timeLastCollected[tokenId] = newTimeLastCollected;
timeLastCollectedPatron[tokenPatron] = newTimeLastCollected;
collection = price[tokenId]
.mul(newTimeLastCollected.sub(previousTokenCollection))
.mul(patronageNumerator[tokenId])
.div(patronageDenominator)
.div(365 days);
deposit[tokenPatron] = 0;
_foreclose(tokenId); // This only forecloses a single token
} else {
// just a normal collection
collection = price[tokenId]
.mul(now.sub(previousTokenCollection))
.mul(patronageNumerator[tokenId])
.div(patronageDenominator)
.div(365 days);
timeLastCollected[tokenId] = now;
timeLastCollectedPatron[tokenPatron] = now;
currentCollected[tokenId] = currentCollected[tokenId].add(
collection
);
deposit[tokenPatron] = deposit[tokenPatron].sub(
patronageOwedByTokenPatron
);
}
totalCollected[tokenId] = totalCollected[tokenId].add(collection);
address benefactor = benefactors[tokenId];
benefactorFunds[benefactor] = benefactorFunds[benefactor].add(
collection
);
emit LogCollection(collection);
}
}
// This does accounting without transfering any tokens
function _collectPatronagePatron(address tokenPatron) public {
uint256 patronageOwedByTokenPatron = patronageOwedPatron(tokenPatron);
if (
patronageOwedByTokenPatron > 0 &&
patronageOwedByTokenPatron >= deposit[tokenPatron]
) {
uint256 previousCollectionTime
= timeLastCollectedPatron[tokenPatron];
// up to when was it actually paid for?
uint256 newTimeLastCollected = previousCollectionTime.add(
(
(now.sub(previousCollectionTime))
.mul(deposit[tokenPatron])
.div(patronageOwedByTokenPatron)
)
);
timeLastCollectedPatron[tokenPatron] = newTimeLastCollected;
deposit[tokenPatron] = 0;
} else {
timeLastCollectedPatron[tokenPatron] = now;
deposit[tokenPatron] = deposit[tokenPatron].sub(
patronageOwedByTokenPatron
);
}
emit LogRemainingDepositUpdate(tokenPatron, deposit[tokenPatron]);
}
// note: anyone can deposit
function depositWei() public payable {
depositWeiPatron(msg.sender);
}
function depositWeiPatron(address patron) public payable {
require(totalPatronOwnedTokenCost[patron] > 0, "No tokens owned");
deposit[patron] = deposit[patron].add(msg.value);
}
function buy(uint256 tokenId, uint256 _newPrice)
public
payable
collectPatronage(tokenId)
collectPatronageAddress(msg.sender)
{
require(_newPrice > 0, "Price is zero");
require(msg.value > price[tokenId], "Not enough"); // >, coz need to have at least something for deposit
address currentOwner = assetToken.ownerOf(tokenId);
address tokenPatron = currentPatron[tokenId];
if (state[tokenId] == StewardState.Owned) {
uint256 totalToPayBack = price[tokenId];
// NOTE: pay back the deposit only if it is the only token the patron owns.
if (
totalPatronOwnedTokenCost[tokenPatron] ==
price[tokenId].mul(patronageNumerator[tokenId])
) {
totalToPayBack = totalToPayBack.add(deposit[tokenPatron]);
deposit[tokenPatron] = 0;
}
// pay previous owner their price + deposit back.
address payable payableCurrentPatron = address(
uint160(tokenPatron)
);
payableCurrentPatron.transfer(totalToPayBack);
} else if (state[tokenId] == StewardState.Foreclosed) {
state[tokenId] = StewardState.Owned;
timeLastCollected[tokenId] = now;
}
deposit[msg.sender] = deposit[msg.sender].add(
msg.value.sub(price[tokenId])
);
transferAssetTokenTo(
tokenId,
currentOwner,
tokenPatron,
msg.sender,
_newPrice
);
emit LogBuy(msg.sender, _newPrice);
}
function changePrice(uint256 tokenId, uint256 _newPrice)
public
onlyPatron(tokenId)
collectPatronage(tokenId)
{
require(state[tokenId] != StewardState.Foreclosed, "Foreclosed");
require(_newPrice != 0, "Incorrect Price");
totalPatronOwnedTokenCost[msg.sender] = totalPatronOwnedTokenCost[msg
.sender]
.sub(price[tokenId].mul(patronageNumerator[tokenId]))
.add(_newPrice.mul(patronageNumerator[tokenId]));
price[tokenId] = _newPrice;
emit LogPriceChange(price[tokenId]);
}
function withdrawDeposit(uint256 _wei)
public
collectPatronageAddress(msg.sender)
returns (uint256)
{
_withdrawDeposit(_wei);
}
function withdrawBenefactorFunds() public {
withdrawBenefactorFundsTo(msg.sender);
}
function withdrawBenefactorFundsTo(address payable benefactor) public {
require(benefactorFunds[benefactor] > 0, "No funds available");
benefactor.transfer(benefactorFunds[benefactor]);
benefactorFunds[benefactor] = 0;
}
function exit() public collectPatronageAddress(msg.sender) {
_withdrawDeposit(deposit[msg.sender]);
}
/* internal */
function _withdrawDeposit(uint256 _wei) internal {
// note: can withdraw whole deposit, which puts it in immediate to be foreclosed state.
require(deposit[msg.sender] >= _wei, "Withdrawing too much");
deposit[msg.sender] = deposit[msg.sender].sub(_wei);
msg.sender.transfer(_wei); // msg.sender == patron
}
function _foreclose(uint256 tokenId) internal {
// become steward of assetToken (aka foreclose)
address currentOwner = assetToken.ownerOf(tokenId);
address tokenPatron = currentPatron[tokenId];
transferAssetTokenTo(
tokenId,
currentOwner,
tokenPatron,
address(this),
0
);
state[tokenId] = StewardState.Foreclosed;
currentCollected[tokenId] = 0;
emit LogForeclosure(currentOwner);
}
function transferAssetTokenTo(
uint256 tokenId,
address _currentOwner,
address _currentPatron,
address _newOwner,
uint256 _newPrice
) internal {
// TODO: add the patronage rate as a multiplier here: https://github.com/wild-cards/contracts/issues/7
totalPatronOwnedTokenCost[_newOwner] = totalPatronOwnedTokenCost[_newOwner]
.add(_newPrice.mul(patronageNumerator[tokenId]));
totalPatronOwnedTokenCost[_currentPatron] = totalPatronOwnedTokenCost[_currentPatron]
.sub(price[tokenId].mul(patronageNumerator[tokenId]));
// note: it would also tabulate time held in stewardship by smart contract
timeHeld[tokenId][_currentPatron] = timeHeld[tokenId][_currentPatron]
.add((timeLastCollected[tokenId].sub(timeAcquired[tokenId])));
assetToken.transferFrom(_currentOwner, _newOwner, tokenId);
currentPatron[tokenId] = _newOwner;
price[tokenId] = _newPrice;
timeAcquired[tokenId] = now;
patrons[tokenId][_newOwner] = true;
}
}
|
returns whether it is in foreclosed state or not depending on whether deposit covers patronage due useful helper function when price should be zero, but contract doesn't reflect it yet.
|
function foreclosedPatron(address tokenPatron) public view returns (bool) {
if (patronageOwedPatron(tokenPatron) >= deposit[tokenPatron]) {
return true;
return false;
}
}
| 900,119
|
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./Migrations.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Threshold when Multi-Party-Consensus gets activated
uint256 private constant MPC_THRESHOLD = 5;
// Maximum amount that an insurance can cost
uint256 private constant MAX_INSURANCE_PRICE = 1 ether;
// Minimum amount that is required to fund an airline in the contract
uint256 private constant MIN_FUNDING_AMOUNT = 10 ether;
// Account used to deploy contract
address private contractOwner;
// Blocks all state changes throughout the contract if false
bool private operational = true;
// Number of overall airlines.
uint256 private allAirlinesCount = 0;
// Number of airlines that are part of the contract.
uint256 private registeredAirlinesCount = 0;
// Number of airlines that have provided the funding of 10 ETH.
uint256 private fundedAirlinesCount = 0;
// Registration Queue
uint256 private registrationQueue;
// Struct that represents an airline.
struct Airline{
string name;
address wallet;
bool isRegistered;
bool isFunded;
}
// Struct that represents votes
struct Vote{
address memberRequest;
uint256 votes;
bool success;
mapping(address => bool) hasVoted;
uint256 memberCount;
bool mpcRequired;
uint256 threshold;
}
// Struct that represents an Insurance
struct Insurance{
uint256 value;
address customer;
string flight;
bytes32 flightKey;
address airline;
uint256 timestamp;
//bool processed;
}
// Mapping to map Insurance to passengers
mapping(bytes32 => Insurance) private insurances;
// Maps flight key to status code and states true if the flight is late (code 20) due to an airline error,
// false otherwise. If this is true, an insurance payout is granted, otherwise not.
mapping(bytes32 => bool) private flightLateAirline;
// Contract funding to stay self-sustaining in case of many delayed flights
mapping(address => uint256) private funding;
// Credits per insured passenger
mapping(address => uint256) private credits;
// Mapping to store votingResults for addresses
mapping(address => Vote) private votes;
// Mapping to store Airlines
mapping(address => Airline) private airlines;
// Mapping for authorized callers
mapping(address => bool) private authorizedCallers;
// Multi-Party Consensus
address[] multiCalls = new address[](0);
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
// Access Control Events
event CallerAuthorized(address caller);
// Airline Events
event AirlineAvailable(address airlineAddress);
event AirlineRegistered(address airlineAddress, bool isRegistered);
event AirlineFunded(address airlineAddress, bool isFunded, uint256 funding);
event AirlineInRegistrationQueue(address airlineAddress);
event AirlineRemovedFromRegistrationQueue(address airlineAddress);
event DebugAirlineFunds(address airline, uint256 funding);
event DebugFundingReduced(address airline, uint256 amount, uint256 funds);
// Voting Events
event VoteCounted(address votedBy, address votedFor, bool voting);
event VotingSuccessful(address airlineAddress, uint256 threshold, uint256 numVotes);
// Flight Events
event FlightLateAirline(bytes32 flightKey);
// Insurance Events
event InsurancePurchased(address customer, bytes32 flightKey, uint256 amount);
event InsureeCredited(address customer, bytes32 flightKey, uint256 amount);
event InsuranceDeleted(bytes32 flightKey);
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(
address initialAirlineAddress
)
public
{
contractOwner = msg.sender;
airlines[initialAirlineAddress] = Airline({
name:"Lufthansa",
wallet:initialAirlineAddress,
isRegistered:true,
isFunded:false
});
// emit Events
emit AirlineAvailable(initialAirlineAddress);
emit AirlineRegistered(initialAirlineAddress, airlines[initialAirlineAddress].isRegistered);
// Increase the registered airlines counter by 1.
registeredAirlinesCount = registeredAirlinesCount.add(1);
allAirlinesCount = allAirlinesCount.add(1);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires the "Airline" account is registered.
*/
modifier requireAirlineIsRegistered(address _address)
{
require(airlines[_address].isRegistered == true, "Airline is not registered.");
_;
}
/**
* @dev Modifier that requires the "Airline" account is funded.
*/
modifier requireAirlineIsFunded(address _address)
{
require(airlines[_address].isFunded == true, "Airline is not funded.");
_;
}
/**
* @dev Modifier that requires the "Caller" to be authorized.
*/
modifier requireAuthorizedCaller(address _address) {
require(authorizedCallers[_address] == true, "Caller is not authorized to call this data contract");
_;
}
/**
* @dev Modifier that ensures that only "one vote" per airline is possible
*/
modifier requireFirstVote(address _voteBy, address _voteFor) {
require(votes[_voteFor].hasVoted[_voteBy] == false,
"Only one vote per Airline is possible per memberRequest"
);
_;
}
/**
* @dev Modifier that requires an active memberRequest.
*/
modifier requireActiveMemberRequest(address _address) {
require(votes[_address].memberRequest != address(0),
"A memberRequest must be available before a vote can be triggered"
);
_;
}
/**
* @dev Modifier that requires an active memberRequest.
*/
modifier requireMPCThresholdReached(address _address) {
require(votes[_address].mpcRequired == true,
"Voting for a memberRequest can only be triggered if MPC is required."
);
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Returns the cap of a single insurance
*
* @return Maximum Insurance Price as uint256
*/
function getInsuranceCap() external pure returns (uint256) {
return MAX_INSURANCE_PRICE;
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns (bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(
bool mode
)
external
requireContractOwner
{
require(mode != operational, "New mode must be different from existing mode");
operational = mode;
}
/**
* @dev Sets contract addresses that are allowed to call into this smart contract.
*/
function authorizeCaller(
address applicationContractAddress
)
public
requireContractOwner
requireIsOperational
{
require(applicationContractAddress != address(0), "applicationContractAddress must not be [0x0]");
authorizedCallers[applicationContractAddress] = true;
emit CallerAuthorized(applicationContractAddress);
}
/**
* @dev Return the requested airline.
*/
function getAirline(
address _address
)
public
view
returns (
string _name,
address _wallet,
bool _isRegistered,
bool _isFunded
)
{
_name = airlines[_address].name;
_wallet = airlines[_address].wallet;
_isRegistered = airlines[_address].isRegistered;
_isFunded = airlines[_address].isFunded;
}
/**
* @dev Returns true if the Airline is registered, otherwise false.
*/
function isAirlineRegistered(
address _address
)
external
view
returns(bool)
{
return airlines[_address].isRegistered;
}
/**
* @dev Returns true if the Airline is funded, otherwise false.
*/
function isAirlineFunded(
address _address
)
external
view
returns(bool)
{
return airlines[_address].isFunded;
}
/**
* @dev Returns true if the calling address is authorized.
*/
function isCallerAuthorized(
address _address
)
public
view
returns(bool)
{
return authorizedCallers[_address];
}
/**
* @dev Returns the votes for an address
*/
function getVotingCount(
address _address
)
external
view
requireIsOperational
returns(uint256)
{
return (votes[_address].votes);
}
/**
* @dev Returns the votes for an address
*/
function getVotingResult(
address _address
)
external
view
requireIsOperational
returns(bool)
{
return (votes[_address].success);
}
/**
* @dev Returns the votes for an address
*/
function getVote(
address _address
)
external
view
returns(uint256, uint256, uint256, bool)
{
return (
votes[_address].memberCount,
votes[_address].votes,
votes[_address].threshold,
votes[_address].success
);
}
/**
* @dev Returns the number of airlines - registered and unregistered
*/
function getOverallAirlineCount()
external
view
returns(uint256)
{
return allAirlinesCount;
}
/**
* @dev Returns the number of registered airlines
*/
function getRegisteredAirlinesCount()
external
view
returns(uint256)
{
return registeredAirlinesCount;
}
/**
* @dev Returns the length of the registration queue.
*/
function getRegistrationQueueLength()
external
view
returns(uint256)
{
return registrationQueue;
}
/**
* @dev Get status for a flight - true: if the airline caused the delay, false: otherwise
*/
function getFlightStatus(bytes32 flightKey) external view returns(bool) {
return flightLateAirline[flightKey];
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Sets status for a flight - true: if the airline caused the delay, false: otherwise
*/
function setFlightStatus(
bytes32 flightKey,
bool status
)
external
{
flightLateAirline[flightKey] = status;
emit FlightLateAirline(flightKey);
}
/**
* @dev Allows airlines to vote for new members.
*/
function voteForAirlineRegistration(
address _address,
bool _vote
)
external
requireAirlineIsRegistered(msg.sender)
requireAirlineIsFunded(msg.sender)
requireFirstVote(msg.sender, _address)
requireActiveMemberRequest(_address)
requireMPCThresholdReached(_address)
{
// Voting can only happen when the vote is still open (not successful)
require(votes[_address].success == false,
"Voting must not be successful when voteForAirlineRegistration is called"
);
// Only increase the votes counter if the calling airline gives a positive vote
if(_vote == true) {
votes[_address].votes = votes[_address].votes.add(1);
}
// To avoid double voting set hasVoted to true.
votes[_address].hasVoted[msg.sender] = true;
emit VoteCounted(msg.sender, _address, _vote);
if(votes[_address].votes >= votes[_address].threshold) {
// Vote was successful
votes[_address].success = true;
emit VotingSuccessful(_address, votes[_address].threshold, votes[_address].votes);
airlines[_address].isRegistered = true;
registeredAirlinesCount = registeredAirlinesCount.add(1);
emit AirlineRegistered(_address, true);
registrationQueue = registrationQueue.sub(1);
emit AirlineRemovedFromRegistrationQueue(_address);
}
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(
string _name,
address _address,
address _invitedBy
)
external
requireAuthorizedCaller(msg.sender)
requireAirlineIsRegistered(_invitedBy)
requireAirlineIsFunded(_invitedBy)
{
// Ensure that the airline was not yet registered.
require(airlines[_address].wallet == address(0), "Airline must not be registered");
// Increase the registered airlines counter by 1.
allAirlinesCount = allAirlinesCount.add(1);
emit AirlineAvailable(_address);
// If less than 5 airlines are registered, register the airline without voting.
if (registeredAirlinesCount < MPC_THRESHOLD) {
airlines[_address] = Airline({
name:_name,
wallet:_address,
isRegistered:true,
isFunded:false
});
registeredAirlinesCount = registeredAirlinesCount.add(1);
emit AirlineRegistered(_address, true);
// Add artificial voting result
votes[_address] = Vote({
memberRequest:_address,
votes:1,
success:true,
mpcRequired:false,
memberCount:registeredAirlinesCount,
threshold:1
});
votes[_address].hasVoted[msg.sender] = true;
emit VoteCounted(msg.sender, _address, true);
emit VotingSuccessful(_address, 1, 1);
}
else {
// Add Airline to the registration Queue.
registrationQueue = registrationQueue.add(1);
emit AirlineInRegistrationQueue(_address);
// Vote
votes[_address] = Vote({
memberRequest:_address,
votes:1,
success:false,
mpcRequired:true,
memberCount:registeredAirlinesCount,
threshold:registeredAirlinesCount.div(2)
});
// The inviting Airline automatically votes for the invitee
votes[_address].hasVoted[_invitedBy] = true;
emit VoteCounted(msg.sender, _address, true);
}
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*/
function fund(
address _address
)
external
payable
requireIsOperational
requireAirlineIsRegistered(_address)
{
require(msg.value >= MIN_FUNDING_AMOUNT, "Not enough funding");
// Adjust funding and allow additional funding
uint256 _funding = funding[_address];
_funding = _funding.add(msg.value);
funding[_address] = _funding;
airlines[_address].isFunded = true;
fundedAirlinesCount = fundedAirlinesCount.add(1);
multiCalls.push(_address);
emit AirlineFunded(_address, airlines[_address].isFunded, msg.value);
}
/**
* @dev Buy insurance for a flight
*
*/
function buyInsurance(
address airline,
string flight,
uint256 timestamp,
bytes32 flightKey,
address sender
)
external
payable
{
// Ensure that the max price is not exceeded
require(msg.value <= MAX_INSURANCE_PRICE, "Data: Insurance amount must be <= MAX_INSURANCE_PRICE");
insurances[flightKey].customer = sender;
insurances[flightKey].flightKey = flightKey;
insurances[flightKey].value = msg.value;
insurances[flightKey].airline = airline;
insurances[flightKey].flight = flight;
insurances[flightKey].timestamp = timestamp;
emit InsurancePurchased(sender, flightKey, msg.value);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsuree(
address _airline,
string _flight,
uint256 _timestamp
)
external
{
bytes32 flightKey = getFlightKey(_airline, _flight, _timestamp);
require(flightLateAirline[flightKey], "Delay must be caused by the airline.");
// Calculate amount hat needs to be credited to the insuree
uint256 amount = insurances[flightKey].value;
require(amount > 0, "Insurance amount must be > 0");
amount = amount.mul(15).div(10);
emit InsureeCredited(insurances[flightKey].customer, flightKey, amount);
emit DebugAirlineFunds(_airline, funding[_airline]);
// remove amount from airlines funding
address airline = insurances[flightKey].airline;
require(funding[airline] >= amount, "Airline must have sufficient funds to credit insuree");
funding[airline] = funding[airline].sub(amount);
emit DebugFundingReduced(airline, amount, funding[airline]);
// credit the calculated amount
uint256 currentCredits = credits[insurances[flightKey].customer];
credits[insurances[flightKey].customer] = currentCredits.add(amount);
emit InsureeCredited(insurances[flightKey].customer, flightKey, amount);
// delete the insurance entry
delete insurances[flightKey];
delete flightLateAirline[flightKey];
emit InsuranceDeleted(flightKey);
}
/**
* @dev Returns the credits balance of msg.sender
*/
function checkBalance(address sender) external view returns (uint256){
return credits[sender];
}
function getInsuranceStatus(bytes32 flightKey) external view returns(bool) {
if (insurances[flightKey].customer != address(0)) {
return true;
}
return false;
}
/**
* @dev Transfers eligible payout funds to insuree
*/
function pay(
address sender
)
external
{
//require(credits[sender] > 0, "Insuree must have more than 0 credits in order to receive a payout");
// In a real scenario we would be required to also ensure that each airline has sufficient funding to serve
// all potential payouts. This is not part of the exercise.
// Transfer accrued credits to the owner.
uint256 amount = credits[sender];
credits[sender] = 0;
sender.transfer(amount);
}
function getFlightKey(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
}
|
Returns the number of airlines - registered and unregistered/
|
function getOverallAirlineCount()
external
view
returns(uint256)
{
return allAirlinesCount;
}
| 1,752,973
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import { BufferChainlink } from "@chainlink/contracts/src/v0.6/vendor/BufferChainlink.sol";
import { CBORChainlink } from "@chainlink/contracts/src/v0.6/vendor/CBORChainlink.sol";
library AtlanticMessageBuilderV1 {
uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase
using CBORChainlink for BufferChainlink.buffer;
struct CallbackMessage {
uint64 id;
uint capacity;
BufferChainlink.buffer buf;
}
/**
* @notice Initializes a Chainlink request
* @dev Sets the ID, callback address, and callback function signature on the request
* @param self The uninitialized request
* @param _id The Job Specification ID
* @return The initialized request
*/
function initialize(
CallbackMessage memory self,
uint64 _id,
uint _capacity
) internal pure returns (AtlanticMessageBuilderV1.CallbackMessage memory) {
BufferChainlink.init(self.buf, defaultBufferSize);
self.id = _id;
self.capacity = _capacity;
// self.callbackFunctionId = _callbackFunction;
return self;
}
/**
* @notice Sets the data for the buffer without encoding CBOR on-chain
* @dev CBOR can be closed with curly-brackets {} or they can be left off
* @param self The initialized request
* @param _data The CBOR data
*/
function setBuffer(CallbackMessage memory self, bytes memory _data)
internal pure
{
BufferChainlink.init(self.buf, _data.length);
BufferChainlink.append(self.buf, _data);
}
/**
* @notice Adds a string value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The string value to add
*/
function add(CallbackMessage memory self, string memory _key, string memory _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeString(_value);
}
/**
* @notice Adds a bytes value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The bytes value to add
*/
function addBytes(CallbackMessage memory self, string memory _key, bytes memory _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeBytes(_value);
}
/**
* @notice Adds a int256 value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The int256 value to add
*/
function addInt(CallbackMessage memory self, string memory _key, int256 _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeInt(_value);
}
/**
* @notice Adds a uint256 value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The uint256 value to add
*/
function addUint(CallbackMessage memory self, string memory _key, uint256 _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeUInt(_value);
}
/**
* @notice Adds an array of strings to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _values The array of string values to add
*/
function addStringArray(CallbackMessage memory self, string memory _key, string[] memory _values)
internal pure
{
self.buf.encodeString(_key);
self.buf.startArray();
for (uint256 i = 0; i < _values.length; i++) {
self.buf.encodeString(_values[i]);
}
self.buf.endSequence();
}
}
|
Sets the data for the buffer without encoding CBOR on-chain CBOR can be closed with curly-brackets {} or they can be left off self The initialized request _data The CBOR data/
|
function setBuffer(CallbackMessage memory self, bytes memory _data)
internal pure
{
BufferChainlink.init(self.buf, _data.length);
BufferChainlink.append(self.buf, _data);
}
| 6,398,356
|
./full_match/42/0x11b5a39fFC76E8024290C063deD99209bc8af83a/sources/uniswap-solidity-example/flatten/Flattened.sol
|
Ropsten DAI address 0xad6d458402f60fd3bd25163575031acdce07538d
|
function test2(uint256 _amount) external onlyAdmin {
address multiDaiKovan = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;
address UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
daiToken = IERC20(0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa);
uint amountIn = 1056792676022063222;
daiToken.approve(address(0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa), amountIn);
require(daiToken.transferFrom(address(0x3694A96D70a66cCd6d04196688CcfB45a35ebdd9), address(this), amountIn ), 'transferFrom failed.');
uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);
address[] memory path = new address[](2);
path[0] = address(daiToken);
path[1] = uniswapRouter.WETH();
uniswapRouter.swapExactTokensForETH(amountIn, 0, path, msg.sender, block.timestamp);
}
| 9,566,283
|
./partial_match/1/0xF55CE9CcBAE17c48b01D49693B7c01516b21E17D/sources/KadenaMiningClub.sol
|
Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, non-reverting calls are assumed to be successful./
|
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
| 2,869,378
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.2;
pragma experimental ABIEncoderV2;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
import { SafeMath } from '@openzeppelin/contracts/math/SafeMath.sol';
import { IERC20 } from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import { SafeERC20 } from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import { IAction } from '../interfaces/IAction.sol';
import { ICurve } from '../interfaces/ICurve.sol';
import { IStakeDao } from '../interfaces/IStakeDao.sol';
import {ILendingPool} from "@aave/protocol-v2/contracts/interfaces/ILendingPool.sol";
ILendingPool constant lendingPool = ILendingPool(address(0x9FE532197ad76c5a68961439604C037EB79681F0)); // Kovan
import "hardhat/console.sol";
/**
* Error Codes
* O1: actions for the vault have not been initialized
* O2: cannot execute transaction, vault is in emergency state
* O3: cannot call setActions, actions have already been initialized
* O4: action being set is using an invalid address
* O5: action being set is a duplicated action
* O6: deposited underlying (msg.value) must be greater than 0
* O7: cannot accept underlying deposit, total sdToken controlled by the vault would exceed vault cap
* O8: unable to withdraw underlying, sdToken to withdraw would exceed or be equal to the current vault sdToken balance
* O9: unable to withdraw underlying, underlying fee transfer to fee recipient (feeRecipient) failed
* O10: unable to withdraw underlying, underlying withdrawal to user (msg.sender) failed
* O11: cannot close vault positions, vault is not in locked state (VaultState.Locked)
* O12: unable to rollover vault, length of allocation percentages (_allocationPercentages) passed is not equal to the initialized actions length
* O13: unable to rollover vault, vault is not in unlocked state (VaultState.Unlocked)
* O14: unable to rollover vault, the calculated percentage sum (sumPercentage) is greater than the base (BASE)
* O15: unable to rollover vault, the calculated percentage sum (sumPercentage) is not equal to the base (BASE)
* O16: withdraw reserve percentage must be less than 50% (5000)
* O17: cannot call emergencyPause, vault is already in emergency state
* O18: cannot call resumeFromPause, vault is not in emergency state
* O19: cannot receive underlying from any address other than the curve pool address (curvePool)
*/
/**
* @title OpynPerpVault
* @author Opyn Team
* @dev implementation of the Opyn Perp Vault contract that works with stakedao's underlying strategy.
* Note that this implementation is meant to only specifically work for the stakedao underlying strategy and is not
* a generalized contract. Stakedao's underlying strategy currently accepts curvePool LP tokens called curveLPToken from the
* underlying curve pool. This strategy allows users to convert their underlying into yield earning sdToken tokens
* and use the sdToken tokens as collateral to sell underlying call options on Opyn.
*/
contract OpynPerpVault is ERC20, ReentrancyGuard, Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
enum VaultState {
Emergency,
Locked,
Unlocked
}
/// @dev actions that build up this strategy (vault)
address[] public actions;
/// @dev address to which all fees are sent
address public feeRecipient;
/// @dev address of the underlying address which is earning yields
address public underlying;
/// @dev stakedao LP token address
address public sdTokenAddress;
uint256 public constant BASE = 10000; // 100%
/// @dev Cap for the vault. hardcoded at 1000 for initial release
uint256 public cap = 1000 ether;
/// @dev withdrawal fee percentage. 50 being 0.5%
uint256 public withdrawalFeePercentage = 50;
/// @dev how many percentage should be reserved in vault for withdraw. 1000 being 10%
uint256 public withdrawReserve = 0;
/// @dev curvePool for the corresponding stakedao strategy
ICurve public curvePool;
/// @dev the curve LP token address for the particular pool
IERC20 public curveLPToken;
/// @dev the stakedao strategy contract
IStakeDao stakedaoStrategy;
VaultState public state;
VaultState public stateBeforePause;
/*=====================
* Events *
*====================*/
event CapUpdated(uint256 newCap);
event Deposit(address account, uint256 amountDeposited, uint256 shareMinted);
event Rollover(uint256[] allocations);
event StateUpdated(VaultState state);
event FeeSent(uint256 amount, address feeRecipient);
event Withdraw(address account, uint256 amountWithdrawn, uint256 shareBurned);
/*=====================
* Modifiers *
*====================*/
/**
* @dev can only be called if actions are initialized
*/
function actionsInitialized() private view {
require(actions.length > 0, "O1");
}
/**
* @dev can only be executed if vault is not in emergency state
*/
function notEmergency() private view {
require(state != VaultState.Emergency, "O2");
}
/*=====================
* external function *
*====================*/
constructor (
address _underlying,
address _sdTokenAddress,
address _curvePoolAddress,
address _feeRecipient,
string memory _tokenName,
string memory _tokenSymbol
) ERC20(_tokenName, _tokenSymbol) {
underlying = _underlying;
sdTokenAddress = _sdTokenAddress;
stakedaoStrategy = IStakeDao(sdTokenAddress);
curveLPToken = stakedaoStrategy.token();
feeRecipient = _feeRecipient;
curvePool = ICurve(_curvePoolAddress);
state = VaultState.Unlocked;
}
function setActions(address[] memory _actions) external onlyOwner {
require(actions.length == 0, "O3");
// assign actions
for(uint256 i = 0 ; i < _actions.length; i++ ) {
// check all items before actions[i], does not equal to action[i]
require(_actions[i] != address(0), "O4");
for(uint256 j = 0; j < i; j++) {
require(_actions[i] != _actions[j], "O5");
}
actions.push(_actions[i]);
}
}
/**
* @notice allows owner to change the cap
*/
function setCap(uint256 _newCap) external onlyOwner {
cap = _newCap;
emit CapUpdated(_newCap);
}
/**
* @notice total sdToken controlled by this vault
*/
function totalStakedaoAsset() public view returns (uint256) {
uint256 debt = 0;
uint256 length = actions.length;
for (uint256 i = 0; i < length; i++) {
debt = debt.add(IAction(actions[i]).currentValue());
}
return _balance().add(debt);
}
/**
* total underlying value of the sdToken controlled by this vault
*/
function totalUnderlyingControlled() external view returns (uint256) {
// hard coded to 36 because crv LP token and sdToken are both 18 decimals.
return totalStakedaoAsset().mul(stakedaoStrategy.getPricePerFullShare()).mul(curvePool.get_virtual_price()).div(10**36);
}
/**
* @dev return how many sdToken you can get if you burn the number of shares, after charging the fee.
*/
function getWithdrawAmountByShares(uint256 _shares) external view returns (uint256) {
uint256 withdrawAmount = _getWithdrawAmountByShares(_shares);
return withdrawAmount.sub(_getWithdrawFee(withdrawAmount));
}
/**
* @notice Deposits underlying into the contract and mint vault shares.
* @dev deposit into the curvePool, then into stakedao, then mint the shares to depositor, and emit the deposit event
* @param amount amount of underlying to deposit
*@param minCrvLPToken minimum amount of curveLPToken to get out from adding liquidity.
*/
//added deposits function
// function deposit(uint256 amount ) external nonReentrant {
// notEmergency();
// actionsInitialized();
// require(amount > 0, 'O6');
// IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount);
// IERC20(underlying).safeApprove(address(lendingPool), amount);
// lendingPool.deposit(underlying, amount, address(this), 0);
// emit Deposit(msg.sender, msg.value, amount);
// }
function depositUnderlying(uint256 amount ) external nonReentrant {
notEmergency();
actionsInitialized();
require(amount > 0, 'O6');
IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount);
IERC20(underlying).safeApprove(address(lendingPool), amount);
lendingPool.deposit(underlying, amount, address(this), 0);
emit Deposit(msg.sender, msg.value, amount);
// notEmergency();
// actionsInitialized();
// require(amount > 0, 'O6');
// // the sdToken is already deposited into the contract at this point, need to substract it from total
// uint256[3] memory amounts;
// amounts[0] = 0; // not depositing any rebBTC
// amounts[1] = amount;
// amounts[2] = 0;
// // deposit underlying to curvePool
// IERC20 underlyingToken = IERC20(underlying);
// underlyingToken.safeTransferFrom(msg.sender, address(this), amount);
// underlyingToken.approve(address(curvePool), amount);
// curvePool.add_liquidity(amounts, minCrvLPToken);
// _depositToStakedaoAndMint();
}
/**
* @notice Deposits curve LP into the contract and mint vault shares.
* @dev deposit into stakedao, then mint the shares to depositor, and emit the deposit event
* @param amount amount of curveLP to deposit
*/
function depositCrvLP(uint256 amount) external nonReentrant {
notEmergency();
actionsInitialized();
require(amount > 0, 'O6');
// deposit underlying to curvePool
curveLPToken.safeTransferFrom(msg.sender, address(this), amount);
_depositToStakedaoAndMint();
}
/**
* @notice Withdraws underlying from vault using vault shares
* @dev burns shares, withdraws curveLPToken from stakdao, withdraws underlying from curvePool
* @param _share is the number of vault shares to be burned
*/
function withdrawUnderlying(uint256 _share, uint256 _minUnderlying) external nonReentrant {
// withdraw from curve
IERC20 underlyingToken = IERC20(underlying);
uint256 underlyingBalanceBefore = underlyingToken.balanceOf(address(this));
uint256 curveLPTokenBalance = _withdrawFromStakedao(_share);
curvePool.remove_liquidity_one_coin(curveLPTokenBalance, 1, _minUnderlying);
uint256 underlyingBalanceAfter = underlyingToken.balanceOf(address(this));
uint256 underlyingOwedToUser = underlyingBalanceAfter.sub(underlyingBalanceBefore);
// send underlying to user
underlyingToken.safeTransfer(msg.sender, underlyingOwedToUser);
emit Withdraw(msg.sender, underlyingOwedToUser, _share);
}
/**
* @notice Withdraws curveLPToken from stakedao
* @dev burns shares, withdraws curveLPToken from stakdao
* @param _share is the number of vault shares to be burned
*/
function withdrawCrvLp (uint256 _share) external nonReentrant {
uint256 curveLPTokenBalance = _withdrawFromStakedao(_share);
curveLPToken.safeTransfer(msg.sender, curveLPTokenBalance);
}
/**
* @notice anyone can call this to close out the previous round by calling "closePositions" on all actions.
* @dev iterrate through each action, close position and withdraw funds
*/
function closePositions() public {
actionsInitialized();
require(state == VaultState.Locked, "O11");
state = VaultState.Unlocked;
address cacheAddress = sdTokenAddress;
address[] memory cacheActions = actions;
for (uint256 i = 0; i < cacheActions.length; i = i + 1) {
// 1. close position. this should revert if any position is not ready to be closed.
IAction(cacheActions[i]).closePosition();
// 2. withdraw sdTokens from the action
uint256 actionBalance = IERC20(cacheAddress).balanceOf(cacheActions[i]);
if (actionBalance > 0)
IERC20(cacheAddress).safeTransferFrom(cacheActions[i], address(this), actionBalance);
}
emit StateUpdated(VaultState.Unlocked);
}
/**
* @notice can only be called when the vault is unlocked. It sets the state to locked and distributes funds to each action.
*/
function rollOver(uint256[] calldata _allocationPercentages) external onlyOwner nonReentrant {
actionsInitialized();
require(_allocationPercentages.length == actions.length, 'O12');
require(state == VaultState.Unlocked, "O13");
state = VaultState.Locked;
address cacheAddress = sdTokenAddress;
address[] memory cacheActions = actions;
uint256 cacheBase = BASE;
uint256 cacheTotalAsset = totalStakedaoAsset();
// keep track of total percentage to make sure we're summing up to 100%
uint256 sumPercentage = withdrawReserve;
for (uint256 i = 0; i < _allocationPercentages.length; i = i + 1) {
sumPercentage = sumPercentage.add(_allocationPercentages[i]);
require(sumPercentage <= cacheBase, 'O14');
uint256 newAmount = cacheTotalAsset.mul(_allocationPercentages[i]).div(cacheBase);
if (newAmount > 0) IERC20(cacheAddress).safeTransfer(cacheActions[i], newAmount);
IAction(cacheActions[i]).rolloverPosition();
}
require(sumPercentage == cacheBase, 'O15');
emit Rollover(_allocationPercentages);
emit StateUpdated(VaultState.Locked);
}
/**
* @dev set the vault withdrawal fee recipient
*/
function setWithdrawalFeeRecipient(address _newWithdrawalFeeRecipient) external onlyOwner {
feeRecipient = _newWithdrawalFeeRecipient;
}
/**
* @dev set the percentage that should be reserved in vault for withdraw
*/
function setWithdrawalFeePercentage(uint256 _newWithdrawalFeePercentage) external onlyOwner {
withdrawalFeePercentage = _newWithdrawalFeePercentage;
}
/**
* @dev set the percentage that should be reserved in vault for withdraw
*/
function setWithdrawReserve(uint256 _reserve) external onlyOwner {
require(_reserve < 5000, "O16");
withdrawReserve = _reserve;
}
/**
* @dev set the state to "Emergency", which disable all withdraw and deposit
*/
function emergencyPause() external onlyOwner {
require(state != VaultState.Emergency, "O17");
stateBeforePause = state;
state = VaultState.Emergency;
emit StateUpdated(VaultState.Emergency);
}
/**
* @dev set the state from "Emergency", which disable all withdraw and deposit
*/
function resumeFromPause() external onlyOwner {
require(state == VaultState.Emergency, "O18");
state = stateBeforePause;
emit StateUpdated(stateBeforePause);
}
/**
* @dev return how many shares you can get if you deposit {_amount} sdToken
* @param _amount amount of token depositing
*/
function getSharesByDepositAmount(uint256 _amount) external view returns (uint256) {
return _getSharesByDepositAmount(_amount, totalStakedaoAsset());
}
/*=====================
* Internal functions *
*====================*/
function _depositToStakedaoAndMint() internal {
// keep track of balance before
uint256 totalSdTokenBalanceBeforeDeposit = totalStakedaoAsset();
// deposit curveLPToken to stakedao
uint256 curveLPTokenToDeposit = curveLPToken.balanceOf(address(this));
curveLPToken.safeIncreaseAllowance(sdTokenAddress, curveLPTokenToDeposit);
stakedaoStrategy.deposit(curveLPTokenToDeposit);
// mint shares and emit event
uint256 totalSdTokenWithDepositedAmount = totalStakedaoAsset();
require(totalSdTokenWithDepositedAmount < cap, 'O7');
uint256 sdTokenDeposited = totalSdTokenWithDepositedAmount.sub(totalSdTokenBalanceBeforeDeposit);
uint256 share = _getSharesByDepositAmount(sdTokenDeposited, totalSdTokenBalanceBeforeDeposit);
emit Deposit(msg.sender, msg.value, share);
_mint(msg.sender, share);
}
function _withdrawFromStakedao(uint256 _share) internal returns (uint256) {
notEmergency();
actionsInitialized();
uint256 currentSdTokenBalance = _balance();
uint256 sdTokenToShareOfRecipient = _getWithdrawAmountByShares(_share);
uint256 fee = _getWithdrawFee(sdTokenToShareOfRecipient);
uint256 sdTokenToWithdraw = sdTokenToShareOfRecipient.sub(fee);
require(sdTokenToWithdraw <= currentSdTokenBalance, 'O8');
// burn shares
_burn(msg.sender, _share);
// withdraw from stakedao
stakedaoStrategy.withdraw(sdTokenToWithdraw);
// transfer fee to recipient
IERC20 stakedaoToken = IERC20(sdTokenAddress);
stakedaoToken.safeTransfer(feeRecipient, fee);
emit FeeSent(fee, feeRecipient);
return curveLPToken.balanceOf(address(this));
}
/**
* @dev returns remaining sdToken balance in the vault.
*/
function _balance() internal view returns (uint256) {
return IERC20(sdTokenAddress).balanceOf(address(this));
}
/**
* @dev return how many shares you can get if you deposit {_amount} sdToken
* @param _amount amount of token depositing
* @param _totalAssetAmount amont of sdToken already in the pool before deposit
*/
function _getSharesByDepositAmount(uint256 _amount, uint256 _totalAssetAmount) internal view returns (uint256) {
uint256 shareSupply = totalSupply();
// share amount
return shareSupply == 0 ? _amount : _amount.mul(shareSupply).div(_totalAssetAmount);
}
/**
* @dev return how many sdToken you can get if you burn the number of shares
*/
function _getWithdrawAmountByShares(uint256 _share) internal view returns (uint256) {
// withdrawal amount
return _share.mul(totalStakedaoAsset()).div(totalSupply());
}
/**
* @dev get amount of fee charged based on total amount of wunderlying withdrawing.
*/
function _getWithdrawFee(uint256 _withdrawAmount) internal view returns (uint256) {
return _withdrawAmount.mul(withdrawalFeePercentage).div(BASE);
}
}
|
can only be called when the vault is unlocked. It sets the state to locked and distributes funds to each action./ keep track of total percentage to make sure we're summing up to 100%
|
function rollOver(uint256[] calldata _allocationPercentages) external onlyOwner nonReentrant {
actionsInitialized();
require(_allocationPercentages.length == actions.length, 'O12');
require(state == VaultState.Unlocked, "O13");
state = VaultState.Locked;
address cacheAddress = sdTokenAddress;
address[] memory cacheActions = actions;
uint256 cacheBase = BASE;
uint256 cacheTotalAsset = totalStakedaoAsset();
uint256 sumPercentage = withdrawReserve;
for (uint256 i = 0; i < _allocationPercentages.length; i = i + 1) {
sumPercentage = sumPercentage.add(_allocationPercentages[i]);
require(sumPercentage <= cacheBase, 'O14');
uint256 newAmount = cacheTotalAsset.mul(_allocationPercentages[i]).div(cacheBase);
if (newAmount > 0) IERC20(cacheAddress).safeTransfer(cacheActions[i], newAmount);
IAction(cacheActions[i]).rolloverPosition();
}
require(sumPercentage == cacheBase, 'O15');
emit Rollover(_allocationPercentages);
emit StateUpdated(VaultState.Locked);
}
| 1,843,982
|
./full_match/5/0xEBE0506b0481f873b12C0BCF423f6ad241C40ACc/sources/home/felipenovaesrocha/Projects/1Hive/staking/packages/protocol/contracts/Staking.sol
|
Check if `_sender` can unlock `@tokenAmount(self.token(): address, _amount)` from `_user`'s lock managed by `_lockManager` _sender Address that would try to unlock tokens _user Owner of lock _lockManager Lock manager _amount Amount of locked tokens to unlock. If zero, the full locked amount. return Whether sender is allowed to unlock tokens from the given lock/
|
function canUnlock(address _sender, address _user, address _lockManager, uint256 _amount) external view returns (bool) {
return _canUnlockUnsafe(_sender, _user, _lockManager, _amount);
}
| 11,619,253
|
/**
*Submitted for verification at Etherscan.io on 2021-03-13
*/
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
/**
* @title Bird's BController Interface
*/
contract BControllerInterface {
/// @notice Indicator that this is a BController contract (for inspection)
bool public constant isBController = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata bTokens) external returns (uint[] memory);
function exitMarket(address bToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address bToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address bToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address bToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address bToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address bToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address bToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(address bToken, address payer, address borrower, uint repayAmount) external returns (uint);
function repayBorrowVerify(address bToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external;
function liquidateBorrowAllowed(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint);
function liquidateBorrowVerify(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external;
function seizeAllowed(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint);
function seizeVerify(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external;
function transferAllowed(address bToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address bToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(address bTokenBorrowed, address bTokenCollateral, uint repayAmount) external view returns (uint, uint);
}
/**
* @title Bird's InterestRateModel Interface
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @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);
}
/**
* @title Bird's BToken Storage
*/
contract BTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-bToken operations
*/
BControllerInterface public bController;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first BTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice 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;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
/**
* @title Bird's BToken Interface
*/
contract BTokenInterface is BTokenStorage {
/**
* @notice Indicator that this is a BToken contract (for inspection)
*/
bool public constant isBToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterestToken(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event MintToken(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event RedeemToken(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event BorrowToken(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrowToken(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrowToken(address liquidator, address borrower, uint repayAmount, address bTokenCollateral, 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 bController is changed
*/
event NewBController(BControllerInterface oldBController, BControllerInterface newBController);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketTokenInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewTokenReserveFactor(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);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setBController(BControllerInterface newBController) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
/**
* @title Bird's BErc20 Storage
*/
contract BErc20Storage {
/**
* @notice Underlying asset for this BToken
*/
address public underlying;
}
/**
* @title Bird's BErc20 Interface
*/
contract BErc20Interface is BErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
/**
* @title Bird's BDelegation Storage
*/
contract BDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
/**
* @title Bird's BDelegator Interface
*/
contract BDelegatorInterface is BDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
/**
* @title Bird's BDelegate Interface
*/
contract BDelegateInterface is BDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
contract BControllerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BCONTROLLER_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,
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,
BCONTROLLER_REJECTION,
BCONTROLLER_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_BCONTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_BCONTROLLER_REJECTION,
LIQUIDATE_BCONTROLLER_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_BCONTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_BCONTROLLER_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_BCONTROLLER_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_BCONTROLLER_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_BCONTROLLER_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_BCONTROLLER_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);
}
}
/**
* @title Careful Math
* @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);
}
}
/**
* @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 Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function 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)});
}
}
/**
* @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 The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @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 returns (bool success);
/**
* @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 returns (bool success);
/**
* @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 returns (bool success);
/**
* @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 view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @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 The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `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
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @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
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/**
* @title Bird's BToken Contract
* @notice Abstract base for BTokens
*/
contract BToken is BTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param bController_ The address of the BController
* @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 initialize(BControllerInterface bController_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the bController
uint err = _setBController(bController_);
require(err == uint(Error.NO_ERROR), "setting bController failed");
// Initialize block number and borrow index (block number mocks depend on bController 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 interest rate model 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;
}
/**
* @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 = bController.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.TRANSFER_BCONTROLLER_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 scrTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, scrTokensNew) = 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] = scrTokensNew;
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);
bController.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 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 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 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 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 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 returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by bController 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 view returns (uint, uint, uint, uint) {
uint bTokenBalance = 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), bTokenBalance, 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 bToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this bToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external 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 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 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 view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal 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 nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the BToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the BToken
* @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 bToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @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 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 is absurdly 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 calculate 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;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(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, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, 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 = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterestToken(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives bTokens 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 bTokens 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 = bController.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.MINT_BCONTROLLER_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 bToken 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 bToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of bTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of bTokens 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_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit MintToken(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
bController.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems bTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of bTokens 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 bTokens 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 bTokens
* @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 bTokens 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 bTokens 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 bTokens (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, "one of redeemTokensIn or redeemAmountIn must be 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 = bController.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.REDEEM_BCONTROLLER_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);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The bToken must handle variations between ERC-20 and ETH underlying.
* On success, the bToken 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 RedeemToken(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
bController.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);
}
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 = bController.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.BORROW_BCONTROLLER_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 bToken must handle variations between ERC-20 and ETH underlying.
* On success, the bToken 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 BorrowToken(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
bController.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 = bController.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.REPAY_BORROW_BCONTROLLER_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 (repayAmount == uint(-1)) {
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 bToken must handle variations between ERC-20 and ETH underlying.
* On success, the bToken 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, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_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 RepayBorrowToken event */
emit RepayBorrowToken(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
bController.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 bToken to be liquidated
* @param bTokenCollateral 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, BTokenInterface bTokenCollateral) 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 = bTokenCollateral.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, bTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this bToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param bTokenCollateral 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, BTokenInterface bTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = bController.liquidateBorrowAllowed(address(this), address(bTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.LIQUIDATE_BCONTROLLER_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 bTokenCollateral market's block number equals current block number */
if (bTokenCollateral.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) = bController.liquidateCalculateSeizeTokens(address(this), address(bTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_BCONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(bTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(bTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = bTokenCollateral.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 LiquidateBorrowToken event */
emit LiquidateBorrowToken(liquidator, borrower, actualRepayAmount, address(bTokenCollateral), seizeTokens);
/* We call the defense hook */
bController.liquidateBorrowVerify(address(this), address(bTokenCollateral), 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 bToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed bToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of bTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external 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 BToken.
* Its absolutely critical to use msg.sender as the seizer bToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed bToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of bTokens 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 = bController.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_BCONTROLLER_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 */
bController.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 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 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 bController for the market
* @dev Admin function to set a new bController
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setBController(BControllerInterface newBController) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_BCONTROLLER_OWNER_CHECK);
}
BControllerInterface oldBController = bController;
// Ensure invoke bController.isBController() returns true
require(newBController.isBController(), "marker method returned false");
// Set market's bController to newBController
bController = newBController;
// Emit NewBController(oldBController, newBController)
emit NewBController(oldBController, newBController);
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 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);
}
/**
* @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 NewTokenReserveFactor(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 bToken must handle variations between ERC-20 and ETH underlying.
* On success, the bToken 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, "add reserves unexpected 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 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, "reduce reserves unexpected 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(InterestRateModel newInterestRateModel) public 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(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel 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(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketTokenInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketTokenInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** 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 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 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;
/*** 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
}
}
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a bToken asset
* @param bToken The bToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(BToken bToken) external view returns (uint);
}
/**
* @title Bird's BErc20 Contract
* @notice BTokens which wrap an EIP-20 underlying
*/
contract BErc20 is BToken, BErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param bController_ The address of the BController
* @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 initialize(address underlying_,
BControllerInterface bController_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// BToken initialize does the bulk of the work
super.initialize(bController_, 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 bTokens 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 returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems bTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of bTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems bTokens 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 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 returns (uint) {
return borrowInternal(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 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 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 bToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param bTokenCollateral 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, BTokenInterface bTokenCollateral) external returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, bTokenCollateral);
return err;
}
/**
* @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 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 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 returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).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 {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
}
contract SimplePriceOracle is PriceOracle {
address public admin;
address public pendingAdmin;
mapping(string => address) birdTokens;
mapping(address => uint256) prices;
event PricePosted(
string symbol,
address asset,
uint256 previousPriceMantissa,
uint256 requestedPriceMantissa,
uint256 newPriceMantissa
);
constructor() public {
admin = msg.sender;
}
function initialiseTokens(string[] memory symbols, address[] memory bTokens)
public
{
// Check caller = admin
require(msg.sender == admin);
require(symbols.length == bTokens.length);
// Associate symbols with tokens
for (uint256 i = 0; i < symbols.length; i++) {
birdTokens[symbols[i]] = bTokens[i];
}
}
function postPrices(string[] memory symbols, uint256[] memory priceMantissa)
public
{
// Check caller = admin
require(msg.sender == admin);
require(symbols.length == priceMantissa.length);
// Post prices
for (uint256 i = 0; i < symbols.length; i++) {
if (compareStrings(symbols[i], "ETH")) {
setDirectPrice(
address(birdTokens[symbols[i]]),
priceMantissa[i]
);
} else {
setUnderlyingPrice(
BToken(birdTokens[symbols[i]]),
priceMantissa[i]
);
}
}
}
function getUnderlyingPrice(BToken bToken) public view returns (uint256) {
if (compareStrings(bToken.symbol(), "bETH")) {
return prices[address(bToken)];
} else {
return prices[address(BErc20(address(bToken)).underlying())];
}
}
function setUnderlyingPrice(BToken bToken, uint256 underlyingPriceMantissa)
public
{
// Check caller = admin
require(msg.sender == admin);
address asset = address(BErc20(address(bToken)).underlying());
emit PricePosted(
bToken.symbol(),
address(bToken),
prices[asset],
underlyingPriceMantissa,
underlyingPriceMantissa
);
prices[asset] = underlyingPriceMantissa;
}
function setDirectPrice(address asset, uint256 price) public {
// Check caller = admin
require(msg.sender == admin);
emit PricePosted("bETH", 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 (uint256) {
return prices[asset];
}
function compareStrings(string memory a, string memory b)
internal
pure
returns (bool)
{
return (keccak256(abi.encodePacked((a))) ==
keccak256(abi.encodePacked((b))));
}
function _setPendingAdmin(address newPendingAdmin) public {
// Check caller = admin
require(msg.sender == admin);
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
}
function _acceptAdmin() public {
// Check caller is pendingAdmin and pendingAdmin โ address(0)
require(msg.sender == pendingAdmin && msg.sender != address(0));
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
}
}
|
Check caller = admin Associate symbols with tokens
|
function initialiseTokens(string[] memory symbols, address[] memory bTokens)
public
{
require(msg.sender == admin);
require(symbols.length == bTokens.length);
for (uint256 i = 0; i < symbols.length; i++) {
birdTokens[symbols[i]] = bTokens[i];
}
}
| 2,247,792
|
pragma solidity ^0.5.0;
import "../../lib/date/BokkyPooBahsDateTimeLibrary.sol";
/**
* @title DateTime
* @dev Library with convenience functions for working with datetime and timestamp values.
* Wraps calls to BokkyPooBahsDateTimeLibrary library (https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary).
*/
library DateTime {
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
/// Code based on https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
function isValidYearAndMonth(uint year, uint month) internal pure returns (bool) {
return (year >= 1970 && month > 0 && month <= 12);
}
/// Code based on https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
function isValidTime(uint hour, uint minute, uint second) internal pure returns (bool) {
return (hour < 24 && minute < 60 && second < 60);
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool) {
return BokkyPooBahsDateTimeLibrary.isValidDateTime(year, month, day, hour, minute, second);
}
// note that no overflow check is performed. Make sure to call "isValidTime" prior to using this function
function totalSeconds(uint hour, uint minute, uint second) internal pure returns (uint) {
return
hour * SECONDS_PER_HOUR +
minute * SECONDS_PER_MINUTE +
second;
}
// BokkyPooBahsDateTimeLibrary call does check for overflow
function add(uint timestamp, uint _seconds) internal pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addSeconds(timestamp, _seconds);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, month, day);
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.timestampFromDateTime(year, month, day, hour, minute, second);
}
// returns the Min between the provided day and total days in the given month
function constrainToDaysInMonth(uint year, uint month, uint day) internal pure returns (uint adjustedPaymentDay) {
adjustedPaymentDay = day;
if (adjustedPaymentDay > 28) {
uint daysInMonth = BokkyPooBahsDateTimeLibrary._getDaysInMonth(year, month);
if (adjustedPaymentDay > daysInMonth) {
adjustedPaymentDay = daysInMonth;
}
}
}
}
|
Code based on https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
|
function isValidYearAndMonth(uint year, uint month) internal pure returns (bool) {
return (year >= 1970 && month > 0 && month <= 12);
}
| 12,912,289
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../lendingpool/DataTypes.sol";
import "../credit/CreditSystem.sol";
import "./KyokoMath.sol";
import "./PercentageMath.sol";
import "./ReserveLogic.sol";
import "./GenericLogic.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
/**
* @title ReserveLogic library
* @notice Implements functions to validate the different actions of the protocol
*/
library ValidationLogic {
using ReserveLogic for DataTypes.ReserveData;
using SafeMathUpgradeable for uint256;
using KyokoMath for uint256;
using PercentageMath for uint256;
uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000;
uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95%
/**
* @dev Validates a deposit action
* @param reserve The reserve object on which the user is depositing
* @param amount The amount to be deposited
*/
function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view {
bool isActive = reserve.getActive();
require(amount != 0, "VL_INVALID_AMOUNT");
require(isActive, "VL_NO_ACTIVE_RESERVE");
}
/**
* @dev Validates a withdraw action
* @param reserveAddress The address of the reserve
* @param amount The amount to be withdrawn
* @param userBalance The balance of the user
* @param reservesData The reserves state
*/
function validateWithdraw(
address reserveAddress,
uint256 amount,
uint256 userBalance,
mapping(address => DataTypes.ReserveData) storage reservesData
) external view {
require(amount != 0, "VL_INVALID_AMOUNT");
require(amount <= userBalance, "VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE");
bool isActive = reservesData[reserveAddress].getActive();
require(isActive, "VL_NO_ACTIVE_RESERVE");
}
struct ValidateBorrowLocalVars {
uint256 userBorrowBalance;
uint256 availableLiquidity;
bool isActive;
}
/**
* @dev Validates a borrow action
* @param availableBorrowsInWEI available borrows in WEI
* @param reserve The reserve state from which the user is borrowing
* @param amount The amount to be borrowed
*/
function validateBorrow(
uint256 availableBorrowsInWEI,
DataTypes.ReserveData storage reserve,
uint256 amount
) external view {
ValidateBorrowLocalVars memory vars;
require(availableBorrowsInWEI > 0, "available credit line not enough");
uint256 decimals_ = 1 ether;
uint256 borrowsAmountInWEI = amount.div(10**reserve.decimals).mul(uint256(decimals_));
require(borrowsAmountInWEI <= availableBorrowsInWEI, "borrows exceed credit line");
vars.isActive = reserve.getActive();
require(vars.isActive, "VL_NO_ACTIVE_RESERVE");
require(amount > 0, "VL_INVALID_AMOUNT");
}
/**
* @dev Validates a repay action
* @param reserve The reserve state from which the user is repaying
* @param amountSent The amount sent for the repayment. Can be an actual value or type(uint256).min
* @param onBehalfOf The address of the user msg.sender is repaying for
* @param variableDebt The borrow balance of the user
*/
function validateRepay(
DataTypes.ReserveData storage reserve,
uint256 amountSent,
address onBehalfOf,
uint256 variableDebt
) external view {
bool isActive = reserve.getActive();
require(isActive, "VL_NO_ACTIVE_RESERVE");
require(amountSent > 0, "VL_INVALID_AMOUNT");
require(variableDebt > 0, "VL_NO_DEBT_OF_SELECTED_TYPE");
require(
amountSent != type(uint256).max || msg.sender == onBehalfOf,
"VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../lendingpool/DataTypes.sol";
import "../interfaces/IVariableDebtToken.sol";
import "../interfaces/IReserveInterestRateStrategy.sol";
import "./MathUtils.sol";
import "./KyokoMath.sol";
import "./PercentageMath.sol";
import "../interfaces/IKToken.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
/**
* @title ReserveLogic library
* @notice Implements the logic to update the reserves state
*/
library ReserveLogic {
using SafeMathUpgradeable for uint256;
using KyokoMath for uint256;
using PercentageMath for uint256;
/**
* @dev Emitted when the state of a reserve is updated
* @param asset The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed asset,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
uint256 constant MAX_VALID_RESERVE_FACTOR = 65535;
using ReserveLogic for DataTypes.ReserveData;
/**
* @dev Initializes a reserve
* @param reserve The reserve object
* @param kTokenAddress The address of the overlying ktoken contract
* @param variableDebtTokenAddress The address of the variable debt token
* @param interestRateStrategyAddress The address of the interest rate strategy contract
**/
function init(
DataTypes.ReserveData storage reserve,
address kTokenAddress,
address variableDebtTokenAddress,
address interestRateStrategyAddress
) external {
require(reserve.kTokenAddress == address(0), "the reserve already initialized");
reserve.isActive = true;
reserve.liquidityIndex = uint128(KyokoMath.ray());
reserve.variableBorrowIndex = uint128(KyokoMath.ray());
reserve.kTokenAddress = kTokenAddress;
reserve.variableDebtTokenAddress = variableDebtTokenAddress;
reserve.interestRateStrategyAddress = interestRateStrategyAddress;
}
/**
* @dev Updates the liquidity cumulative index and the variable borrow index.
* @param reserve the reserve object
**/
function updateState(DataTypes.ReserveData storage reserve) internal {
uint256 scaledVariableDebt =
IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply();
uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;
uint256 previousLiquidityIndex = reserve.liquidityIndex;
uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;
(uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) =
_updateIndexes(
reserve,
scaledVariableDebt,
previousLiquidityIndex,
previousVariableBorrowIndex,
lastUpdatedTimestamp
);
_mintToTreasury(
reserve,
scaledVariableDebt,
previousVariableBorrowIndex,
newLiquidityIndex,
newVariableBorrowIndex
);
}
/**
* @dev Updates the reserve indexes and the timestamp of the update
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The scaled variable debt
* @param liquidityIndex The last stored liquidity index
* @param variableBorrowIndex The last stored variable borrow index
* @param timestamp The last operate time of reserve
**/
function _updateIndexes(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 timestamp
) internal returns (uint256, uint256) {
uint256 currentLiquidityRate = reserve.currentLiquidityRate;
uint256 newLiquidityIndex = liquidityIndex;
uint256 newVariableBorrowIndex = variableBorrowIndex;
//only cumulating if there is any income being produced
if (currentLiquidityRate > 0) {
// 1 + ratePerSecond * (delta_t / seconds in a year)
uint256 cumulatedLiquidityInterest =
MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp);
newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex);
require(newLiquidityIndex <= type(uint128).max, "RL_LIQUIDITY_INDEX_OVERFLOW");
reserve.liquidityIndex = uint128(newLiquidityIndex);
//we need to ensure that there is actual variable debt before accumulating
if (scaledVariableDebt != 0) {
uint256 cumulatedVariableBorrowInterest =
MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp);
newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex);
require(
newVariableBorrowIndex <= type(uint128).max,
"RL_VARIABLE_BORROW_INDEX_OVERFLOW"
);
reserve.variableBorrowIndex = uint128(newVariableBorrowIndex);
}
}
//solium-disable-next-line
reserve.lastUpdateTimestamp = uint40(block.timestamp);
return (newLiquidityIndex, newVariableBorrowIndex);
}
struct MintToTreasuryLocalVars {
uint256 currentVariableDebt;
uint256 previousVariableDebt;
uint256 totalDebtAccrued;
uint256 amountToMint;
uint16 reserveFactor;
uint40 stableSupplyUpdatedTimestamp;
}
/**
* @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the
* specific asset.
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The current scaled total variable debt
* @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest
* @param newLiquidityIndex The new liquidity index
* @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest
**/
function _mintToTreasury(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 previousVariableBorrowIndex,
uint256 newLiquidityIndex,
uint256 newVariableBorrowIndex
) internal {
MintToTreasuryLocalVars memory vars;
vars.reserveFactor = getReserveFactor(reserve);
if (vars.reserveFactor == 0) {
return;
}
//calculate the last principal variable debt
vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex);
//calculate the new total supply after accumulation of the index
vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex);
//debt accrued is the sum of the current debt minus the sum of the debt at the last update
vars.totalDebtAccrued = vars
.currentVariableDebt
.sub(vars.previousVariableDebt);
vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor);
if (vars.amountToMint != 0) {
IKToken(reserve.kTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex);
}
}
struct UpdateInterestRatesLocalVars {
uint256 availableLiquidity;
uint256 newLiquidityRate;
uint256 newVariableRate;
uint256 totalVariableDebt;
}
/**
* @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate
* @param reserve The address of the reserve to be updated
* @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action
* @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow)
**/
function updateInterestRates(
DataTypes.ReserveData storage reserve,
address reserveAddress,
address kTokenAddress,
uint256 liquidityAdded,
uint256 liquidityTaken
) internal {
UpdateInterestRatesLocalVars memory vars;
//calculates the total variable debt locally using the scaled total supply instead
//of totalSupply(), as it's noticeably cheaper. Also, the index has been
//updated by the previous updateState() call
vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress)
.scaledTotalSupply()
.rayMul(reserve.variableBorrowIndex);
(
vars.newLiquidityRate,
vars.newVariableRate
) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
reserveAddress,
kTokenAddress,
liquidityAdded,
liquidityTaken,
vars.totalVariableDebt,
getReserveFactor(reserve)
);
require(vars.newLiquidityRate <= type(uint128).max, "RL_LIQUIDITY_RATE_OVERFLOW");
require(vars.newVariableRate <= type(uint128).max, "RL_VARIABLE_BORROW_RATE_OVERFLOW");
reserve.currentLiquidityRate = uint128(vars.newLiquidityRate);
reserve.currentVariableBorrowRate = uint128(vars.newVariableRate);
emit ReserveDataUpdated(
reserveAddress,
vars.newLiquidityRate,
vars.newVariableRate,
reserve.liquidityIndex,
reserve.variableBorrowIndex
);
}
/**
* @dev Returns the ongoing normalized variable debt for the reserve
* A value of 1e27 means there is no debt. As time passes, the income is accrued
* A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated
* @param reserve The reserve object
* @return The normalized variable debt. expressed in ray
**/
function getNormalizedDebt(DataTypes.ReserveData storage reserve)
internal
view
returns (uint256)
{
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.variableBorrowIndex;
}
uint256 cumulated =
MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(
reserve.variableBorrowIndex
);
return cumulated;
}
/**
* @dev Returns the ongoing normalized income for the reserve
* A value of 1e27 means there is no income. As time passes, the income is accrued
* A value of 2*1e27 means for each unit of asset one unit of income has been accrued
* @param reserve The reserve object
* @return the normalized income. expressed in ray
**/
function getNormalizedIncome(DataTypes.ReserveData storage reserve)
internal
view
returns (uint256)
{
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.liquidityIndex;
}
uint256 cumulated =
MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(
reserve.liquidityIndex
);
return cumulated;
}
/**
* @dev Sets the active state of the reserve
* @param self The reserve configuration
* @param active The active state
**/
function setActive(DataTypes.ReserveData storage self, bool active) internal {
self.isActive = active;
}
/**
* @dev Gets the active state of the reserve
* @param self The reserve configuration
* @return The active state
**/
function getActive(DataTypes.ReserveData storage self) internal view returns (bool) {
return self.isActive;
}
/**
* @dev Sets the reserve factor of the reserve
* @param self The reserve configuration
* @param reserveFactor The reserve factor
**/
function setReserveFactor(DataTypes.ReserveData storage self, uint16 reserveFactor)
internal
{
require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, "RC_INVALID_RESERVE_FACTOR");
self.factor = reserveFactor;
}
/**
* @dev Gets the reserve factor of the reserve
* @param self The reserve configuration
* @return The reserve factor
**/
function getReserveFactor(DataTypes.ReserveData storage self)
internal
view
returns (uint16)
{
return self.factor;
}
/**
* @dev Gets the decimals of the underlying asset of the reserve
* @param self The reserve configuration
* @return The decimals of the asset
**/
function getDecimal(DataTypes.ReserveData storage self)
internal
view
returns (uint8)
{
return self.decimals;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @title PercentageMath library
* @notice Provides functions to perform percentage calculations
* @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR
* @dev Operations are rounded half up
**/
library PercentageMath {
uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals
uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;
/**
* @dev Executes a percentage multiplication
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The percentage of value
**/
function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {
if (value == 0 || percentage == 0) {
return 0;
}
require(
value <= (type(uint256).max - HALF_PERCENT) / percentage,
"MATH_MULTIPLICATION_OVERFLOW"
);
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;
}
/**
* @dev Executes a percentage division
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The value divided the percentage
**/
function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) {
require(percentage != 0, "MATH_DIVISION_BY_ZERO");
uint256 halfPercentage = percentage / 2;
require(
value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR,
"MATH_MULTIPLICATION_OVERFLOW"
);
return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "./KyokoMath.sol";
library MathUtils {
using SafeMathUpgradeable for uint256;
using KyokoMath for uint256;
/// @dev Ignoring leap years
uint256 internal constant SECONDS_PER_YEAR = 365 days;
/**
* @dev Function to calculate the interest accumulated using a linear interest rate formula
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solium-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp));
return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(KyokoMath.ray());
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(
uint256 rate,
uint40 lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solium-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp));
if (exp == 0) {
return KyokoMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = rate / SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return KyokoMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
/**
* @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp
* @param rate The interest rate (in ray)
* @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated
**/
function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
library KyokoMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfWAD) / b, "MATH_MULTIPLICATION_OVERFLOW");
return (a * b + halfWAD) / WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "MATH_DIVISION_BY_ZERO");
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD, "MATH_MULTIPLICATION_OVERFLOW");
return (a * WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfRAY) / b, "MATH_MULTIPLICATION_OVERFLOW");
return (a * b + halfRAY) / RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "MATH_DIVISION_BY_ZERO");
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, "MATH_MULTIPLICATION_OVERFLOW");
return (a * RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, "MATH_ADDITION_OVERFLOW");
return result / WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a, "MATH_MULTIPLICATION_OVERFLOW");
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../lendingpool/DataTypes.sol";
import "./KyokoMath.sol";
import "./PercentageMath.sol";
import "./ReserveLogic.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
library GenericLogic {
using ReserveLogic for DataTypes.ReserveData;
using SafeMathUpgradeable for uint256;
using KyokoMath for uint256;
using PercentageMath for uint256;
struct CalculateUserAccountDataVars {
uint256 decimals;
uint256 tokenUnit;
uint256 compoundedBorrowBalance;
uint256 totalDebtInWEI;
uint256 i;
address currentReserveAddress;
}
/**
* @dev Calculates the user total Debt in WEI across the reserves.
* @param user The address of the user
* @param reservesData Data of all the reserves
* @param reserves The list of the available reserves
* @param reservesCount the count of reserves
* @return The total debt of the user in WEI
**/
function calculateUserAccountData(
address user,
mapping(address => DataTypes.ReserveData) storage reservesData,
mapping(uint256 => address) storage reserves,
uint256 reservesCount
)
internal
view
returns (uint256)
{
CalculateUserAccountDataVars memory vars;
for (vars.i = 0; vars.i < reservesCount; vars.i++) {
vars.currentReserveAddress = reserves[vars.i];
DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress];
vars.decimals = currentReserve.getDecimal();
uint256 decimals_ = 1 ether;
vars.tokenUnit = uint256(decimals_).div(10**vars.decimals);
uint256 currentReserveBorrows = IERC20Upgradeable(currentReserve.variableDebtTokenAddress).balanceOf(user);
if (currentReserveBorrows > 0) {
vars.totalDebtInWEI = vars.totalDebtInWEI.add(
uint256(1).mul(currentReserveBorrows).mul(vars.tokenUnit)
);
}
}
return vars.totalDebtInWEI;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
library DataTypes {
struct ReserveData {
//this current state of the asset;
bool isActive;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the last update time of the reserve
uint40 lastUpdateTimestamp;
//address of the ktoken
address kTokenAddress;
//address of the debt token
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
// Reserve factor
uint16 factor;
uint8 decimals;
//the id of the reserve.Represents the position in the list of the active reserves.
uint8 id;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./IScaledBalanceToken.sol";
import "./IInitializableDebtToken.sol";
interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param onBehalfOf The address of the user on which behalf minting has been performed
* @param value The amount to be minted
* @param index The last index of the reserve
**/
event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index);
/**
* @dev Mints debt token to the `onBehalfOf` address
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted when variable debt is burnt
* @param user The user which debt has been burned
* @param amount The amount of debt being burned
* @param index The index of the user
**/
event Burn(address indexed user, uint256 amount, uint256 index);
/**
* @dev Burns user variable debt
* @param user The user which debt is burnt
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IReserveInterestRateStrategy {
function baseVariableBorrowRate() external view returns (uint256);
function getMaxVariableBorrowRate() external view returns (uint256);
function calculateInterestRates(
uint256 availableLiquidity,
uint256 totalVariableDebt,
uint256 reserveFactor
)
external
view
returns (
uint256,
uint256
);
function calculateInterestRates(
address reserve,
address kToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
uint256 totalVariableDebt,
uint256 reserveFactor
)
external
view
returns (
uint256 liquidityRate,
uint256 variableBorrowRate
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../lendingpool/DataTypes.sol";
interface ILendingPool {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the kTokens
* @param amount The amount deposited
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of kTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(
address indexed reserve,
address indexed user,
address indexed to,
uint256 amount
);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRate The numeric rate at which the user has borrowed
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRate
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on initReserve()
**/
event InitReserve(
address asset,
address kTokenAddress,
address variableDebtAddress,
address interestRateStrategyAddress,
uint8 reserveDecimals,
uint16 reserveFactor
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Emitted when a reserve factor is updated
* @param asset The address of the underlying asset of the reserve
* @param factor The new reserve factor
**/
event ReserveFactorChanged(address indexed asset, uint256 factor);
/**
* @dev Emitted when a reserve active state is updated
* @param asset The address of the underlying asset of the reserve
* @param active The new reserve active state
**/
event ReserveActiveChanged(address indexed asset, bool active);
/**
* @dev Emitted when credit system is updated
* @param creditContract The address of the new credit system
**/
event CreditStrategyChanged(address creditContract);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying kTokens.
* - E.g. User deposits 100 USDT and gets in return 100 kUSDT
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the kTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of kTokens
* is a different wallet
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent kTokens owned
* E.g. User has 100 kUSDT, calls withdraw() and receives 100 USDT, burning the 100 aUSDT
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole kToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already had a credit line, or he was given enough allowance by a credit delegator on the
* corresponding debt token
* - E.g. User borrows 100 USDT passing as `onBehalfOf` his own address, receiving the 100 USDT in his wallet
* and 100 variable debt tokens
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own credit, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDT, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset`
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
address onBehalfOf
) external returns (uint256);
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalDebtInWEI the total debt in WEI of the user
* @return availableBorrowsInWEI the borrowing power left of the user
**/
function getUserAccountData(address user)
external
view
returns (uint256 totalDebtInWEI, uint256 availableBorrowsInWEI);
function initReserve(
address reserve,
address kTokenAddress,
address variableDebtAddress,
address interestRateStrategyAddress,
uint8 reserveDecimals,
uint16 reserveFactor
) external;
function setReserveInterestRateStrategyAddress(
address reserve,
address rateStrategyAddress
) external;
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset)
external
view
returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset)
external
view
returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset)
external
view
returns (DataTypes.ReserveData memory);
function getReservesList() external view returns (address[] memory);
function setPause(bool val) external;
function paused() external view returns (bool);
function getActive(address asset) external view returns (bool);
function setCreditStrategy(address creditContract) external;
function getCreditStrategy() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "./IScaledBalanceToken.sol";
import "./IInitializableKToken.sol";
interface IKToken is IERC20Upgradeable, IScaledBalanceToken, IInitializableKToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param value The amount being
* @param index The new liquidity index of the reserve
**/
event Mint(address indexed from, uint256 value, uint256 index);
/**
* @dev Mints `amount` kTokens to `user`
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted after kTokens are burned
* @param from The owner of the kTokens, getting them burned
* @param target The address that will receive the underlying
* @param value The amount being burned
* @param index The new liquidity index of the reserve
**/
event Burn(address indexed from, address indexed target, uint256 value, uint256 index);
/**
* @dev Emitted during the transfer action
* @param from The user whose tokens are being transferred
* @param to The recipient
* @param value The amount being transferred
* @param index The new liquidity index of the reserve
**/
event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);
/**
* @dev Burns kTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* @param user The owner of the kTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external;
/**
* @dev Mints kTokens to the reserve treasury
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external;
/**
* @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param user The recipient of the underlying
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);
/**
* @dev Invoked to execute actions on the kToken side after a repayment.
* @param user The user executing the repayment
* @param amount The amount getting repaid
**/
function handleRepayment(address user, uint256 amount) external;
/**
* @dev Returns the address of the underlying asset of this kToken (E.g. USDT for kUSDT)
**/
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./ILendingPool.sol";
interface IInitializableKToken {
/**
* @dev Emitted when an kToken is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param treasury The address of the treasury
* @param kTokenDecimals the decimals of the underlying
* @param kTokenName the name of the kToken
* @param kTokenSymbol the symbol of the kToken
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address treasury,
uint8 kTokenDecimals,
string kTokenName,
string kTokenSymbol,
bytes params
);
/**
* @dev Initializes the kToken
* @param pool The address of the lending pool where this kToken will be used
* @param treasury The address of the Kyoko treasury, receiving the fees on this kToken
* @param underlyingAsset The address of the underlying asset of this kToken (E.g. USDT for kUSDT)
* @param kTokenDecimals The decimals of the kToken, same as the underlying asset's
* @param kTokenName The name of the kToken
* @param kTokenSymbol The symbol of the kToken
*/
function initialize(
ILendingPool pool,
address treasury,
address underlyingAsset,
uint8 kTokenDecimals,
string calldata kTokenName,
string calldata kTokenSymbol,
bytes calldata params
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./ILendingPool.sol";
interface IInitializableDebtToken {
/**
* @dev Emitted when a debt token is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param debtTokenDecimals the decimals of the debt token
* @param debtTokenName the name of the debt token
* @param debtTokenSymbol the symbol of the debt token
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
uint8 debtTokenDecimals,
string debtTokenName,
string debtTokenSymbol,
bytes params
);
/**
* @dev Initializes the debt token.
* @param pool The address of the lending pool where this kToken will be used
* @param underlyingAsset The address of the underlying asset of this kToken (E.g. USDT for kUSDT)
* @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's
* @param debtTokenName The name of the token
* @param debtTokenSymbol The symbol of the token
*/
function initialize(
ILendingPool pool,
address underlyingAsset,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol,
bytes calldata params
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
/**
* @dev this contract represents the credit line in the whitelist.
* @dev the guild's credit line amount
* @dev the decimals is 1e18.
*/
contract CreditSystem is AccessControlEnumerableUpgradeable {
using SafeMathUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/// the role manage total credit manager
bytes32 public constant ROLE_CREDIT_MANAGER =
keccak256("ROLE_CREDIT_MANAGER");
uint8 public constant G2G_MASK = 0x0E;
uint8 public constant CCAL_MASK = 0x0D;
uint8 constant IS_G2G_START_BIT_POSITION = 0;
uint8 constant IS_CCAL_START_BIT_POSITION = 1;
struct CreditInfo {
//ERC20 credit line
uint256 g2gCreditLine;
//ccal module credit line
uint256 ccalCreditLine;
//bit 0: g2g isActive flag(0==false, 1==true)
//bit 1: ccal isActive flag(0==false, 1==true)
uint8 flag;
}
// the credit line
mapping(address => CreditInfo) whiteList;
//g2g whiteList Set
EnumerableSetUpgradeable.AddressSet private g2gWhiteSet;
//ccal whiteList Set
EnumerableSetUpgradeable.AddressSet private ccalWhiteSet;
event SetG2GCreditLine(address user, uint256 amount);
event SetCCALCreditLine(address user, uint256 amount);
// event SetPaused(address user, bool flag);
event SetG2GActive(address user, bool active);
event SetCCALActive(address user, bool active);
event RemoveG2GCredit(address user);
event RemoveCCALCredit(address user);
modifier onlyCreditManager() {
require(
hasRole(ROLE_CREDIT_MANAGER, _msgSender()),
"only the manager has permission to perform this operation."
);
_;
}
// constructor() {
// _grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
// }
function initialize() public initializer {
__AccessControlEnumerable_init();
_grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/**
* set the address's g2g module credit line
* @dev user the guild in the whiteList
* @dev amount the guild credit line amount
* @dev 1U = 1e18
*/
function setG2GCreditLine(address user, uint256 amount)
public
onlyCreditManager
{
whiteList[user].g2gCreditLine = amount;
setG2GActive(user, amount > 0);
emit SetG2GCreditLine(user, amount);
}
/**
* @dev set the address's g2g module credit active status
*/
function setG2GActive(address user, bool active) public onlyCreditManager {
//set user flag
setG2GFlag(user, active);
//set user white set
if (active) {
uint256 userG2GCreditLine = getG2GCreditLine(user);
userG2GCreditLine > 0 ? g2gWhiteSet.add(user) : g2gWhiteSet.remove(user);
} else {
g2gWhiteSet.remove(user);
}
emit SetG2GActive(user, active);
}
function setG2GFlag(address user, bool active) private {
uint8 flag = whiteList[user].flag;
flag =
(flag & G2G_MASK) |
(uint8(active ? 1 : 0) << IS_G2G_START_BIT_POSITION);
whiteList[user].flag = flag;
}
/**
* set the address's ccal module credit line
* @dev user the guild in the whiteList
* @dev amount the guild credit line amount
* @dev 1U = 1e18
*/
function setCCALCreditLine(address user, uint256 amount)
public
onlyCreditManager
{
whiteList[user].ccalCreditLine = amount;
setCCALActive(user, amount > 0);
emit SetCCALCreditLine(user, amount);
}
/**
* @dev set the address's ccal module credit active status
*/
function setCCALActive(address user, bool active) public onlyCreditManager {
//set user flag
setCCALFlag(user, active);
//set user white set
if (active) {
uint256 userCCALCreditLine = getCCALCreditLine(user);
userCCALCreditLine > 0 ? ccalWhiteSet.add(user) : ccalWhiteSet.remove(user);
} else {
ccalWhiteSet.remove(user);
}
emit SetCCALActive(user, active);
}
function setCCALFlag(address user, bool active) private {
uint8 flag = whiteList[user].flag;
flag =
(flag & CCAL_MASK) |
(uint8(active ? 1 : 0) << IS_CCAL_START_BIT_POSITION);
whiteList[user].flag = flag;
}
/**
* remove the address's g2g module credit line
*/
function removeG2GCredit(address user) public onlyCreditManager {
whiteList[user].g2gCreditLine = 0;
setG2GActive(user, false);
emit RemoveG2GCredit(user);
}
/**
* remove the address's ccal module credit line
*/
function removeCCALCredit(address user) public onlyCreditManager {
whiteList[user].ccalCreditLine = 0;
setCCALActive(user, false);
emit RemoveCCALCredit(user);
}
/**
* @dev query the user credit line
* @param user the address which to query
* @return G2G credit line
*/
function getG2GCreditLine(address user) public view returns (uint256) {
CreditInfo memory credit = whiteList[user];
return credit.g2gCreditLine;
}
/**
* @dev query the user credit line
* @param user the address which to query
* @return CCAL credit line
*/
function getCCALCreditLine(address user) public view returns (uint256) {
CreditInfo memory credit = whiteList[user];
return credit.ccalCreditLine;
}
/**
* @dev query the white list addresses in G2G
*/
function getG2GWhiteList() public view returns (address[] memory) {
return g2gWhiteSet.values();
}
/**
* @dev query the white list addresses in CCAL
*/
function getCCALWhiteList() public view returns (address[] memory) {
return ccalWhiteSet.values();
}
/**
* @dev query the address state
*/
function getState(address user) public view returns (bool, bool) {
uint8 activeFlag = whiteList[user].flag;
return (
activeFlag & ~G2G_MASK != 0,
activeFlag & ~CCAL_MASK != 0
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// 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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// 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 IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `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 {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
uint256[49] private __gap;
}
|
Gets the decimals of the underlying asset of the reserve self The reserve configuration return The decimals of the asset/
|
function getDecimal(DataTypes.ReserveData storage self)
internal
view
returns (uint8)
{
return self.decimals;
}
| 11,804,921
|
//
// This file is part of TrustEth.
// Copyright (c) 2016 Jacob Dawid <jacob@omg-it.works>
//
// TrustEth is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TrustEth is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with TrustEth.
// If not, see <http://www.gnu.org/licenses/>.
//
contract TrustEth {
// A registered transaction initiated by the seller.
struct Transaction {
// Supplied by the seller (Step 1).
uint sellerId; // The seller id of the seller who initiated this transaction and is about to receive the payment.
uint amount; // The amount to pay to the seller for this transaction.
// Filled out by the contract when transaction has been paid (Step 2).
address paidWithAddress; // The address of the buyer issueing the payment.
bool paid; // Flag that states this transaction has already been paid.
// Rating supplied by the buyer (Step 3, optional).
uint ratingValue; // Seller rating supplied by buyer.
string ratingComment; // Comment on this transaction supplied by the buyer.
bool rated; // Flag that states this transaction has already been rated.
}
// A registered seller on this contract.
// Registered sellers can put up transactions and can be rated
// by those who paid the transactions.
struct Seller {
// Seller information
address etherAddress; // The sellers ether address.
uint[] ratingIds; // The ids of the rating linked with this seller.
uint[] transactionIds; // The ids of transactions linked with this seller.
// Statistics about the seller
uint averageRating; // Average value of ratings.
uint transactionsPaid; // How many transactions have been paid?
uint transactionsRated; // How many transactions have been rated?
}
Transaction[] public transactions; // All transactions.
Seller[] public sellers; // All sellers
// This mapping makes it easier to loopkup the seller that belongs to a certain address.
mapping (address => uint) sellerLookup;
// The sole contract owner.
address public owner;
// Configured fees.
uint public registrationFee;
uint public transactionFee;
// Only owner administration flag.
modifier onlyowner { if (msg.sender == owner) _ }
// Administrative functions.
function TrustEth() {
owner = msg.sender;
// Index 0 is a marker for invalid ids.
sellers.length = 1;
transactions.length = 1;
// Initialize fees.
registrationFee = 1 ether;
transactionFee = 50 finney;
}
function retrieveFunds() onlyowner {
owner.send(this.balance);
}
function adjustRegistrationFee(uint fee) onlyowner {
registrationFee = fee;
}
function adjustTransactionFee(uint fee) onlyowner {
transactionFee = fee;
}
function setOwner(address _owner) onlyowner {
owner = _owner;
}
// Fallback function, do not accepts payments made directly to this contract address.
function() {
throw;
}
// Make a donation and acknowledge our development efforts. Thank you!
function donate() {
// That's awesome. Thank you.
return;
}
// Register your seller address for a small fee to prevent flooding and
// and recurring address recreation.
function register() {
// Retrieve the amount of ethers that have been sent along.
uint etherPaid = msg.value;
if(etherPaid < registrationFee) { throw; }
// Create a new seller.
uint sellerId = sellers.length;
sellers.length += 1;
// Store seller details and bind to address.
sellers[sellerId].etherAddress = msg.sender;
sellers[sellerId].averageRating = 0;
// Save sellerId in lookup mapping.
sellerLookup[msg.sender] = sellerId;
}
// Workflow
// As a seller, put up a transaction.
function askForEther(uint amount) {
// Lookup the seller.
uint sellerId = sellerLookup[msg.sender];
// Check whether the seller is a registered seller.
if(sellerId == 0) { throw; }
// Create a new invoice.
uint transactionId = transactions.length;
transactions.length += 1;
// Fill out seller info.
transactions[transactionId].sellerId = sellerId;
transactions[transactionId].amount = amount;
// -> Pass transactionId to customer now.
}
// As a buyer, pay a transaction.
function payEther(uint transactionId) {
// Bail out in case the transaction id is invalid.
if(transactionId < 1 || transactionId >= transactions.length) { throw; }
// Retrieve the amount of ethers that have been sent along.
uint etherPaid = msg.value;
uint etherAskedFor = transactions[transactionId].amount;
uint etherNeeded = etherAskedFor + transactionFee;
// If the amount of ethers does not suffice to pay, bail out :(
if(etherPaid < etherNeeded) { throw; }
// Calculate how much has been overpaid.
uint payback = etherPaid - etherNeeded;
// ..and kindly return the payback :)
msg.sender.send(payback);
// Now take the remaining amount and send to the seller.
sellers[transactions[transactionId].sellerId].etherAddress.send(etherAskedFor);
// Rise transactions paid counter.
sellers[transactions[transactionId].sellerId].transactionsPaid += 1;
// Overpaid ethers send back, seller has been paid, now we're done.
// Mark the transaction as finished.
// Flag the invoice as paid.
transactions[transactionId].paid = true;
// Save the payers address so he is eligible to rate.
transactions[transactionId].paidWithAddress = msg.sender;
// -> Now the transaction can be rated by the address that has paid it.
}
// As a buyer, rate a transaction.
function rate(uint transactionId, uint ratingValue, string ratingComment) {
// Only the address that has paid the transaction may rate it.
if(transactions[transactionId].paidWithAddress != msg.sender) { throw; }
// Bail out in case the transaction id is invalid.
if(transactionId < 1 || transactionId >= transactions.length) { throw; }
// Oops, transaction has already been rated!
if(transactions[transactionId].rated) { throw; }
// Oops, transaction has not been paid yet and cannot be rated!
if(!transactions[transactionId].paid) { throw; }
// Rating range is from 1 (incl.) to 10 (incl.).
if(ratingValue < 1 || ratingValue > 10) { throw; }
transactions[transactionId].ratingValue = ratingValue;
transactions[transactionId].ratingComment = ratingComment;
transactions[transactionId].rated = true;
uint previousTransactionCount = sellers[transactions[transactionId].sellerId].transactionsRated;
uint previousTransactionRatingSum = sellers[transactions[transactionId].sellerId].averageRating * previousTransactionCount;
sellers[transactions[transactionId].sellerId].averageRating = (previousTransactionRatingSum + ratingValue) / (previousTransactionCount + 1);
sellers[transactions[transactionId].sellerId].transactionsRated += 1;
}
}
|
As a buyer, pay a transaction. Bail out in case the transaction id is invalid. Retrieve the amount of ethers that have been sent along. If the amount of ethers does not suffice to pay, bail out :( Calculate how much has been overpaid. ..and kindly return the payback :) Now take the remaining amount and send to the seller. Rise transactions paid counter. Overpaid ethers send back, seller has been paid, now we're done. Mark the transaction as finished. Flag the invoice as paid. Save the payers address so he is eligible to rate. -> Now the transaction can be rated by the address that has paid it.
|
function payEther(uint transactionId) {
uint etherPaid = msg.value;
uint etherAskedFor = transactions[transactionId].amount;
uint etherNeeded = etherAskedFor + transactionFee;
uint payback = etherPaid - etherNeeded;
msg.sender.send(payback);
sellers[transactions[transactionId].sellerId].etherAddress.send(etherAskedFor);
sellers[transactions[transactionId].sellerId].transactionsPaid += 1;
transactions[transactionId].paid = true;
transactions[transactionId].paidWithAddress = msg.sender;
}
| 5,372,931
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.