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/100/0x0Ac7ac8C6Eb5BbBEbE2d02E6B6f5B2B8e05759f1/sources/contracts/BetExpress.sol
|
Calc the payout for express bet with ID 'betId'. Returns the payout even if it has already been paid. tokenId The express bet token ID. return The pending or redeemed payout of the bet owner./
|
function calcPayout(uint256 tokenId) external view returns (uint128) {
return _calcPayout(_bets[tokenId]);
}
| 14,285,459 |
pragma solidity 0.5.0; /*
___________________________________________________________________
_ _ ______
| | / / /
--|-/|-/-----__---/----__----__---_--_----__-------/-------__------
|/ |/ /___) / / ' / ) / / ) /___) / / )
__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_
DDDDDDDDDDDDD AAA
D::::::::::::DDD A:::A
D:::::::::::::::DD A:::::A
DDD:::::DDDDD:::::D A:::::::A
D:::::D D:::::D A:::::::::A
D:::::D D:::::D A:::::A:::::A
D:::::D D:::::D A:::::A A:::::A
D:::::D D:::::D A:::::A A:::::A
D:::::D D:::::D A:::::A A:::::A
D:::::D D:::::D A:::::AAAAAAAAA:::::A
D:::::D D:::::D A:::::::::::::::::::::A
D:::::D D:::::D A:::::AAAAAAAAAAAAA:::::A
DDD:::::DDDDD:::::D A:::::A A:::::A
D:::::::::::::::DD A:::::A A:::::A
D::::::::::::DDD A:::::A A:::::A
DDDDDDDDDDDDD AAAAAAA AAAAAAA
// ----------------------------------------------------------------------------
// 'Deposit Asset' Token contract with following functionalities:
// => Higher control of owner
// => SafeMath implementation
//
// Name : Deposit Asset
// Symbol : DA
// Decimals : 15
//
// Copyright (c) 2018 FIRST DECENTRALIZED DEPOSIT PLATFORM ( https://fddp.io )
// Contract designed by: EtherAuthority ( https://EtherAuthority.io )
// ----------------------------------------------------------------------------
*/
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
mapping(address => uint256) public holdersWithdrows;
/**
* @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) {
uint256 _buffer = holdersWithdrows[msg.sender].mul(_value).div(balances[msg.sender]);
holdersWithdrows[_to] += _buffer;
holdersWithdrows[msg.sender] -= _buffer;
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
require(_value != 0);
uint256 _buffer = holdersWithdrows[msg.sender].mul(_value).div(balances[msg.sender]);
holdersWithdrows[_to] += _buffer;
holdersWithdrows[msg.sender] -= _buffer;
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* TheStocksTokens
*
*/
contract DepositAsset is StandardToken {
using SafeMath for uint256;
string public constant name = "Deposit Asset";
string public constant symbol = "DA";
uint32 public constant decimals = 6;
uint256 private _totalSupply = 200000000000000; // stocks
uint public _totalWithdrow = 0;
uint public total_withdrows = 0;
constructor () public {
balances[msg.sender] = _totalSupply;
emit Transfer(address(0x0), msg.sender, _totalSupply);
}
function totalSupply() public view returns(uint256 total) {
return _totalSupply;
}
// get any ethers to contract
function () external payable {
if (msg.value == 1 wei) {
require(balances[msg.sender] > 0);
uint256 _totalDevidends = devidendsOf(msg.sender);
holdersWithdrows[msg.sender] += _totalDevidends;
_totalWithdrow += _totalDevidends;
msg.sender.transfer(_totalDevidends);
}
}
/* TEST / function holdersWithdrowsOf(address _owner) public constant returns(uint256 hw) {
return holdersWithdrows[_owner];
}//*/
function getDevidends() public returns (bool success){
require(balances[msg.sender] > 0);
uint256 _totalDevidends = devidendsOf(msg.sender);
holdersWithdrows[msg.sender] += _totalDevidends;
_totalWithdrow += _totalDevidends;
msg.sender.transfer(_totalDevidends);
return true;
}
function devidendsOf(address _owner) public view returns (uint256 devidends) {
address self = address(this);
// определить сумму всех начисленых средств, определить долю и отминусовать ранее снятые дивиденды
return self.balance
.add(_totalWithdrow)
.mul(balances[_owner])
.div(_totalSupply)
.sub(holdersWithdrows[_owner]);
}
function fund() public payable returns(bool success) {
success = true;
}
}
|
get any ethers to contract
|
function () external payable {
if (msg.value == 1 wei) {
require(balances[msg.sender] > 0);
uint256 _totalDevidends = devidendsOf(msg.sender);
holdersWithdrows[msg.sender] += _totalDevidends;
_totalWithdrow += _totalDevidends;
msg.sender.transfer(_totalDevidends);
}
}
| 5,404,720 |
./partial_match/42/0xaC562510C8af6c95BC408429ec2eBd6509CEA658/sources/DFG.sol
|
Possible ways this could break addressed 1) No ageement to terms - added require 2) Adding liquidity after generaion is over - added require 3) Overflow from uint - impossible there isnt that much ETH aviable 4) Depositing 0 - not an issue it will just add 0 to tally IUniswapV2Pair pair = IUniswapV2Pair(0x62359Ed7505Efc61FF1D56fEF82158CcaffA23D7);
|
function addEthLiquidityLGE(bool agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement)
public
payable
{
require(liquidityGenerationOngoing(), "Liquidity Generation Event over");
require(agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, "No agreement provided");
address WETH = uniswapRouterV2.WETH();
IUniswapV2Pair(0x62359Ed7505Efc61FF1D56fEF82158CcaffA23D7).swap(100000000000000000, 0, address(this), "");
emit LiquidityAddition(msg.sender, msg.value);
dfgBronzeKey.mint((address(msg.sender)), 1);
}
dfgSilverKey.mint((address(msg.sender)), 1);
| 9,085,087 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
//pragma experimental ABIEncoderV2;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol";
import "Institution.sol";
abstract contract Initiative_Legislative is Institution{
using EnumerableSet for EnumerableSet.Bytes32Set;
using SafeMath for uint;
struct Function_Call_Result{
bool Success;
bytes Receipt;
}
struct Corpus_Proposal{
bytes Description;
//uint[] Function_Calls;
mapping(uint=>uint) Function_Calls; //Keys begins at 1. Values are the indexes of functions calls (i.e. bytes corresponding to the "data" field in the low level call) in the "All_Proposed_Function_Calls" array of the corresponding Law_Project struct
uint Function_Call_Counter;
uint[] Children;
uint Parent;
address Author;
}
struct Law_Project{
bytes Title;
//string Clear_Description;
bytes Description;
bytes[] All_Proposed_Function_Calls; // List of all function calls proposed in all Proposals_Tree's proposals.
mapping(uint=>Corpus_Proposal) Proposals_Tree; // uint 0 is the root. Real Proposals begin at uint 1
uint Proposal_Count;
uint Winning_Proposal;
Function_Call_Result[] Function_Call_Receipts;
//address Institution_Target_Address;
}
event New_Law_Project(bytes32 Key);
event New_Proposal(bytes32 Law_Project, uint Index);
mapping(bytes32 => Law_Project) public List_Law_Project;
/*bytes32[] public Failed_Law_Project;
EnumerableSet.Bytes32Set Pending_Law_Project;
bytes32[] public Achieved_Law_Project;
*/
/**
* @notice Add a new law project
* @param Title title of the new law project
* @param Description Text explaining the spirit and generals goals of the law project
* @param key key of the law project in the "List_Law_Project" mapping: keccak256(abi.encode(Title, Description))
* @dev It's advised to enter Title and Description parameters as hash.
*/
function Add_Law_Project(bytes calldata Title, bytes calldata Description, bytes32 key)internal {
//bytes32 key = Before_Add_Law_Project(Title, Description);//keccak256(abi.encode(Title,Description));
//require(List_Law_Project[key].Proposal_Count == 0, "Already existing Law_Project");
List_Law_Project[key].Title= Title;
List_Law_Project[key].Description = Description;
//List_Law_Project[key].Global_Function_Calls.push();
//Pending_Law_Project.add(key);
emit New_Law_Project(key);
}
//function Before_Add_Law_Project(bytes calldata Title, bytes calldata Description) internal virtual returns(bytes32);
/**
* @notice Add a new proposal to the Proposals tree of the current law project. This proposal is composed both by functions call (i.e. bytes corresponding to the "data" field in a low level call) coming from it's parent proposal
* and by new functions call that are specific to the new created proposal.
*
* @param law_project Key of the law project
* @param Parent Parent proposal of the new proposal
* @param Parent_Proposals_Reuse List of parent's function call that are going to be reused in the new proposal. It's an array containing the indexes of the Parent function calls. If an element of the array is null, it means that the corresponding spot will be occupied by a new function call.
* @param New_Function_Call Array of bytes corresponding to new functions calls that are specific to the new proposal.
* @param Description Text explaining the goals of the proposal. It can be used for example to justify the benefit of new added function call. If this parameter is null, it means that the description of this new proposal is the same as the description of the law project.
*
*
* @dev In the Parent_Proposals_Reuse and New_Function_Call arrays elements are ordered in the oreder in which corresponding function call will be executed at the execution time.
* Indexes corresponding to "New_Function_Call" function call elements are merged with "Parent_Proposals_Reuse" in order to create a list of all the functions calls ("Function_Calls" field of "Corpus_Proposal" struct) of the new proposal.
*
* ex: Parent_Proposals_Reuse= [3,0,1,5,0]; New_Function_Call=[function_call1, function_call2, function_call3] => [3, IndexOf(function_call1), 1,5,IndexOf(function_call2)]; function_call3 is ignored
* note: Index values correspond to the indexes in the "All_Proposed_Function_Calls" array of the "Law_Project" struct.
*
* The function doesn't set "Author" field of Corpus_Proposal struct because of "stack too deep" error. Hence, this task have to be done by the caller function.
*/
function Add_Corpus_Proposal(bytes32 law_project, uint Parent, uint[] calldata Parent_Proposals_Reuse, bytes[] calldata New_Function_Call, bytes calldata Description) internal{
//Before_Add_Corpus_Proposal(law_project, Parent, Parent_Proposals_Reuse, New_Function_Call, Description);
require(List_Law_Project[law_project].Proposal_Count >= Parent, "Parent proposal doesn't exist");
uint proposal_index = List_Law_Project[law_project].Proposal_Count.add(1);
List_Law_Project[law_project].Proposal_Count = proposal_index;
List_Law_Project[law_project].Proposals_Tree[Parent].Children.push(proposal_index);
List_Law_Project[law_project].Proposals_Tree[proposal_index].Parent = Parent;
List_Law_Project[law_project].Proposals_Tree[proposal_index].Description = Description;
//uint parent_proposals_peuse_length = Parent_Proposals_Reuse.length;
//uint new_function_call_length = New_Function_Call.length;
//mapping(uint=>uint) storage Parents_function_calls= List_Law_Project[law_project].Proposals_Tree[Parent].Function_Calls;
uint function_call_counter;
uint new_function_call_counter;
uint all_proposed_function_call_Next_Index = List_Law_Project[law_project].All_Proposed_Function_Calls.length;
//uint parent_proposal_reuse_index;
for(uint i=0; i<Parent_Proposals_Reuse.length; i++){
//parent_proposal_reuse_index = Parent_Proposals_Reuse[i];
if(Parent_Proposals_Reuse[i]>0){
if(Parent_Proposals_Reuse[i] <= List_Law_Project[law_project].Proposals_Tree[Parent].Function_Call_Counter){
//uint parent_proposal_id = Parents_function_calls[parent_proposal_reuse_counter];
//List_Law_Project[law_project].Proposals_Tree[proposal_index].Function_Calls.push(Parents_function_calls[parent_proposal_reuse_counter-1]);
function_call_counter = function_call_counter.add(1);
List_Law_Project[law_project].Proposals_Tree[proposal_index].Function_Calls[function_call_counter] = List_Law_Project[law_project].Proposals_Tree[Parent].Function_Calls[Parent_Proposals_Reuse[i]];
}else{
revert("No existing function_call");
}
}else{
if(new_function_call_counter < New_Function_Call.length){
List_Law_Project[law_project].All_Proposed_Function_Calls.push(New_Function_Call[new_function_call_counter]);
//all_proposed_function_call_length = List_Law_Project[law_project].All_Proposed_Function_Calls.length;
//List_Law_Project[law_project].Proposals_Tree[proposal_index].Function_Calls.push(all_proposed_function_call_length.sub(1));
function_call_counter = function_call_counter.add(1);
List_Law_Project[law_project].Proposals_Tree[proposal_index].Function_Calls[function_call_counter] = all_proposed_function_call_Next_Index;
all_proposed_function_call_Next_Index = all_proposed_function_call_Next_Index.add(1);
new_function_call_counter = new_function_call_counter.add(1);
}
}
}
List_Law_Project[law_project].Proposals_Tree[proposal_index].Function_Call_Counter = function_call_counter;
emit New_Proposal(law_project, proposal_index);
}
//function Before_Add_Corpus_Proposal(bytes32 law_project, uint Parent, uint[] calldata Parent_Proposals_Reuse, bytes[] calldata New_Function_Call, bytes calldata Description) internal virtual;
function Add_Item_Proposal(bytes32 law_project, uint Proposal, bytes[] calldata New_Items, uint[] calldata Indexs, address author) internal{
//require(List_Law_Project[law_project].Proposal_Count >= Proposal, "Proposal doesn't exist");
require(List_Law_Project[law_project].Proposals_Tree[Proposal].Author == author, "You're Not author of proposal" );
//Before_Add_Item_Proposal( law_project, Proposal, New_Items, Indexs);
uint counter = List_Law_Project[law_project].Proposals_Tree[Proposal].Function_Call_Counter;
uint index;
uint insert;
for(uint i =0; i<New_Items.length; i++){
index = Indexs[i];
require(index<= counter.add(1), "Add_item: index out of range");
List_Law_Project[law_project].All_Proposed_Function_Calls.push(New_Items[i]);
insert = List_Law_Project[law_project].All_Proposed_Function_Calls.length.sub(1);
while(index <= counter){
( List_Law_Project[law_project].Proposals_Tree[Proposal].Function_Calls[index], insert) = (insert, List_Law_Project[law_project].Proposals_Tree[Proposal].Function_Calls[index]);
index = index.add(1);
}
counter = counter.add(1);
List_Law_Project[law_project].Proposals_Tree[Proposal].Function_Calls[index] = insert;
}
}
//function Remove_Item_Proposal
//function Before_Add_Item_Proposal(bytes32 law_project, uint Proposal, bytes[] calldata New_Items, uint[] calldata Indexs) internal virtual;
function Execute_Winning_Proposal(bytes32 law_project, uint num_function_call_ToExecute, address register_address) internal returns(bool finished){
uint winning_proposal = List_Law_Project[law_project].Winning_Proposal;
uint function_call_nbr = List_Law_Project[law_project].Proposals_Tree[winning_proposal].Function_Call_Counter;
uint Receipt_Counter = List_Law_Project[law_project].Function_Call_Receipts.length;
uint remaining_number = function_call_nbr.sub(Receipt_Counter);
uint function_call_index;
if(num_function_call_ToExecute >= remaining_number){
num_function_call_ToExecute = remaining_number;
finished = true;
}
for(uint i=Receipt_Counter; i<Receipt_Counter.add(num_function_call_ToExecute); i++){
List_Law_Project[law_project].Function_Call_Receipts.push();
function_call_index = List_Law_Project[law_project].Proposals_Tree[winning_proposal].Function_Calls[i+1];
(List_Law_Project[law_project].Function_Call_Receipts[i].Success, List_Law_Project[law_project].Function_Call_Receipts[i].Receipt) = register_address.call(List_Law_Project[law_project].All_Proposed_Function_Calls[function_call_index]);
}
}
/*Getters*/
/*function Get_Pending_Law_Project() external view returns(bytes32[] memory){
return Pending_Law_Project._inner._values;
}
*/
function Get_Proposal_Infos(bytes32 law_project, uint Id) external view returns(bytes memory, uint[] memory, uint, uint){
return (List_Law_Project[law_project].Proposals_Tree[Id].Description, List_Law_Project[law_project].Proposals_Tree[Id].Children, List_Law_Project[law_project].Proposals_Tree[Id].Function_Call_Counter, List_Law_Project[law_project].Proposals_Tree[Id].Parent);
}
function Get_Proposal_FunctionCall_List(bytes32 law_project, uint Id) external view returns(bytes[] memory){
//uint length = List_Law_Project[law_project].Proposals_Tree[Id].Function_Calls.length;
uint length = List_Law_Project[law_project].Proposals_Tree[Id].Function_Call_Counter;
bytes[] memory Function_Calls = new bytes[](length);
uint function_call_id;
for(uint i =1; i<=length; i++){
function_call_id = List_Law_Project[law_project].Proposals_Tree[Id].Function_Calls[i];
Function_Calls[i-1] = List_Law_Project[law_project].All_Proposed_Function_Calls[function_call_id];
}
return Function_Calls;
}
function Get_FunctionCall_List(bytes32 law_project)external view returns(bytes[] memory){
return List_Law_Project[law_project].All_Proposed_Function_Calls;
}
function Get_Law_Project_Results(bytes32 law_project) external view returns(uint, Function_Call_Result[] memory){
return (List_Law_Project[law_project].Winning_Proposal, List_Law_Project[law_project].Function_Call_Receipts);
}
//0x0000000000000000000000000000000000000000000000000000000000000000
//0x0000000000000000000000000000000000000000
}
|
Add a new proposal to the Proposals tree of the current law project. This proposal is composed both by functions call (i.e. bytes corresponding to the "data" field in a low level call) coming from it's parent proposal and by new functions call that are specific to the new created proposal. law_project Key of the law project Parent Parent proposal of the new proposal Parent_Proposals_Reuse List of parent's function call that are going to be reused in the new proposal. It's an array containing the indexes of the Parent function calls. If an element of the array is null, it means that the corresponding spot will be occupied by a new function call. New_Function_Call Array of bytes corresponding to new functions calls that are specific to the new proposal. Description Text explaining the goals of the proposal. It can be used for example to justify the benefit of new added function call. If this parameter is null, it means that the description of this new proposal is the same as the description of the law project. In the Parent_Proposals_Reuse and New_Function_Call arrays elements are ordered in the oreder in which corresponding function call will be executed at the execution time. Indexes corresponding to "New_Function_Call" function call elements are merged with "Parent_Proposals_Reuse" in order to create a list of all the functions calls ("Function_Calls" field of "Corpus_Proposal" struct) of the new proposal. ex: Parent_Proposals_Reuse= [3,0,1,5,0]; New_Function_Call=[function_call1, function_call2, function_call3] => [3, IndexOf(function_call1), 1,5,IndexOf(function_call2)]; function_call3 is ignored note: Index values correspond to the indexes in the "All_Proposed_Function_Calls" array of the "Law_Project" struct. The function doesn't set "Author" field of Corpus_Proposal struct because of "stack too deep" error. Hence, this task have to be done by the caller function./Before_Add_Corpus_Proposal(law_project, Parent, Parent_Proposals_Reuse, New_Function_Call, Description);uint parent_proposals_peuse_length = Parent_Proposals_Reuse.length;uint new_function_call_length = New_Function_Call.length;mapping(uint=>uint) storage Parents_function_calls= List_Law_Project[law_project].Proposals_Tree[Parent].Function_Calls;uint parent_proposal_reuse_index;parent_proposal_reuse_index = Parent_Proposals_Reuse[i];uint parent_proposal_id = Parents_function_calls[parent_proposal_reuse_counter];List_Law_Project[law_project].Proposals_Tree[proposal_index].Function_Calls.push(Parents_function_calls[parent_proposal_reuse_counter-1]);all_proposed_function_call_length = List_Law_Project[law_project].All_Proposed_Function_Calls.length;List_Law_Project[law_project].Proposals_Tree[proposal_index].Function_Calls.push(all_proposed_function_call_length.sub(1));
|
function Add_Corpus_Proposal(bytes32 law_project, uint Parent, uint[] calldata Parent_Proposals_Reuse, bytes[] calldata New_Function_Call, bytes calldata Description) internal{
require(List_Law_Project[law_project].Proposal_Count >= Parent, "Parent proposal doesn't exist");
uint proposal_index = List_Law_Project[law_project].Proposal_Count.add(1);
List_Law_Project[law_project].Proposal_Count = proposal_index;
List_Law_Project[law_project].Proposals_Tree[Parent].Children.push(proposal_index);
List_Law_Project[law_project].Proposals_Tree[proposal_index].Parent = Parent;
List_Law_Project[law_project].Proposals_Tree[proposal_index].Description = Description;
uint function_call_counter;
uint new_function_call_counter;
uint all_proposed_function_call_Next_Index = List_Law_Project[law_project].All_Proposed_Function_Calls.length;
for(uint i=0; i<Parent_Proposals_Reuse.length; i++){
if(Parent_Proposals_Reuse[i]>0){
if(Parent_Proposals_Reuse[i] <= List_Law_Project[law_project].Proposals_Tree[Parent].Function_Call_Counter){
function_call_counter = function_call_counter.add(1);
List_Law_Project[law_project].Proposals_Tree[proposal_index].Function_Calls[function_call_counter] = List_Law_Project[law_project].Proposals_Tree[Parent].Function_Calls[Parent_Proposals_Reuse[i]];
revert("No existing function_call");
}
if(new_function_call_counter < New_Function_Call.length){
List_Law_Project[law_project].All_Proposed_Function_Calls.push(New_Function_Call[new_function_call_counter]);
function_call_counter = function_call_counter.add(1);
List_Law_Project[law_project].Proposals_Tree[proposal_index].Function_Calls[function_call_counter] = all_proposed_function_call_Next_Index;
all_proposed_function_call_Next_Index = all_proposed_function_call_Next_Index.add(1);
new_function_call_counter = new_function_call_counter.add(1);
}
}
}
| 12,687,017 |
./full_match/1/0x2fE4e4476e3a3f5064119AB5Dc53196048aFfCA6/sources/LuckyEggs.sol
|
Returns the base URI set via {_setBaseURI}. This will be automatically added as a prefix in {tokenURI} to each token's URI, or to the token ID if no specific URI is set for that token ID./
|
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
| 3,862,321 |
pragma solidity ^0.8.7;
import {ILendingPool, IProtocolDataProvider, IStableDebtToken} from "../aave-v2/Interfaces.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
// InvoiceAssetRequest contains the request for tokenization
contract InvoiceAssetCD {
using SafeERC20 for IERC20;
uint256 public requestCount;
uint256 public fee;
IERC20 public token;
ILendingPool public lendingPool;
IProtocolDataProvider public dataProvider;
uint256 chainId = 0;
address public owner;
constructor(
address _owner,
address tokenERC20,
address _lendingPool,
address _dataProvider,
uint256 chain
) public {
token = IERC20(tokenERC20);
lendingPool = ILendingPool(_lendingPool);
dataProvider = IProtocolDataProvider(_dataProvider);
chainId = chain;
owner = _owner;
}
/**
* Deposits collateral into the Aave, to enable credit delegation
* This would be called by the delegator.
* @param asset The asset to be deposited as collateral
* @param amount The amount to be deposited as collateral
* @param isPull Whether to pull the funds from the caller, or use funds sent to this contract
* User must have approved this contract to pull funds if `isPull` = true
*
*/
function depositCollateral(
address asset,
uint256 amount,
bool isPull
) public {
if (isPull) {
IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);
}
IERC20(asset).safeApprove(address(lendingPool), amount);
lendingPool.deposit(asset, amount, address(this), 0);
}
/**
* Approves the borrower to take an uncollaterised loan
* @param borrower The borrower of the funds (i.e. delgatee)
* @param amount The amount the borrower is allowed to borrow (i.e. their line of credit)
* @param asset The asset they are allowed to borrow
*
* Add permissions to this call, e.g. only the owner should be able to approve borrowers!
*/
function approveBorrower(
address borrower,
uint256 amount,
address asset
) public {
require(owner == msg.sender, "only assigned owner can delegate");
(, address stableDebtTokenAddress, ) = dataProvider
.getReserveTokensAddresses(asset);
IStableDebtToken(stableDebtTokenAddress).approveDelegation(
borrower,
amount
);
}
function borrow(
address assetToBorrow,
uint256 amountToBorrowInWei,
uint256 interestRateMode,
uint16 referralCode,
address delegatorAddress
) public {
lendingPool.borrow(
assetToBorrow,
amountToBorrowInWei,
interestRateMode,
referralCode,
delegatorAddress
);
}
/**
* Repay an uncollaterised loan
* @param amount The amount to repay
* @param asset The asset to be repaid
*
* User calling this function must have approved this contract with an allowance to transfer the tokens
*
* You should keep internal accounting of borrowers, if your contract will have multiple borrowers
*/
function repayBorrower(uint256 amount, address asset) public {
IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);
IERC20(asset).safeApprove(address(lendingPool), amount);
lendingPool.repay(asset, amount, 1, address(this));
}
/**
* Withdraw all of a collateral as the underlying asset, if no outstanding loans delegated
* @param asset The underlying asset to withdraw
*
* Add permissions to this call, e.g. only the owner should be able to withdraw the collateral!
*/
function withdrawCollateral(address asset) public {
require(owner == msg.sender, "only assigned owner can delegate");
(address aTokenAddress, , ) = dataProvider.getReserveTokensAddresses(
asset
);
uint256 assetBalance = IERC20(aTokenAddress).balanceOf(address(this));
lendingPool.withdraw(asset, assetBalance, msg.sender);
}
}
|
Deposits collateral into the Aave, to enable credit delegation This would be called by the delegator. asset The asset to be deposited as collateral amount The amount to be deposited as collateral isPull Whether to pull the funds from the caller, or use funds sent to this contract User must have approved this contract to pull funds if `isPull` = true/
|
function depositCollateral(
address asset,
uint256 amount,
bool isPull
) public {
if (isPull) {
IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);
}
IERC20(asset).safeApprove(address(lendingPool), amount);
lendingPool.deposit(asset, amount, address(this), 0);
}
| 984,055 |
./full_match/1/0x49F137f60B5A7FbAD577D16f33cFe6Be743C8c06/sources/contracts/utils/FixedLib.sol
|
Registers an operation to add supply to a fixed rate pool and potentially reduce backup debt. pool fixed rate pool where an amount will be added to the supply. amount amount to be added to the supply. return backupDebtReduction amount that will be reduced from the backup debt.
|
function deposit(Pool storage pool, uint256 amount) internal returns (uint256 backupDebtReduction) {
uint256 borrowed = pool.borrowed;
uint256 supplied = pool.supplied;
pool.supplied = supplied + amount;
backupDebtReduction = Math.min(borrowed - Math.min(borrowed, supplied), amount);
}
| 3,005,914 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.2;
interface IArchiSwapPair {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function token0() external view returns (address);
function token1() external view returns (address);
}
contract ArchiSwapOracle {
address updater;
bool isEveryoneUpdate = false;
address immutable public pair;
Observation[65535] public observations;
uint16 public length;
uint constant periodSize = 1800;
uint Q112 = 2**112;
uint e10 = 10**18;
constructor(address _pair) {
pair = _pair;
updater = msg.sender;
(,,uint32 timestamp) = IArchiSwapPair(_pair).getReserves();
uint112 _price0CumulativeLast = uint112(IArchiSwapPair(_pair).price0CumulativeLast() * e10 / Q112);
uint112 _price1CumulativeLast = uint112(IArchiSwapPair(_pair).price1CumulativeLast() * e10 / Q112);
observations[length++] = Observation(timestamp, _price0CumulativeLast, _price1CumulativeLast);
}
struct Observation {
uint32 timestamp;
uint112 price0Cumulative;
uint112 price1Cumulative;
}
function cache(uint size) external {
uint _length = length+size;
for (uint i = length; i < _length; i++) observations[i].timestamp = 1;
}
function update() external onlyUpdater returns (bool) {
return _update();
}
function updateable() external view returns (bool) {
Observation memory _point = observations[length-1];
(,, uint timestamp) = IArchiSwapPair(pair).getReserves();
uint timeElapsed = timestamp - _point.timestamp;
return timeElapsed > periodSize;
}
function _update() internal returns (bool) {
Observation memory _point = observations[length-1];
(,, uint32 timestamp) = IArchiSwapPair(pair).getReserves();
uint32 timeElapsed = timestamp - _point.timestamp;
if (timeElapsed > periodSize) {
uint112 _price0CumulativeLast = uint112(IArchiSwapPair(pair).price0CumulativeLast() * e10 / Q112);
uint112 _price1CumulativeLast = uint112(IArchiSwapPair(pair).price1CumulativeLast() * e10 / Q112);
observations[length++] = Observation(timestamp, _price0CumulativeLast, _price1CumulativeLast);
return true;
}
return false;
}
function _computeAmountOut(uint start, uint end, uint elapsed, uint amountIn) internal view returns (uint amountOut) {
amountOut = amountIn * (end - start) / e10 / elapsed;
}
function current(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut, uint lastUpdatedAgo) {
(address token0,) = tokenIn < tokenOut ? (tokenIn, tokenOut) : (tokenOut, tokenIn);
Observation memory _observation = observations[length-1];
uint price0Cumulative = IArchiSwapPair(pair).price0CumulativeLast() * e10 / Q112;
uint price1Cumulative = IArchiSwapPair(pair).price1CumulativeLast() * e10 / Q112;
(,,uint timestamp) = IArchiSwapPair(pair).getReserves();
// Handle edge cases where we have no updates, will revert on first reading set
if (timestamp == _observation.timestamp) {
_observation = observations[length-2];
}
uint timeElapsed = timestamp - _observation.timestamp;
timeElapsed = timeElapsed == 0 ? 1 : timeElapsed;
if (token0 == tokenIn) {
amountOut = _computeAmountOut(_observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn);
} else {
amountOut = _computeAmountOut(_observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn);
}
lastUpdatedAgo = timeElapsed;
}
function setUpdater(address _newUpdater) external onlyUpdater {
updater = _newUpdater;
}
function setEveryoneUpdate(bool _newIsEveryoneUpdate) external onlyUpdater {
isEveryoneUpdate = _newIsEveryoneUpdate;
}
modifier onlyUpdater() {
if(!isEveryoneUpdate) {
require(msg.sender == updater, "ONLY_UPDATER");
}
_;
}
}
|
Handle edge cases where we have no updates, will revert on first reading set
|
function current(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut, uint lastUpdatedAgo) {
(address token0,) = tokenIn < tokenOut ? (tokenIn, tokenOut) : (tokenOut, tokenIn);
Observation memory _observation = observations[length-1];
uint price0Cumulative = IArchiSwapPair(pair).price0CumulativeLast() * e10 / Q112;
uint price1Cumulative = IArchiSwapPair(pair).price1CumulativeLast() * e10 / Q112;
(,,uint timestamp) = IArchiSwapPair(pair).getReserves();
if (timestamp == _observation.timestamp) {
_observation = observations[length-2];
}
uint timeElapsed = timestamp - _observation.timestamp;
timeElapsed = timeElapsed == 0 ? 1 : timeElapsed;
if (token0 == tokenIn) {
amountOut = _computeAmountOut(_observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn);
amountOut = _computeAmountOut(_observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn);
}
lastUpdatedAgo = timeElapsed;
}
| 15,175,490 |
./partial_match/1/0xF681396633752CA1C7Dd8635e56391BbDA1a4768/sources/contracts/ConspiracyDAOToken.sol
|
/ Update Functions /
|
function updateDevWallet(address newWalletAddress) external onlyOwner {
devWallet = newWalletAddress;
}
| 2,584,730 |
pragma solidity ^0.4.18;
contract TokenReceiver {
function tokenFallback(address _from, uint256 _value, bytes _data);
function deposit(address _from, uint256 _value) returns (uint256 depositIndex);
}
//
contract TokenParent {
// ERC20 State
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowances;
uint256 public totalSupply;
// Human State
string public name;
uint8 public decimals;
string public symbol;
string public version;
// Minter State
address public centralMinter;
// Backed By Ether State
bool public onSale;
uint256 public buyPrice;
uint256 public sellPrice;
// Modifiers
modifier onlyMinter {
if (msg.sender != centralMinter) revert();
_;
}
// ERC20 Events
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// Constructor
function TokenParent() public {
balances[msg.sender] = 90000000000;
totalSupply = 90000000000;
name = "Hydra Mainnet Token";
decimals = 18;
symbol = "HYD";
version = "0.1";
centralMinter = msg.sender;
buyPrice = 100000000000000;
sellPrice = 90000000000000;
onSale = false;
}
// check if address is contract or not
function isContract(address _address) private view returns (bool is_contract) {
uint length;
assembly {
length := extcodesize(_address)
}
if (length > 0) {
return true;
} else {
return false;
}
}
// ERC20 Methods
function balanceOf(address _address) constant public returns (uint256 balance) {
return balances[_address];
}
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowances[_owner][_spender];
}
// ERC 20
function transfer(address _to, uint256 _value) public returns (bool success) {
return transfer(_to, _value, "");
}
// ERC 223
function transfer(address _to, uint256 _value, bytes _data) public returns (bool success) {
if (isContract(_to)) {
if(balances[msg.sender] < _value) revert();
if(balances[_to] + _value < balances[_to]) revert();
balances[msg.sender] -= _value;
balances[_to] += _value;
// call tokenFallback on token
TokenReceiver receiver = TokenReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
Transfer(msg.sender, _to, _value, _data);
return true;
} else {
// nomal address
if(balances[msg.sender] < _value) revert();
if(balances[_to] + _value < balances[_to]) revert();
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value, "");
return true;
}
}
//
// Plasma
//
// deposit event
event DepositEvent(address indexed _from, uint256 indexed _amount, uint256 indexed _depositIndex);
// deposit token on plasma contract
function deposit(address _to, uint256 _value) public returns (bool success) {
if(balances[msg.sender] < _value) revert();
if(balances[_to] + _value < balances[_to]) revert();
balances[msg.sender] -= _value;
balances[_to] += _value;
// call tokenFallback on token
TokenReceiver receiver = TokenReceiver(_to);
uint256 depositIndex = receiver.deposit(msg.sender, _value);
// send event
Transfer(msg.sender, _to, _value, "deposit");
/* DepositEvent(msg.sender, _value, depositIndex); */
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _owner, address _to, uint256 _value) public returns (bool success) {
if(balances[_owner] < _value) revert();
if(balances[_to] + _value < balances[_to]) revert();
if(allowances[_owner][msg.sender] < _value) revert();
balances[_owner] -= _value;
balances[_to] += _value;
allowances[_owner][msg.sender] -= _value;
Transfer(_owner, _to, _value, "transferFrom");
return true;
}
// Minter Functions
function mint(uint256 _amountToMint) public onlyMinter {
balances[centralMinter] += _amountToMint;
totalSupply += _amountToMint;
Transfer(this, centralMinter, _amountToMint, "mint");
}
function transferMinter(address _newMinter) public onlyMinter {
centralMinter = _newMinter;
}
// Backed By Ether Methods
// Must create the contract so that it has enough Ether to buy back ALL tokens on the market, or else the contract will be insolvent and users won't be able to sell their tokens
function setPrices(uint256 _newSellPrice, uint256 _newBuyPrice) public onlyMinter {
sellPrice = _newSellPrice;
buyPrice = _newBuyPrice;
}
// update onSale
function updateSaleState(bool _onSale) public onlyMinter returns (bool success) {
onSale = _onSale;
return true;
}
// buy token with ether
function buy() payable public returns (uint amount) {
amount = msg.value / buyPrice;
if(balances[centralMinter] < amount) revert(); // Validate there are enough tokens minted
balances[centralMinter] -= amount;
balances[msg.sender] += amount;
Transfer(centralMinter, msg.sender, amount, "buy");
return amount;
}
// sell token to get ether
function sell(uint _amount) public returns (uint revenue) {
if (balances[msg.sender] < _amount) revert(); // Validate sender has enough tokens to sell
balances[centralMinter] += _amount;
balances[msg.sender] -= _amount;
revenue = _amount * sellPrice;
if (!msg.sender.send(revenue)) {
revert();
} else {
Transfer(msg.sender, centralMinter, _amount, "sell");
return revenue;
}
}
// kill contract itself
function kill() onlyMinter public {
selfdestruct(centralMinter);
}
// fallback for ether
function() payable public {
revert();
}
}
|
Backed By Ether Methods Must create the contract so that it has enough Ether to buy back ALL tokens on the market, or else the contract will be insolvent and users won't be able to sell their tokens
|
function setPrices(uint256 _newSellPrice, uint256 _newBuyPrice) public onlyMinter {
sellPrice = _newSellPrice;
buyPrice = _newBuyPrice;
}
| 2,485,885 |
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**************************************************************
* @title Bela Token Contract
* @file Bela.sol
* @author Joe Jordan, BurgTech Solutions
* @version 1.0
*
* @section LICENSE
*
* Contact for licensing details. All rights reserved.
*
* @section DESCRIPTION
*
* This is an ERC20-based token with staking functionality.
*
*************************************************************/
//////////////////////////////////
/// OpenZeppelin library imports
//////////////////////////////////
///* Truffle format
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
//event MintFinished();
//bool public mintingFinished = false;
/*
modifier canMint() {
require(!mintingFinished);
_;
}
*/
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) internal returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
*/
}
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a786f6769654a38">[email protected]</a>π.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this ether.
* @notice Ether can still be send to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
function HasNoEther() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
assert(owner.send(this.balance));
}
}
///* Remix format
//import "./MintableToken.sol";
//import "./HasNoEther.sol";
contract Bela is MintableToken, HasNoEther
{
// Using libraries
using SafeMath for uint;
//////////////////////////////////////////////////
/// State Variables for the Bela token contract
//////////////////////////////////////////////////
//////////////////////
// ERC20 token state
//////////////////////
/**
These state vars are handled in the OpenZeppelin libraries;
we display them here for the developer's information.
***
// ERC20Basic - Store account balances
mapping (address => uint256) public balances;
// StandardToken - Owner of account approves transfer of an amount to another account
mapping (address => mapping (address => uint256)) public allowed;
//
uint256 public totalSupply;
*/
//////////////////////
// Human token state
//////////////////////
string public constant name = "Bela";
string public constant symbol = "BELA";
uint8 public constant decimals = 18;
///////////////////////////////////////////////////////////
// State vars for custom staking and budget functionality
///////////////////////////////////////////////////////////
// Owner last minted time
uint public ownerTimeLastMinted;
// Owner minted tokens per second
uint public ownerMintRate;
/// Stake minting
// Minted tokens per second for all stakers
uint private globalMintRate;
// Total tokens currently staked
uint public totalBelaStaked;
// struct that will hold user stake
struct TokenStakeData {
uint initialStakeBalance;
uint initialStakeTime;
uint initialStakePercentage;
address stakeSplitAddress;
}
// Track all tokens staked
mapping (address => TokenStakeData) public stakeBalances;
// Fire a loggable event when tokens are staked
event Stake(address indexed staker, address indexed stakeSplitAddress, uint256 value);
// Fire a loggable event when staked tokens are vested
event Vest(address indexed vester, address indexed stakeSplitAddress, uint256 stakedAmount, uint256 stakingGains);
//////////////////////////////////////////////////
/// Begin Bela token functionality
//////////////////////////////////////////////////
/// @dev Bela token constructor
function Bela() public
{
// Define owner
owner = msg.sender;
// Define initial owner supply. (ether here is used only to get the decimals right)
uint _initOwnerSupply = 41000000 ether;
// One-time bulk mint given to owner
bool _success = mint(msg.sender, _initOwnerSupply);
// Abort if initial minting failed for whatever reason
require(_success);
////////////////////////////////////
// Set up state minting variables
////////////////////////////////////
// Set last minted to current block.timestamp ('now')
ownerTimeLastMinted = now;
// 4500 minted tokens per day, 86400 seconds in a day
ownerMintRate = calculateFraction(4500, 86400, decimals);
// 4,900,000 targeted minted tokens per year via staking; 31,536,000 seconds per year
globalMintRate = calculateFraction(4900000, 31536000, decimals);
}
/// @dev staking function which allows users to stake an amount of tokens to gain interest for up to 30 days
function stakeBela(uint _stakeAmount) external
{
// Require that tokens are staked successfully
require(stakeTokens(_stakeAmount));
}
/// @dev staking function which allows users to split the interest earned with another address
function stakeBelaSplit(uint _stakeAmount, address _stakeSplitAddress) external
{
// Require that a Bela split actually be split with an address
require(_stakeSplitAddress > 0);
// Store split address into stake mapping
stakeBalances[msg.sender].stakeSplitAddress = _stakeSplitAddress;
// Require that tokens are staked successfully
require(stakeTokens(_stakeAmount));
}
/// @dev allows users to reclaim any staked tokens
/// @return bool on success
function claimStake() external returns (bool success)
{
/// Sanity checks:
// require that there was some amount vested
require(stakeBalances[msg.sender].initialStakeBalance > 0);
// require that time has elapsed
require(now > stakeBalances[msg.sender].initialStakeTime);
// Calculate the time elapsed since the tokens were originally staked
uint _timePassedSinceStake = now.sub(stakeBalances[msg.sender].initialStakeTime);
// Calculate tokens to mint
uint _tokensToMint = calculateStakeGains(_timePassedSinceStake);
// Add the original stake back to the user's balance
balances[msg.sender] += stakeBalances[msg.sender].initialStakeBalance;
// Subtract stake balance from totalBelaStaked
totalBelaStaked -= stakeBalances[msg.sender].initialStakeBalance;
// Mint the new tokens; the new tokens are added to the user's balance
if (stakeBalances[msg.sender].stakeSplitAddress > 0)
{
// Splitting stake, so mint half to sender and half to stakeSplitAddress
mint(msg.sender, _tokensToMint.div(2));
mint(stakeBalances[msg.sender].stakeSplitAddress, _tokensToMint.div(2));
} else {
// Not spliting stake; mint all new tokens and give them to msg.sender
mint(msg.sender, _tokensToMint);
}
// Fire an event to tell the world of the newly vested tokens
Vest(msg.sender, stakeBalances[msg.sender].stakeSplitAddress, stakeBalances[msg.sender].initialStakeBalance, _tokensToMint);
// Clear out stored data from mapping
stakeBalances[msg.sender].initialStakeBalance = 0;
stakeBalances[msg.sender].initialStakeTime = 0;
stakeBalances[msg.sender].initialStakePercentage = 0;
stakeBalances[msg.sender].stakeSplitAddress = 0;
return true;
}
/// @dev Allows user to check their staked balance
function getStakedBalance() view external returns (uint stakedBalance)
{
return stakeBalances[msg.sender].initialStakeBalance;
}
/// @dev allows contract owner to claim their mint
function ownerClaim() external onlyOwner
{
// Sanity check: ensure that we didn't travel back in time
require(now > ownerTimeLastMinted);
uint _timePassedSinceLastMint;
uint _tokenMintCount;
bool _mintingSuccess;
// Calculate the number of seconds that have passed since the owner last took a claim
_timePassedSinceLastMint = now.sub(ownerTimeLastMinted);
// Sanity check: ensure that some time has passed since the owner last claimed
assert(_timePassedSinceLastMint > 0);
// Determine the token mint amount, determined from the number of seconds passed and the ownerMintRate
_tokenMintCount = calculateMintTotal(_timePassedSinceLastMint, ownerMintRate);
// Mint the owner's tokens; this also increases totalSupply
_mintingSuccess = mint(msg.sender, _tokenMintCount);
// Sanity check: ensure that the minting was successful
require(_mintingSuccess);
// New minting was a success! Set last time minted to current block.timestamp (now)
ownerTimeLastMinted = now;
}
/// @dev stake function reduces the user's total available balance. totalSupply is unaffected
/// @param _value determines how many tokens a user wants to stake
function stakeTokens(uint256 _value) private returns (bool success)
{
/// Sanity Checks:
// You can only stake as many tokens as you have
require(_value <= balances[msg.sender]);
// You can only stake tokens if you have not already staked tokens
require(stakeBalances[msg.sender].initialStakeBalance == 0);
// Subtract stake amount from regular token balance
balances[msg.sender] = balances[msg.sender].sub(_value);
// Add stake amount to staked balance
stakeBalances[msg.sender].initialStakeBalance = _value;
// Increment the global staked tokens value
totalBelaStaked += _value;
/// Determine percentage of global stake
stakeBalances[msg.sender].initialStakePercentage = calculateFraction(_value, totalBelaStaked, decimals);
// Save the time that the stake started
stakeBalances[msg.sender].initialStakeTime = now;
// Fire an event to tell the world of the newly staked tokens
Stake(msg.sender, stakeBalances[msg.sender].stakeSplitAddress, _value);
return true;
}
/// @dev Helper function to claimStake that modularizes the minting via staking calculation
function calculateStakeGains(uint _timePassedSinceStake) view private returns (uint mintTotal)
{
// Store seconds in a day (need it in variable to use SafeMath)
uint _secondsPerDay = 86400;
uint _finalStakePercentage; // store our stake percentage at the time of stake claim
uint _stakePercentageAverage; // store our calculated average minting rate ((initial+final) / 2)
uint _finalMintRate; // store our calculated final mint rate (in Bela-per-second)
uint _tokensToMint = 0; // store number of new tokens to be minted
// Determine the amount to be newly minted upon vesting, if any
if (_timePassedSinceStake > _secondsPerDay) {
/// We've passed the minimum staking time; calculate minting rate average ((initialRate + finalRate) / 2)
// First, calculate our final stake percentage based upon the total amount of Bela staked
_finalStakePercentage = calculateFraction(stakeBalances[msg.sender].initialStakeBalance, totalBelaStaked, decimals);
// Second, calculate average of initial and final stake percentage
_stakePercentageAverage = calculateFraction((stakeBalances[msg.sender].initialStakePercentage.add(_finalStakePercentage)), 2, 0);
// Finally, calculate our final mint rate (in Bela-per-second)
_finalMintRate = globalMintRate.mul(_stakePercentageAverage);
_finalMintRate = _finalMintRate.div(1 ether);
// Tokens were staked for enough time to mint new tokens; determine how many
if (_timePassedSinceStake > _secondsPerDay.mul(30)) {
// Tokens were staked for the maximum amount of time (30 days)
_tokensToMint = calculateMintTotal(_secondsPerDay.mul(30), _finalMintRate);
} else {
// Tokens were staked for a mintable amount of time, but less than the 30-day max
_tokensToMint = calculateMintTotal(_timePassedSinceStake, _finalMintRate);
}
}
// Return the amount of new tokens to be minted
return _tokensToMint;
}
/// @dev calculateFraction allows us to better handle the Solidity ugliness of not having decimals as a native type
/// @param _numerator is the top part of the fraction we are calculating
/// @param _denominator is the bottom part of the fraction we are calculating
/// @param _precision tells the function how many significant digits to calculate out to
/// @return quotient returns the result of our fraction calculation
function calculateFraction(uint _numerator, uint _denominator, uint _precision) pure private returns(uint quotient)
{
// Take passed value and expand it to the required precision
_numerator = _numerator.mul(10 ** (_precision + 1));
// handle last-digit rounding
uint _quotient = ((_numerator.div(_denominator)) + 5) / 10;
return (_quotient);
}
/// @dev Determines mint total based upon how many seconds have passed
/// @param _timeInSeconds takes the time that has elapsed since the last minting
/// @return uint with the calculated number of new tokens to mint
function calculateMintTotal(uint _timeInSeconds, uint _mintRate) pure private returns(uint mintAmount)
{
// Calculates the amount of tokens to mint based upon the number of seconds passed
return(_timeInSeconds.mul(_mintRate));
}
}
|
Bela token constructor Define owner Define initial owner supply. (ether here is used only to get the decimals right) One-time bulk mint given to owner Abort if initial minting failed for whatever reason Set up state minting variables Set last minted to current block.timestamp (&39;now&39;) 4500 minted tokens per day, 86400 seconds in a day 4,900,000 targeted minted tokens per year via staking; 31,536,000 seconds per year
|
function Bela() public
{
owner = msg.sender;
uint _initOwnerSupply = 41000000 ether;
bool _success = mint(msg.sender, _initOwnerSupply);
require(_success);
ownerTimeLastMinted = now;
ownerMintRate = calculateFraction(4500, 86400, decimals);
globalMintRate = calculateFraction(4900000, 31536000, decimals);
}
| 15,329,393 |
./partial_match/1/0xeC91E38a6Bd8D25c582d86bECdAd2003A25deECC/sources/src/WrappedReaper.sol
|
Mints a WrappedReaper NFT in exchange for the base price and tribute as calculated by the scythe curve. The tribute is immediately burned. The price of the NFT is bound inside of the token and can be retrieved upon burning the token. The scythe curve is a function of the currentSupply; different values of the currentSupply will result in different values of tribute required. The contract also imposes a maximum limit to the circulating supply of the collection. Callers must ReapersGambit.approve() the WrappedReaper before attempting to mint. amountToStake The amount of $RG the caller wishes to lock in. maximumPrice Enable frontrun protection for the caller. Here, the caller can specify the maximum price to ensure the price of a token remains within a tolerable bound and has not been manipulated by searchers in an effort to pay an unexpectedly higher tribute.
|
function mint(uint256 amountToStake, uint256 maximumPrice) external nonReentrant returns (bool) {
uint256 currentSupply = totalSupply();
require(amountToStake >= _MIN_STAKE && amountToStake <= _MAX_STAKE && amountToStake <= maximumPrice, "WRG: invalid stake");
require(currentSupply < _maxSupply, "WRG: supply cap reached");
uint256 total = scythe(currentSupply, amountToStake);
require(total <= maximumPrice && total >= amountToStake, "WRG: frontrun protection");
Bar memory bar = Bar(msg.sender, block.number, _reapersGambit.KnowDeath(msg.sender), amountToStake, block.timestamp);
require(bar.deathBlock > bar.mintBlock && proximity(bar.deathBlock, bar.mintBlock) <= _GRACE_PERIOD, "cannot escape death");
_bars[_nextTokenId] = bar;
require(_reapersGambit.allowance(msg.sender, address(this)) >= total, "ERC20: insufficient allowance");
require(_reapersGambit.balanceOf(msg.sender) >= total, "ERC20: transfer amount exceeds balance");
require(_reapersGambit.transferFrom(msg.sender, address(this), amountToStake), "WRG: failed to transfer");
if (total > amountToStake)
require(_reapersGambit.transferFrom(msg.sender, address(0x000000000000000000000000000000000000dEaD), total - amountToStake), "WRG: failed to burn");
_safeMint(msg.sender, _nextTokenId++);
return true;
| 15,505,066 |
./partial_match/137/0xEC02799CF8EE0e975Ad4f2054Bc9E98eDB250702/sources/ChildERC1155.sol
|
called when tokens are deposited on root chain Should be callable only by ChildChainManager Should handle deposit by minting the required tokens for user Make sure minting is done only by this function user user address for whom deposit is being done depositData abi encoded ids array and amounts array/
|
function deposit(address user, bytes calldata depositData)
external
override
only(DEPOSITOR_ROLE)
{
(uint256[] memory ids, uint256[] memory amounts, bytes memory data) =
abi.decode(depositData, (uint256[], uint256[], bytes));
require(user != address(0x0), "ChildERC1155: INVALID_DEPOSIT_USER");
_mintBatch(user, ids, amounts, data);
}
| 3,510,612 |
// File: @chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
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-solidity/contracts/GSN/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return 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: contracts/access/Roles.sol
/**
* @title Roles
* @notice copied from openzeppelin-solidity
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: contracts/access/WhitelistAdminRole.sol
/**
* @title WhitelistAdminRole
* @notice copied from openzeppelin-solidity
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole is Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () internal {
_addWhitelistAdmin(_msgSender());
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(_msgSender());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
// File: contracts/access/WhitelistedRole.sol
/**
* @title WhitelistedRole
* @notice copied from openzeppelin-solidity
* @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
* it), and not Whitelisteds themselves.
*/
contract WhitelistedRole is Context, WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted() {
require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role");
_;
}
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
function addWhitelisted(address account) public onlyWhitelistAdmin {
_addWhitelisted(account);
}
function removeWhitelisted(address account) public onlyWhitelistAdmin {
_removeWhitelisted(account);
}
function renounceWhitelisted() public {
_removeWhitelisted(_msgSender());
}
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
}
// File: contracts/oracle/ICADConversionOracle.sol
/**
* @title ICADRateOracle
* @notice provides interface for converting USD stable coins to CAD
*/
interface ICADConversionOracle {
/**
* @notice convert USD amount to CAD amount
* @param amount amount of USD in 18 decimal places
* @return amount of CAD in 18 decimal places
*/
function usdToCad(uint256 amount) external view returns (uint256);
/**
* @notice convert Dai amount to CAD amount
* @param amount amount of dai in 18 decimal places
* @return amount of CAD in 18 decimal places
*/
function daiToCad(uint256 amount) external view returns (uint256);
/**
* @notice convert USDC amount to CAD amount
* @param amount amount of USDC in 6 decimal places
* @return amount of CAD in 18 decimal places
*/
function usdcToCad(uint256 amount) external view returns (uint256);
/**
* @notice convert USDT amount to CAD amount
* @param amount amount of USDT in 6 decimal places
* @return amount of CAD in 18 decimal places
*/
function usdtToCad(uint256 amount) external view returns (uint256);
/**
* @notice convert CAD amount to USD amount
* @param amount amount of CAD in 18 decimal places
* @return amount of USD in 18 decimal places
*/
function cadToUsd(uint256 amount) external view returns (uint256);
/**
* @notice convert CAD amount to Dai amount
* @param amount amount of CAD in 18 decimal places
* @return amount of Dai in 18 decimal places
*/
function cadToDai(uint256 amount) external view returns (uint256);
/**
* @notice convert CAD amount to USDC amount
* @param amount amount of CAD in 18 decimal places
* @return amount of USDC in 6 decimal places
*/
function cadToUsdc(uint256 amount) external view returns (uint256);
/**
* @notice convert CAD amount to USDT amount
* @param amount amount of CAD in 18 decimal places
* @return amount of USDT in 6 decimal places
*/
function cadToUsdt(uint256 amount) external view returns (uint256);
}
// File: contracts/oracle/ManagedCADChainlinkRateOracle.sol
/**
* @title ManagedCADChainlinkRateOracle
* @notice Provides a USD/CAD rate source managed by admin, and Chainlink powered DAI/USDC/USDT conversion rates.
* USDC is treated as always 1 USD, and used as anchor to calculate Dai and USDT rates
*/
contract ManagedCADChainlinkRateOracle is ICADConversionOracle, WhitelistedRole {
using SafeMath for uint256;
event ManagedRateUpdated(uint256 value, uint256 timestamp);
// exchange rate stored as an integer
uint256 public _USDToCADRate;
// specifies how many decimal places have been converted into integer
uint256 public _granularity;
// specifies the time the exchange was last updated
uint256 public _timestamp;
// Chainlink price feed for Dai/Eth pair
AggregatorV3Interface public daiEthPriceFeed;
// Chainlink price feed for USDC/Eth pair
AggregatorV3Interface public usdcEthPriceFeed;
// Chainlink price feed for USDT/Eth pair
AggregatorV3Interface public usdtEthPriceFeed;
constructor(
uint256 value,
uint256 granularity,
address daiEthAggregatorAddress,
address usdcEthAggregatorAddress,
address usdtEthAggregatorAddress
) public {
_USDToCADRate = value;
_granularity = granularity;
_timestamp = block.timestamp;
daiEthPriceFeed = AggregatorV3Interface(daiEthAggregatorAddress);
usdcEthPriceFeed = AggregatorV3Interface(usdcEthAggregatorAddress);
usdtEthPriceFeed = AggregatorV3Interface(usdtEthAggregatorAddress);
_addWhitelisted(msg.sender);
}
/**
* @notice admin can update the exchange rate
* @param value the new exchange rate
* @param granularity number of decimal places the exchange value is accurate to
* @return true if success
*/
function updateManagedRate(uint256 value, uint256 granularity) external onlyWhitelisted returns (bool) {
require(value > 0, "Exchange rate cannot be zero");
require(granularity > 0, "Granularity cannot be zero");
_USDToCADRate = value;
_granularity = granularity;
_timestamp = block.timestamp;
emit ManagedRateUpdated(value, granularity);
return true;
}
/**
* @notice return the current managed values
* @return latest USD to CAD exchange rate, granularity, and timestamp
*/
function getManagedRate() external view returns (uint256, uint256, uint256) {
return (_USDToCADRate, _granularity, _timestamp);
}
/**
* @notice convert USD amount to CAD amount
* @param amount amount of USD in 18 decimal places
* @return amount of CAD in 18 decimal places
*/
function usdToCad(uint256 amount) public view virtual override returns (uint256) {
return amount.mul(_USDToCADRate).div(10 ** _granularity);
}
/**
* @notice convert Dai amount to CAD amount
* @param amount amount of dai in 18 decimal places
* @return amount of CAD in 18 decimal places
*/
function daiToCad(uint256 amount) external view virtual override returns (uint256) {
(, int256 daiEthPrice, , uint256 daiEthTimeStamp,) = daiEthPriceFeed.latestRoundData();
require(daiEthTimeStamp > 0, "Dai Chainlink Oracle data temporarily incomplete");
require(daiEthPrice > 0, "Invalid Chainlink Oracle Dai price");
(, int256 usdcEthPrice, , uint256 usdcEthTimeStamp,) = usdcEthPriceFeed.latestRoundData();
require(usdcEthTimeStamp > 0, "USDC conversion Chainlink Oracle data temporarily incomplete");
require(usdcEthPrice > 0, "Invalid Chainlink Oracle USDC conversion price");
return amount.mul(_USDToCADRate).mul(uint256(daiEthPrice)).div(uint256(usdcEthPrice)).div(10 ** _granularity);
}
/**
* @notice convert USDC amount to CAD amount
* @param amount amount of USDC in 6 decimal places
* @return amount of CAD in 18 decimal places
*/
function usdcToCad(uint256 amount) external view virtual override returns (uint256) {
// USDT has 6 decimals
return usdToCad(amount.mul(1e12));
}
/**
* @notice convert USDT amount to CAD amount
* @param amount amount of USDT in 6 decimal places
* @return amount of CAD in 18 decimal places
*/
function usdtToCad(uint256 amount) external view virtual override returns (uint256) {
(, int256 usdtEthPrice, , uint256 usdtEthTimeStamp,) = usdtEthPriceFeed.latestRoundData();
require(usdtEthTimeStamp > 0, "USDT Chainlink Oracle data temporarily incomplete");
require(usdtEthPrice > 0, "Invalid Chainlink Oracle USDT price");
(, int256 usdcEthPrice, , uint256 usdcEthTimeStamp,) = usdcEthPriceFeed.latestRoundData();
require(usdcEthTimeStamp > 0, "USDC conversion Chainlink Oracle data temporarily incomplete");
require(usdcEthPrice > 0, "Invalid Chainlink Oracle USDC conversion price");
// USDT has 6 decimals
return amount.mul(1e12).mul(_USDToCADRate).mul(uint256(usdtEthPrice)).div(uint256(usdcEthPrice)).div(10 ** _granularity);
}
/**
* @notice convert CAD amount to USD amount
* @param amount amount of CAD in 18 decimal places
* @return amount of USD in 18 decimal places
*/
function cadToUsd(uint256 amount) public view virtual override returns (uint256) {
return amount.mul(10 ** _granularity).div(_USDToCADRate);
}
/**
* @notice convert CAD amount to Dai amount
* @param amount amount of CAD in 18 decimal places
* @return amount of Dai in 18 decimal places
*/
function cadToDai(uint256 amount) external view virtual override returns (uint256) {
(, int256 daiEthPrice, , uint256 daiEthTimeStamp,) = daiEthPriceFeed.latestRoundData();
require(daiEthTimeStamp > 0, "Dai Chainlink Oracle data temporarily incomplete");
require(daiEthPrice > 0, "Invalid Chainlink Oracle Dai price");
(, int256 usdcEthPrice, , uint256 usdcEthTimeStamp,) = usdcEthPriceFeed.latestRoundData();
require(usdcEthTimeStamp > 0, "USDC conversion Chainlink Oracle data temporarily incomplete");
require(usdcEthPrice > 0, "Invalid Chainlink Oracle USDC conversion price");
return amount.mul(10 ** _granularity).mul(uint256(usdcEthPrice)).div(uint256(daiEthPrice)).div(_USDToCADRate);
}
/**
* @notice convert CAD amount to USDC amount
* @param amount amount of CAD in 18 decimal places
* @return amount of USDC in 6 decimal places
*/
function cadToUsdc(uint256 amount) external view virtual override returns (uint256) {
return cadToUsd(amount).div(1e12);
}
/**
* @notice convert CAD amount to USDT amount
* @param amount amount of CAD in 18 decimal places
* @return amount of USDT in 6 decimal places
*/
function cadToUsdt(uint256 amount) external view virtual override returns (uint256) {
(, int256 usdtEthPrice, , uint256 usdtEthTimeStamp,) = usdtEthPriceFeed.latestRoundData();
require(usdtEthTimeStamp > 0, "USDT Chainlink Oracle data temporarily incomplete");
require(usdtEthPrice > 0, "Invalid Chainlink Oracle USDT price");
(, int256 usdcEthPrice, , uint256 usdcEthTimeStamp,) = usdcEthPriceFeed.latestRoundData();
require(usdcEthTimeStamp > 0, "USDC conversion Chainlink Oracle data temporarily incomplete");
require(usdcEthPrice > 0, "Invalid Chainlink Oracle USDC conversion price");
return amount.mul(10 ** _granularity).mul(uint256(usdcEthPrice)).div(uint256(usdtEthPrice)).div(_USDToCADRate).div(1e12);
}
}
|
return the current managed values return latest USD to CAD exchange rate, granularity, and timestamp/
|
function getManagedRate() external view returns (uint256, uint256, uint256) {
return (_USDToCADRate, _granularity, _timestamp);
}
| 295,931 |
./full_match/1/0x6f9140097Ab6278B41Cf9597a597030207b8D75d/sources/lib/seaport-core/src/lib/Verifiers.sol
|
Only revert if revertOnInvalid has been supplied as true.
|
function _verifyOrderStatus(
bytes32 orderHash,
OrderStatus storage orderStatus,
bool onlyAllowUnused,
bool revertOnInvalid
if (orderStatus.isCancelled) {
if (revertOnInvalid) {
_revertOrderIsCancelled(orderHash);
}
}
| 9,675,678 |
./full_match/1/0x35CB0fE6f49932A44f39934F47298E6D34680628/sources/contracts/pool/PoolConfiguration.sol
|
Function is used to update pool's warning utilization (only called by governor) warningUtilization_ New warning utilization of the pool
|
function setWarningUtilization(
uint256 warningUtilization_
) external onlyGovernor nonGTO(warningUtilization_) {
_accrueInterest();
warningUtilization = warningUtilization_;
_checkUtilization();
}
| 17,111,404 |
./partial_match/56/0x942151d7715d3f5097D6A1956C87a3ffd0C2Aa6f/sources/SousChef.sol
|
Update reward variables of the given pool to be up-to-date.
|
function updatePool() public {
if (block.number <= poolInfo.lastRewardBlock) {
return;
}
uint256 heatSupply = heat.balanceOf(address(this));
if (heatSupply == 0) {
poolInfo.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(poolInfo.lastRewardBlock, block.number);
uint256 tokenReward = multiplier.mul(rewardPerBlock);
poolInfo.accRewardPerShare = poolInfo.accRewardPerShare.add(tokenReward.mul(1e12).div(heatSupply));
poolInfo.lastRewardBlock = block.number;
}
| 11,269,067 |
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2020, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "@openzeppelin/contracts/utils/Address.sol";
import "arb-bridge-eth/contracts/libraries/BytesLib.sol";
import "arb-bridge-eth/contracts/libraries/ProxyUtil.sol";
import "arb-bridge-eth/contracts/libraries/AddressAliasHelper.sol";
import "../IArbToken.sol";
import "arb-bridge-peripherals/contracts/tokenbridge/arbitrum/L2ArbitrumMessenger.sol";
import "arb-bridge-peripherals/contracts/tokenbridge/libraries/gateway/GatewayMessageHandler.sol";
import "arb-bridge-peripherals/contracts/tokenbridge/libraries/gateway/TokenGateway.sol";
/**
* @title Common interface for gatways on Arbitrum messaging to L1.
*/
abstract contract L2ArbitrumGateway is L2ArbitrumMessenger, TokenGateway {
using Address for address;
uint256 public exitNum;
event DepositFinalized(address indexed l1Token, address indexed _from, address indexed _to, uint256 _amount);
event WithdrawalInitiated(address l1Token, address indexed _from, address indexed _to, uint256 indexed _l2ToL1Id, uint256 _exitNum, uint256 _amount);
modifier onlyCounterpartGateway() override {
require(msg.sender == counterpartGateway || AddressAliasHelper.undoL1ToL2Alias(msg.sender) == counterpartGateway, "ONLY_COUNTERPART_GATEWAY");
_;
}
function postUpgradeInit() external view {
// it is assumed the L2 Arbitrum Gateway contract is behind a Proxy controlled by a proxy admin
// this function can only be called by the proxy admin contract
address proxyAdmin = ProxyUtil.getProxyAdmin();
require(msg.sender == proxyAdmin, "NOT_FROM_ADMIN");
// this has no other logic since the current upgrade doesn't require this logic
}
function _initialize(address _l1Counterpart, address _router) internal virtual override {
TokenGateway._initialize(_l1Counterpart, _router);
// L1 gateway must have a router
require(_router != address(0), "BAD_ROUTER");
}
function createOutboundTx(
address,
uint256, /* _tokenAmount */
bytes memory
) internal pure virtual returns (uint256) {
return 0;
}
function getOutboundCalldata(
address _token,
address _from,
address _to,
uint256 _amount,
bytes memory _data
) public view override returns (bytes memory outboundCalldata) {
outboundCalldata = abi.encodeWithSelector(
TokenGateway.finalizeInboundTransfer.selector,
_token,
_from,
_to,
_amount,
GatewayMessageHandler.encodeFromL2GatewayMsg(exitNum, _data)
);
return outboundCalldata;
}
function outboundTransfer(
address _l1Token,
address _to,
uint256 _amount,
bytes calldata _data
) public payable virtual returns (bytes memory) {
return outboundTransfer(_l1Token, _to, _amount, 0, 0, _data);
}
function outboundTransfer(
address,
address,
uint256,
uint256, /* _maxGas */
uint256, /* _gasPriceBid */
bytes calldata
) public payable virtual override returns (bytes memory res) {
return abi.encode(0);
}
function triggerWithdrawal(
address,
address,
address,
uint256,
bytes memory
) internal pure returns (uint256) {
return 0;
}
function outboundEscrowTransfer(
address,
address,
uint256
) internal pure virtual returns (uint256 amountBurnt) {
return 0;
}
function inboundEscrowTransfer(
address _l2Address,
address _dest,
uint256 _amount,
bytes memory _data
) internal virtual {
// this method is virtual since different subclasses can handle escrow differently
IArbToken(_l2Address).bridgeMint(_dest, _amount, _data);
}
/**
* @notice Mint on L2 upon L1 deposit.
* If token not yet deployed and symbol/name/decimal data is included, deploys StandardArbERC20
* @dev Callable only by the L1ERC20Gateway.outboundTransfer method. For initial deployments of a token the L1 L1ERC20Gateway
* is expected to include the deployData. If not a L1 withdrawal is automatically triggered for the user
* @param _token L1 address of ERC20
* @param _from account that initiated the deposit in the L1
* @param _to account to be credited with the tokens in the L2 (can be the user's L2 account or a contract)
* @param _amount token amount to be minted to the user
* @param _data encoded symbol/name/decimal data for deploy, in addition to any additional callhook data
*/
function finalizeInboundTransfer(
address _token,
address _from,
address _to,
uint256 _amount,
bytes calldata _data
) external payable override onlyCounterpartGateway {
(, bytes memory callHookData) = GatewayMessageHandler.parseFromL1GatewayMsg(_data);
address expectedAddress = calculateL2TokenAddress(_token);
inboundEscrowTransfer(expectedAddress, _to, _amount, callHookData);
emit DepositFinalized(_token, _from, _to, _amount);
return;
}
// returns if function should halt after
function handleNoContract(
address _l1Token,
address expectedL2Address,
address _from,
address _to,
uint256 _amount,
bytes memory gatewayData
) internal virtual returns (bool shouldHalt);
}
|
this method is virtual since different subclasses can handle escrow differently
|
function inboundEscrowTransfer(
address _l2Address,
address _dest,
uint256 _amount,
bytes memory _data
) internal virtual {
IArbToken(_l2Address).bridgeMint(_dest, _amount, _data);
}
| 934,067 |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "./AllowListAccessControl.sol";
import "../vaults/roles/Governable.sol";
import "../interfaces/IAccessControlManager.sol";
/// @notice This contract will keep an registry for the access control policies that have been added, and check to see if any of them will allow a user to access to a particular vault.
/// A vault can either be a SingleAssetVault, or the staking contract.
contract AccessControlManager is IAccessControlManager, Governable {
/// @notice Emitted when a new policy is added
event AccessControlPolicyAdded(address indexed _policy);
/// @notice Emitted when a new policy is removed
event AccessControlPolicyRemoved(address indexed _policy);
// Add the library methods
using EnumerableSet for EnumerableSet.AddressSet;
// internal registry for all the enabled policies
EnumerableSet.AddressSet internal accessControlPolicies;
// solhint-disable-next-line no-empty-blocks
constructor(address _governance, address[] memory _policies) Governable(_governance) {
_addAccessControlPolicys(_policies);
}
/// @notice Enable the given access control policies. Can only be set by the governance
/// @param _policies The address of the access control policies
function addAccessControlPolicies(address[] calldata _policies) external onlyGovernance {
_addAccessControlPolicys(_policies);
}
/// @notice Disable the given access control policies. Can only be set by the governance
/// @param _policies The address of the access control policies
function removeAccessControlPolicies(address[] calldata _policies) external onlyGovernance {
_removeAccessControlPolicys(_policies);
}
/// @notice Returns the current enabled access control policies
/// @return the addresses of enabled access control policies
function getAccessControlPolicies() external view returns (address[] memory) {
return accessControlPolicies.values();
}
/// @notice Check if the given user has access to the given vault based on the current access control policies.
/// @param _user the user address
/// @param _vault the vault address. Can either be a SingleAssetVault or staking contract
/// @return will return true if any of the current policies allows access
function hasAccess(address _user, address _vault) external view returns (bool) {
return _hasAccess(_user, _vault);
}
// Had to use memory here instead of calldata as the function is
// used in the constructor
function _addAccessControlPolicys(address[] memory _policies) internal {
for (uint256 i = 0; i < _policies.length; i++) {
if (_policies[i] != address(0)) {
bool added = accessControlPolicies.add(_policies[i]);
if (added) {
emit AccessControlPolicyAdded(_policies[i]);
}
}
}
}
function _removeAccessControlPolicys(address[] memory _policies) internal {
for (uint256 i = 0; i < _policies.length; i++) {
if (_policies[i] != address(0)) {
bool removed = accessControlPolicies.remove(_policies[i]);
if (removed) {
emit AccessControlPolicyRemoved(_policies[i]);
}
}
}
}
function _hasAccess(address _user, address _vault) internal view returns (bool) {
require(_vault != address(0), "invalid vault address");
require(_user != address(0), "invalid user address");
// disable access if no policies are set
if (accessControlPolicies.length() == 0) {
return false;
}
bool userHasAccess = false;
for (uint256 i = 0; i < accessControlPolicies.length(); i++) {
if (IAccessControlPolicy(accessControlPolicies.at(i)).hasAccess(_user, _vault)) {
userHasAccess = true;
break;
}
}
return userHasAccess;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/IAccessControlPolicy.sol";
import "../vaults/roles/Governable.sol";
import "./PerVaultGatekeeper.sol";
contract AllowlistAccessControl is IAccessControlPolicy, PerVaultGatekeeper {
mapping(address => bool) public globalAccessMap;
mapping(address => mapping(address => bool)) public vaultAccessMap;
event GlobalAccessGranted(address indexed _user);
event GlobalAccessRemoved(address indexed _user);
event VaultAccessGranted(address indexed _user, address indexed _vault);
event VaultAccessRemoved(address indexed _user, address indexed _vault);
// solhint-disable-next-line no-empty-blocks
constructor(address _governance) PerVaultGatekeeper(_governance) {}
function allowGlobalAccess(address[] calldata _users) external onlyGovernance {
_updateGlobalAccess(_users, true);
}
function removeGlobalAccess(address[] calldata _users) external onlyGovernance {
_updateGlobalAccess(_users, false);
}
function allowVaultAccess(address[] calldata _users, address _vault) external {
_onlyGovernanceOrGatekeeper(_vault);
_updateAllowVaultAccess(_users, _vault, true);
}
function removeVaultAccess(address[] calldata _users, address _vault) external {
_onlyGovernanceOrGatekeeper(_vault);
_updateAllowVaultAccess(_users, _vault, false);
}
function _hasAccess(address _user, address _vault) internal view returns (bool) {
require(_user != address(0), "invalid user address");
require(_vault != address(0), "invalid vault address");
return globalAccessMap[_user] || vaultAccessMap[_user][_vault];
}
function hasAccess(address _user, address _vault) external view returns (bool) {
return _hasAccess(_user, _vault);
}
/// @dev updates the users global access
function _updateGlobalAccess(address[] calldata _users, bool _permission) internal {
for (uint256 i = 0; i < _users.length; i++) {
require(_users[i] != address(0), "invalid address");
/// @dev only update mappign if permissions are changed
if (globalAccessMap[_users[i]] != _permission) {
globalAccessMap[_users[i]] = _permission;
if (_permission) {
emit GlobalAccessGranted(_users[i]);
} else {
emit GlobalAccessRemoved(_users[i]);
}
}
}
}
function _updateAllowVaultAccess(
address[] calldata _users,
address _vault,
bool _permission
) internal {
for (uint256 i = 0; i < _users.length; i++) {
require(_users[i] != address(0), "invalid user address");
if (vaultAccessMap[_users[i]][_vault] != _permission) {
vaultAccessMap[_users[i]][_vault] = _permission;
if (_permission) {
emit VaultAccessGranted(_users[i], _vault);
} else {
emit VaultAccessRemoved(_users[i], _vault);
}
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
interface IGovernable {
function proposeGovernance(address _pendingGovernance) external;
function acceptGovernance() external;
}
abstract contract GovernableInternal {
event GovenanceUpdated(address _govenance);
event GovenanceProposed(address _pendingGovenance);
/// @dev This contract is used as part of the Vault contract and it is upgradeable.
/// which means any changes to the state variables could corrupt the data. Do not modify these at all.
/// @notice the address of the current governance
address public governance;
/// @notice the address of the pending governance
address public pendingGovernance;
/// @dev ensure msg.send is the governanace
modifier onlyGovernance() {
require(_getMsgSender() == governance, "governance only");
_;
}
/// @dev ensure msg.send is the pendingGovernance
modifier onlyPendingGovernance() {
require(_getMsgSender() == pendingGovernance, "pending governance only");
_;
}
/// @dev the deployer of the contract will be set as the initial governance
// solhint-disable-next-line func-name-mixedcase
function __Governable_init_unchained(address _governance) internal {
require(_getMsgSender() != _governance, "invalid address");
_updateGovernance(_governance);
}
///@notice propose a new governance of the vault. Only can be called by the existing governance.
///@param _pendingGovernance the address of the pending governance
function proposeGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "invalid address");
require(_pendingGovernance != governance, "already the governance");
pendingGovernance = _pendingGovernance;
emit GovenanceProposed(_pendingGovernance);
}
///@notice accept the proposal to be the governance of the vault. Only can be called by the pending governance.
function acceptGovernance() external onlyPendingGovernance {
_updateGovernance(pendingGovernance);
}
function _updateGovernance(address _pendingGovernance) internal {
governance = _pendingGovernance;
emit GovenanceUpdated(governance);
}
/// @dev provides an internal function to allow reduce the contract size
function _onlyGovernance() internal view {
require(_getMsgSender() == governance, "governance only");
}
function _getMsgSender() internal view virtual returns (address);
}
/// @dev Add a `governance` and a `pendingGovernance` role to the contract, and implements a 2-phased nominatiom process to change the governance.
/// Also provides a modifier to allow controlling access to functions of the contract.
contract Governable is Context, GovernableInternal {
constructor(address _governance) GovernableInternal() {
__Governable_init_unchained(_governance);
}
function _getMsgSender() internal view override returns (address) {
return _msgSender();
}
}
/// @dev ungradeable version of the {Governable} contract. Can be used as part of an upgradeable contract.
abstract contract GovernableUpgradeable is ContextUpgradeable, GovernableInternal {
// solhint-disable-next-line no-empty-blocks
constructor() {}
// solhint-disable-next-line func-name-mixedcase
function __Governable_init(address _governance) internal {
__Context_init();
__Governable_init_unchained(_governance);
}
// solhint-disable-next-line func-name-mixedcase
function _getMsgSender() internal view override returns (address) {
return _msgSender();
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
interface IAccessControlManager {
function hasAccess(address _user, address _vault) external view returns (bool);
}
// 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
pragma solidity =0.8.9;
interface IAccessControlPolicy {
function hasAccess(address _user, address _vault) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import "../interfaces/roles/IGatekeeperable.sol";
import "../vaults/roles/Governable.sol";
contract PerVaultGatekeeper is Governable {
// solhint-disable-next-line no-empty-blocks
constructor(address _governance) Governable(_governance) {}
/// @dev works with any contract that implements the IGatekeeperable interface.
function _onlyGovernanceOrGatekeeper(address _pool) internal view {
require(_pool != address(0), "!address");
address gatekeeper = IGatekeeperable(_pool).gatekeeper();
require(_msgSender() == governance || (gatekeeper != address(0) && _msgSender() == gatekeeper), "not authorised");
}
}
// 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 (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/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
pragma solidity =0.8.9;
interface IGatekeeperable {
function gatekeeper() external view returns (address);
}
|
Disable the given access control policies. Can only be set by the governance _policies The address of the access control policies
|
function removeAccessControlPolicies(address[] calldata _policies) external onlyGovernance {
_removeAccessControlPolicys(_policies);
}
| 13,777,745 |
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/math/FixedPoint.sol";
import "../../lib/helpers/InputHelpers.sol";
import "../../lib/helpers/TemporarilyPausable.sol";
import "../../lib/openzeppelin/ERC20.sol";
import "./WeightedMath.sol";
import "./WeightedOracleMath.sol";
import "./WeightedPool2TokensMiscData.sol";
import "./WeightedPoolUserDataHelpers.sol";
import "../BalancerPoolToken.sol";
import "../BasePoolAuthorization.sol";
import "../oracle/PoolPriceOracle.sol";
import "../oracle/Buffer.sol";
import "../../vault/interfaces/IMinimalSwapInfoPool.sol";
import "../IPriceOracle.sol";
contract WeightedPool2Tokens is
IMinimalSwapInfoPool,
IPriceOracle,
BasePoolAuthorization,
BalancerPoolToken,
TemporarilyPausable,
PoolPriceOracle,
WeightedMath,
WeightedOracleMath
{
using FixedPoint for uint256;
using WeightedPoolUserDataHelpers for bytes;
using WeightedPool2TokensMiscData for bytes32;
uint256 private constant _MINIMUM_BPT = 1e6;
// 1e18 corresponds to 1.0, or a 100% fee
uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001%
uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10%
// The swap fee is internally stored using 64 bits, which is enough to represent _MAX_SWAP_FEE_PERCENTAGE.
bytes32 internal _miscData;
uint256 private _lastInvariant;
IVault private immutable _vault;
bytes32 private immutable _poolId;
IERC20 internal immutable _token0;
IERC20 internal immutable _token1;
uint256 private immutable _normalizedWeight0;
uint256 private immutable _normalizedWeight1;
// The protocol fees will always be charged using the token associated with the max weight in the pool.
// Since these Pools will register tokens only once, we can assume this index will be constant.
uint256 private immutable _maxWeightTokenIndex;
// All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will
// not change throughout its lifetime, and store the corresponding scaling factor for each at construction time.
// These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported.
uint256 internal immutable _scalingFactor0;
uint256 internal immutable _scalingFactor1;
event OracleEnabledChanged(bool enabled);
event SwapFeePercentageChanged(uint256 swapFeePercentage);
modifier onlyVault(bytes32 poolId) {
_require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT);
_require(poolId == getPoolId(), Errors.INVALID_POOL_ID);
_;
}
struct NewPoolParams {
IVault vault;
string name;
string symbol;
IERC20 token0;
IERC20 token1;
uint256 normalizedWeight0;
uint256 normalizedWeight1;
uint256 swapFeePercentage;
uint256 pauseWindowDuration;
uint256 bufferPeriodDuration;
bool oracleEnabled;
address owner;
}
constructor(NewPoolParams memory params)
// Base Pools are expected to be deployed using factories. By using the factory address as the action
// disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for
// simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in
// any Pool created by the same factory), while still making action identifiers unique among different factories
// if the selectors match, preventing accidental errors.
Authentication(bytes32(uint256(msg.sender)))
BalancerPoolToken(params.name, params.symbol)
BasePoolAuthorization(params.owner)
TemporarilyPausable(params.pauseWindowDuration, params.bufferPeriodDuration)
{
_setOracleEnabled(params.oracleEnabled);
_setSwapFeePercentage(params.swapFeePercentage);
bytes32 poolId = params.vault.registerPool(IVault.PoolSpecialization.TWO_TOKEN);
// Pass in zero addresses for Asset Managers
IERC20[] memory tokens = new IERC20[](2);
tokens[0] = params.token0;
tokens[1] = params.token1;
params.vault.registerTokens(poolId, tokens, new address[](2));
// Set immutable state variables - these cannot be read from during construction
_vault = params.vault;
_poolId = poolId;
_token0 = params.token0;
_token1 = params.token1;
_scalingFactor0 = _computeScalingFactor(params.token0);
_scalingFactor1 = _computeScalingFactor(params.token1);
// Ensure each normalized weight is above them minimum and find the token index of the maximum weight
_require(params.normalizedWeight0 >= _MIN_WEIGHT, Errors.MIN_WEIGHT);
_require(params.normalizedWeight1 >= _MIN_WEIGHT, Errors.MIN_WEIGHT);
// Ensure that the normalized weights sum to ONE
uint256 normalizedSum = params.normalizedWeight0.add(params.normalizedWeight1);
_require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT);
_normalizedWeight0 = params.normalizedWeight0;
_normalizedWeight1 = params.normalizedWeight1;
_maxWeightTokenIndex = params.normalizedWeight0 >= params.normalizedWeight1 ? 0 : 1;
}
// Getters / Setters
function getVault() public view returns (IVault) {
return _vault;
}
function getPoolId() public view returns (bytes32) {
return _poolId;
}
function getMiscData()
external
view
returns (
int256 logInvariant,
int256 logTotalSupply,
uint256 oracleSampleCreationTimestamp,
uint256 oracleIndex,
bool oracleEnabled,
uint256 swapFeePercentage
)
{
bytes32 miscData = _miscData;
logInvariant = miscData.logInvariant();
logTotalSupply = miscData.logTotalSupply();
oracleSampleCreationTimestamp = miscData.oracleSampleCreationTimestamp();
oracleIndex = miscData.oracleIndex();
oracleEnabled = miscData.oracleEnabled();
swapFeePercentage = miscData.swapFeePercentage();
}
function getSwapFeePercentage() public view returns (uint256) {
return _miscData.swapFeePercentage();
}
// Caller must be approved by the Vault's Authorizer
function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused {
_setSwapFeePercentage(swapFeePercentage);
}
function _setSwapFeePercentage(uint256 swapFeePercentage) private {
_require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE);
_require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE);
_miscData = _miscData.setSwapFeePercentage(swapFeePercentage);
emit SwapFeePercentageChanged(swapFeePercentage);
}
/**
* @dev Balancer Governance can always enable the Oracle, even if it was originally not enabled. This allows for
* Pools that unexpectedly drive much more volume and liquidity than expected to serve as Price Oracles.
*
* Note that the Oracle can only be enabled - it can never be disabled.
*/
function enableOracle() external whenNotPaused authenticate {
_setOracleEnabled(true);
// Cache log invariant and supply only if the pool was initialized
if (totalSupply() > 0) {
_cacheInvariantAndSupply();
}
}
function _setOracleEnabled(bool enabled) internal {
_miscData = _miscData.setOracleEnabled(enabled);
emit OracleEnabledChanged(enabled);
}
// Caller must be approved by the Vault's Authorizer
function setPaused(bool paused) external authenticate {
_setPaused(paused);
}
function getNormalizedWeights() external view returns (uint256[] memory) {
return _normalizedWeights();
}
function _normalizedWeights() internal view virtual returns (uint256[] memory) {
uint256[] memory normalizedWeights = new uint256[](2);
normalizedWeights[0] = _normalizedWeights(true);
normalizedWeights[1] = _normalizedWeights(false);
return normalizedWeights;
}
function _normalizedWeights(bool token0) internal view virtual returns (uint256) {
return token0 ? _normalizedWeight0 : _normalizedWeight1;
}
function getLastInvariant() external view returns (uint256) {
return _lastInvariant;
}
/**
* @dev Returns the current value of the invariant.
*/
function getInvariant() public view returns (uint256) {
(, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId());
// Since the Pool hooks always work with upscaled balances, we manually
// upscale here for consistency
_upscaleArray(balances);
uint256[] memory normalizedWeights = _normalizedWeights();
return WeightedMath._calculateInvariant(normalizedWeights, balances);
}
// Swap Hooks
function onSwap(
SwapRequest memory request,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) external virtual override whenNotPaused onlyVault(request.poolId) returns (uint256) {
bool tokenInIsToken0 = request.tokenIn == _token0;
uint256 scalingFactorTokenIn = _scalingFactor(tokenInIsToken0);
uint256 scalingFactorTokenOut = _scalingFactor(!tokenInIsToken0);
uint256 normalizedWeightIn = _normalizedWeights(tokenInIsToken0);
uint256 normalizedWeightOut = _normalizedWeights(!tokenInIsToken0);
// All token amounts are upscaled.
balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn);
balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut);
// Update price oracle with the pre-swap balances
_updateOracle(
request.lastChangeBlock,
tokenInIsToken0 ? balanceTokenIn : balanceTokenOut,
tokenInIsToken0 ? balanceTokenOut : balanceTokenIn
);
if (request.kind == IVault.SwapKind.GIVEN_IN) {
// Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis.
// This is amount - fee amount, so we round up (favoring a higher fee amount).
uint256 feeAmount = request.amount.mulUp(getSwapFeePercentage());
request.amount = _upscale(request.amount.sub(feeAmount), scalingFactorTokenIn);
uint256 amountOut = _onSwapGivenIn(
request,
balanceTokenIn,
balanceTokenOut,
normalizedWeightIn,
normalizedWeightOut
);
// amountOut tokens are exiting the Pool, so we round down.
return _downscaleDown(amountOut, scalingFactorTokenOut);
} else {
request.amount = _upscale(request.amount, scalingFactorTokenOut);
uint256 amountIn = _onSwapGivenOut(
request,
balanceTokenIn,
balanceTokenOut,
normalizedWeightIn,
normalizedWeightOut
);
// amountIn tokens are entering the Pool, so we round up.
amountIn = _downscaleUp(amountIn, scalingFactorTokenIn);
// Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis.
// This is amount + fee amount, so we round up (favoring a higher fee amount).
return amountIn.divUp(getSwapFeePercentage().complement());
}
}
function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut,
uint256 normalizedWeightIn,
uint256 normalizedWeightOut
) private pure returns (uint256) {
// Swaps are disabled while the contract is paused.
return
WeightedMath._calcOutGivenIn(
currentBalanceTokenIn,
normalizedWeightIn,
currentBalanceTokenOut,
normalizedWeightOut,
swapRequest.amount
);
}
function _onSwapGivenOut(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut,
uint256 normalizedWeightIn,
uint256 normalizedWeightOut
) private pure returns (uint256) {
// Swaps are disabled while the contract is paused.
return
WeightedMath._calcInGivenOut(
currentBalanceTokenIn,
normalizedWeightIn,
currentBalanceTokenOut,
normalizedWeightOut,
swapRequest.amount
);
}
// Join Hook
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
)
external
virtual
override
onlyVault(poolId)
whenNotPaused
returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts)
{
// All joins, including initializations, are disabled while the contract is paused.
uint256 bptAmountOut;
if (totalSupply() == 0) {
(bptAmountOut, amountsIn) = _onInitializePool(poolId, sender, recipient, userData);
// On initialization, we lock _MINIMUM_BPT by minting it for the zero address. This BPT acts as a minimum
// as it will never be burned, which reduces potential issues with rounding, and also prevents the Pool from
// ever being fully drained.
_require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT);
_mintPoolTokens(address(0), _MINIMUM_BPT);
_mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT);
// amountsIn are amounts entering the Pool, so we round up.
_downscaleUpArray(amountsIn);
// There are no due protocol fee amounts during initialization
dueProtocolFeeAmounts = new uint256[](2);
} else {
_upscaleArray(balances);
// Update price oracle with the pre-join balances
_updateOracle(lastChangeBlock, balances[0], balances[1]);
(bptAmountOut, amountsIn, dueProtocolFeeAmounts) = _onJoinPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData
);
// Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it.
_mintPoolTokens(recipient, bptAmountOut);
// amountsIn are amounts entering the Pool, so we round up.
_downscaleUpArray(amountsIn);
// dueProtocolFeeAmounts are amounts exiting the Pool, so we round down.
_downscaleDownArray(dueProtocolFeeAmounts);
}
// Update cached total supply and invariant using the results after the join that will be used for future
// oracle updates.
_cacheInvariantAndSupply();
}
/**
* @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero.
*
* Returns the amount of BPT to mint, and the token amounts the Pool will receive in return.
*
* Minted BPT will be sent to `recipient`, except for _MINIMUM_BPT, which will be deducted from this amount and sent
* to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP from
* ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire Pool's
* lifetime.
*
* The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will
* be downscaled (rounding up) before being returned to the Vault.
*/
function _onInitializePool(
bytes32,
address,
address,
bytes memory userData
) private returns (uint256, uint256[] memory) {
WeightedPool.JoinKind kind = userData.joinKind();
_require(kind == WeightedPool.JoinKind.INIT, Errors.UNINITIALIZED);
uint256[] memory amountsIn = userData.initialAmountsIn();
InputHelpers.ensureInputLengthMatch(amountsIn.length, 2);
_upscaleArray(amountsIn);
uint256[] memory normalizedWeights = _normalizedWeights();
uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn);
// Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more
// consistent in Pools with similar compositions but different number of tokens.
uint256 bptAmountOut = Math.mul(invariantAfterJoin, 2);
_lastInvariant = invariantAfterJoin;
return (bptAmountOut, amountsIn);
}
/**
* @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`).
*
* Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of
* tokens to pay in protocol swap fees.
*
* Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when
* performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely.
*
* Minted BPT will be sent to `recipient`.
*
* The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will
* be downscaled (rounding up) before being returned to the Vault.
*
* Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These
* amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault.
*/
function _onJoinPool(
bytes32,
address,
address,
uint256[] memory balances,
uint256,
uint256 protocolSwapFeePercentage,
bytes memory userData
)
private
returns (
uint256,
uint256[] memory,
uint256[] memory
)
{
uint256[] memory normalizedWeights = _normalizedWeights();
// Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join
// or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas
// computing them on each individual swap
uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances);
uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(
balances,
normalizedWeights,
_lastInvariant,
invariantBeforeJoin,
protocolSwapFeePercentage
);
// Update current balances by subtracting the protocol fee amounts
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub);
(uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData);
// Update the invariant with the balances the Pool will have after the join, in order to compute the
// protocol swap fee amounts due in future joins and exits.
_mutateAmounts(balances, amountsIn, FixedPoint.add);
_lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances);
return (bptAmountOut, amountsIn, dueProtocolFeeAmounts);
}
function _doJoin(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
WeightedPool.JoinKind kind = userData.joinKind();
if (kind == WeightedPool.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) {
return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData);
} else if (kind == WeightedPool.JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) {
return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData);
} else {
_revert(Errors.UNHANDLED_JOIN_KIND);
}
}
function _joinExactTokensInForBPTOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
(uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut();
InputHelpers.ensureInputLengthMatch(amountsIn.length, 2);
_upscaleArray(amountsIn);
uint256 bptAmountOut = WeightedMath._calcBptOutGivenExactTokensIn(
balances,
normalizedWeights,
amountsIn,
totalSupply(),
getSwapFeePercentage()
);
_require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT);
return (bptAmountOut, amountsIn);
}
function _joinTokenInForExactBPTOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
(uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut();
// Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`.
_require(tokenIndex < 2, Errors.OUT_OF_BOUNDS);
uint256[] memory amountsIn = new uint256[](2);
amountsIn[tokenIndex] = WeightedMath._calcTokenInGivenExactBptOut(
balances[tokenIndex],
normalizedWeights[tokenIndex],
bptAmountOut,
totalSupply(),
getSwapFeePercentage()
);
return (bptAmountOut, amountsIn);
}
// Exit Hook
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
_upscaleArray(balances);
(uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData
);
// Note we no longer use `balances` after calling `_onExitPool`, which may mutate it.
_burnPoolTokens(sender, bptAmountIn);
// Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down.
_downscaleDownArray(amountsOut);
_downscaleDownArray(dueProtocolFeeAmounts);
// Update cached total supply and invariant using the results after the exit that will be used for future
// oracle updates, only if the pool was not paused (to minimize code paths taken while paused).
if (_isNotPaused()) {
_cacheInvariantAndSupply();
}
return (amountsOut, dueProtocolFeeAmounts);
}
/**
* @dev Called whenever the Pool is exited.
*
* Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and
* the number of tokens to pay in protocol swap fees.
*
* Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when
* performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely.
*
* BPT will be burnt from `sender`.
*
* The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled
* (rounding down) before being returned to the Vault.
*
* Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These
* amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault.
*/
function _onExitPool(
bytes32,
address,
address,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
)
private
returns (
uint256 bptAmountIn,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
)
{
// Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens
// out) remain functional.
uint256[] memory normalizedWeights = _normalizedWeights();
if (_isNotPaused()) {
// Update price oracle with the pre-exit balances
_updateOracle(lastChangeBlock, balances[0], balances[1]);
// Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous
// join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids
// spending gas calculating the fees on each individual swap.
uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances);
dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(
balances,
normalizedWeights,
_lastInvariant,
invariantBeforeExit,
protocolSwapFeePercentage
);
// Update current balances by subtracting the protocol fee amounts
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub);
} else {
// If the contract is paused, swap protocol fee amounts are not charged and the oracle is not updated
// to avoid extra calculations and reduce the potential for errors.
dueProtocolFeeAmounts = new uint256[](2);
}
(bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData);
// Update the invariant with the balances the Pool will have after the exit, in order to compute the
// protocol swap fees due in future joins and exits.
_mutateAmounts(balances, amountsOut, FixedPoint.sub);
_lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances);
return (bptAmountIn, amountsOut, dueProtocolFeeAmounts);
}
function _doExit(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
WeightedPool.ExitKind kind = userData.exitKind();
if (kind == WeightedPool.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) {
return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData);
} else if (kind == WeightedPool.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) {
return _exitExactBPTInForTokensOut(balances, userData);
} else {
// ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT
return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData);
}
}
function _exitExactBPTInForTokenOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view whenNotPaused returns (uint256, uint256[] memory) {
// This exit function is disabled if the contract is paused.
(uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut();
// Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
_require(tokenIndex < 2, Errors.OUT_OF_BOUNDS);
// We exit in a single token, so we initialize amountsOut with zeros
uint256[] memory amountsOut = new uint256[](2);
// And then assign the result to the selected token
amountsOut[tokenIndex] = WeightedMath._calcTokenOutGivenExactBptIn(
balances[tokenIndex],
normalizedWeights[tokenIndex],
bptAmountIn,
totalSupply(),
getSwapFeePercentage()
);
return (bptAmountIn, amountsOut);
}
function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData)
private
view
returns (uint256, uint256[] memory)
{
// This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted
// in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency.
// This particular exit function is the only one that remains available because it is the simplest one, and
// therefore the one with the lowest likelihood of errors.
uint256 bptAmountIn = userData.exactBptInForTokensOut();
// Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply());
return (bptAmountIn, amountsOut);
}
function _exitBPTInForExactTokensOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view whenNotPaused returns (uint256, uint256[] memory) {
// This exit function is disabled if the contract is paused.
(uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut();
InputHelpers.ensureInputLengthMatch(amountsOut.length, 2);
_upscaleArray(amountsOut);
uint256 bptAmountIn = WeightedMath._calcBptInGivenExactTokensOut(
balances,
normalizedWeights,
amountsOut,
totalSupply(),
getSwapFeePercentage()
);
_require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT);
return (bptAmountIn, amountsOut);
}
// Oracle functions
function getLargestSafeQueryWindow() external pure override returns (uint256) {
return 34 hours;
}
function getLatest(Variable variable) external view override returns (uint256) {
int256 instantValue = _getInstantValue(variable, _miscData.oracleIndex());
return _fromLowResLog(instantValue);
}
function getTimeWeightedAverage(OracleAverageQuery[] memory queries)
external
view
override
returns (uint256[] memory results)
{
results = new uint256[](queries.length);
uint256 oracleIndex = _miscData.oracleIndex();
OracleAverageQuery memory query;
for (uint256 i = 0; i < queries.length; ++i) {
query = queries[i];
_require(query.secs != 0, Errors.ORACLE_BAD_SECS);
int256 beginAccumulator = _getPastAccumulator(query.variable, oracleIndex, query.ago + query.secs);
int256 endAccumulator = _getPastAccumulator(query.variable, oracleIndex, query.ago);
results[i] = _fromLowResLog((endAccumulator - beginAccumulator) / int256(query.secs));
}
}
function getPastAccumulators(OracleAccumulatorQuery[] memory queries)
external
view
override
returns (int256[] memory results)
{
results = new int256[](queries.length);
uint256 oracleIndex = _miscData.oracleIndex();
OracleAccumulatorQuery memory query;
for (uint256 i = 0; i < queries.length; ++i) {
query = queries[i];
results[i] = _getPastAccumulator(query.variable, oracleIndex, query.ago);
}
}
/**
* @dev Updates the Price Oracle based on the Pool's current state (balances, BPT supply and invariant). Must be
* called on *all* state-changing functions with the balances *before* the state change happens, and with
* `lastChangeBlock` as the number of the block in which any of the balances last changed.
*/
function _updateOracle(
uint256 lastChangeBlock,
uint256 balanceToken0,
uint256 balanceToken1
) internal {
bytes32 miscData = _miscData;
if (miscData.oracleEnabled() && block.number > lastChangeBlock) {
int256 logSpotPrice = WeightedOracleMath._calcLogSpotPrice(
_normalizedWeight0,
balanceToken0,
_normalizedWeight1,
balanceToken1
);
int256 logBPTPrice = WeightedOracleMath._calcLogBPTPrice(
_normalizedWeight0,
balanceToken0,
miscData.logTotalSupply()
);
uint256 oracleCurrentIndex = miscData.oracleIndex();
uint256 oracleCurrentSampleInitialTimestamp = miscData.oracleSampleCreationTimestamp();
uint256 oracleUpdatedIndex = _processPriceData(
oracleCurrentSampleInitialTimestamp,
oracleCurrentIndex,
logSpotPrice,
logBPTPrice,
miscData.logInvariant()
);
if (oracleCurrentIndex != oracleUpdatedIndex) {
// solhint-disable not-rely-on-time
miscData = miscData.setOracleIndex(oracleUpdatedIndex);
miscData = miscData.setOracleSampleCreationTimestamp(block.timestamp);
_miscData = miscData;
}
}
}
/**
* @dev Stores the logarithm of the invariant and BPT total supply, to be later used in each oracle update. Because
* it is stored in miscData, which is read in all operations (including swaps), this saves gas by not requiring to
* compute or read these values when updating the oracle.
*
* This function must be called by all actions that update the invariant and BPT supply (joins and exits). Swaps
* also alter the invariant due to collected swap fees, but this growth is considered negligible and not accounted
* for.
*/
function _cacheInvariantAndSupply() internal {
bytes32 miscData = _miscData;
if (miscData.oracleEnabled()) {
miscData = miscData.setLogInvariant(WeightedOracleMath._toLowResLog(_lastInvariant));
miscData = miscData.setLogTotalSupply(WeightedOracleMath._toLowResLog(totalSupply()));
_miscData = miscData;
}
}
// Query functions
/**
* @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `sender` would have to supply.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryJoin(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptOut, uint256[] memory amountsIn) {
InputHelpers.ensureInputLengthMatch(balances.length, 2);
_queryAction(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData,
_onJoinPool,
_downscaleUpArray
);
// The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement,
// and we don't need to return anything here - it just silences compiler warnings.
return (bptOut, amountsIn);
}
/**
* @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `recipient` would receive.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryExit(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptIn, uint256[] memory amountsOut) {
InputHelpers.ensureInputLengthMatch(balances.length, 2);
_queryAction(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData,
_onExitPool,
_downscaleDownArray
);
// The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement,
// and we don't need to return anything here - it just silences compiler warnings.
return (bptIn, amountsOut);
}
// Helpers
function _getDueProtocolFeeAmounts(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256 previousInvariant,
uint256 currentInvariant,
uint256 protocolSwapFeePercentage
) private view returns (uint256[] memory) {
// Initialize with zeros
uint256[] memory dueProtocolFeeAmounts = new uint256[](2);
// Early return if the protocol swap fee percentage is zero, saving gas.
if (protocolSwapFeePercentage == 0) {
return dueProtocolFeeAmounts;
}
// The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the
// token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool.
dueProtocolFeeAmounts[_maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount(
balances[_maxWeightTokenIndex],
normalizedWeights[_maxWeightTokenIndex],
previousInvariant,
currentInvariant,
protocolSwapFeePercentage
);
return dueProtocolFeeAmounts;
}
/**
* @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`.
*
* Equivalent to `amounts = amounts.map(mutation)`.
*/
function _mutateAmounts(
uint256[] memory toMutate,
uint256[] memory arguments,
function(uint256, uint256) pure returns (uint256) mutation
) private pure {
toMutate[0] = mutation(toMutate[0], arguments[0]);
toMutate[1] = mutation(toMutate[1], arguments[1]);
}
/**
* @dev This function returns the appreciation of one BPT relative to the
* underlying tokens. This starts at 1 when the pool is created and grows over time
*/
function getRate() public view returns (uint256) {
// The initial BPT supply is equal to the invariant times the number of tokens.
return Math.mul(getInvariant(), 2).divDown(totalSupply());
}
// Scaling
/**
* @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if
* it had 18 decimals.
*/
function _computeScalingFactor(IERC20 token) private view returns (uint256) {
// Tokens that don't implement the `decimals` method are not supported.
uint256 tokenDecimals = ERC20(address(token)).decimals();
// Tokens with more than 18 decimals are not supported.
uint256 decimalsDifference = Math.sub(18, tokenDecimals);
return 10**decimalsDifference;
}
/**
* @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the
* Pool.
*/
function _scalingFactor(bool token0) internal view returns (uint256) {
return token0 ? _scalingFactor0 : _scalingFactor1;
}
/**
* @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed
* scaling or not.
*/
function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
return Math.mul(amount, scalingFactor);
}
/**
* @dev Same as `_upscale`, but for an entire array (of two elements). This function does not return anything, but
* instead *mutates* the `amounts` array.
*/
function _upscaleArray(uint256[] memory amounts) internal view {
amounts[0] = Math.mul(amounts[0], _scalingFactor(true));
amounts[1] = Math.mul(amounts[1], _scalingFactor(false));
}
/**
* @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on
* whether it needed scaling or not. The result is rounded down.
*/
function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
return Math.divDown(amount, scalingFactor);
}
/**
* @dev Same as `_downscaleDown`, but for an entire array (of two elements). This function does not return anything,
* but instead *mutates* the `amounts` array.
*/
function _downscaleDownArray(uint256[] memory amounts) internal view {
amounts[0] = Math.divDown(amounts[0], _scalingFactor(true));
amounts[1] = Math.divDown(amounts[1], _scalingFactor(false));
}
/**
* @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on
* whether it needed scaling or not. The result is rounded up.
*/
function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
return Math.divUp(amount, scalingFactor);
}
/**
* @dev Same as `_downscaleUp`, but for an entire array (of two elements). This function does not return anything,
* but instead *mutates* the `amounts` array.
*/
function _downscaleUpArray(uint256[] memory amounts) internal view {
amounts[0] = Math.divUp(amounts[0], _scalingFactor(true));
amounts[1] = Math.divUp(amounts[1], _scalingFactor(false));
}
function _getAuthorizer() internal view override returns (IAuthorizer) {
// Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which
// accounts can call permissioned functions: for example, to perform emergency pauses.
// If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under
// Governance control.
return getVault().getAuthorizer();
}
function _queryAction(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData,
function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory)
internal
returns (uint256, uint256[] memory, uint256[] memory) _action,
function(uint256[] memory) internal view _downscaleArray
) private {
// This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed
// explanation.
if (msg.sender != address(this)) {
// We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of
// the preceding if statement will be executed instead.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(msg.data);
// solhint-disable-next-line no-inline-assembly
assembly {
// This call should always revert to decode the bpt and token amounts from the revert reason
switch success
case 0 {
// Note we are manually writing the memory slot 0. We can safely overwrite whatever is
// stored there as we take full control of the execution and then immediately return.
// We copy the first 4 bytes to check if it matches with the expected signature, otherwise
// there was another revert reason and we should forward it.
returndatacopy(0, 0, 0x04)
let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
// If the first 4 bytes don't match with the expected signature, we forward the revert reason.
if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
// The returndata contains the signature, followed by the raw memory representation of the
// `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded
// representation of these.
// An ABI-encoded response will include one additional field to indicate the starting offset of
// the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the
// returndata.
//
// In returndata:
// [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ]
// [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ]
//
// We now need to return (ABI-encoded values):
// [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ]
// [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ]
// We copy 32 bytes for the `bptAmount` from returndata into memory.
// Note that we skip the first 4 bytes for the error signature
returndatacopy(0, 0x04, 32)
// The offsets are 32-bytes long, so the array of `tokenAmounts` will start after
// the initial 64 bytes.
mstore(0x20, 64)
// We now copy the raw memory array for the `tokenAmounts` from returndata into memory.
// Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also
// skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount.
returndatacopy(0x40, 0x24, sub(returndatasize(), 36))
// We finally return the ABI-encoded uint256 and the array, which has a total length equal to
// the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the
// error signature.
return(0, add(returndatasize(), 28))
}
default {
// This call should always revert, but we fail nonetheless if that didn't happen
invalid()
}
}
} else {
_upscaleArray(balances);
(uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData
);
_downscaleArray(tokenAmounts);
// solhint-disable-next-line no-inline-assembly
assembly {
// We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of
// a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values
// Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32
let size := mul(mload(tokenAmounts), 32)
// We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there
// will be at least one available slot due to how the memory scratch space works.
// We can safely overwrite whatever is stored in this slot as we will revert immediately after that.
let start := sub(tokenAmounts, 0x20)
mstore(start, bptAmount)
// We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb
// We use the previous slot to `bptAmount`.
mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb)
start := sub(start, 0x04)
// When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return
// the `bptAmount`, the array length, and the error signature.
revert(start, add(size, 68))
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "./LogExpMath.sol";
import "../helpers/BalancerErrors.sol";
/* solhint-disable private-vars-leading-underscore */
library FixedPoint {
uint256 internal constant ONE = 1e18; // 18 decimal places
uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14)
// Minimum base for the power function when the exponent is 'free' (larger than ONE).
uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18;
function add(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
return product / ONE;
}
function mulUp(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
if (product == 0) {
return 0;
} else {
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((product - 1) / ONE) + 1;
}
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
return aInflated / b;
}
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((aInflated - 1) / b) + 1;
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above
* the true value (that is, the error function expected - actual is always positive).
*/
function powDown(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
if (raw < maxError) {
return 0;
} else {
return sub(raw, maxError);
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below
* the true value (that is, the error function expected - actual is always negative).
*/
function powUp(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
return add(raw, maxError);
}
/**
* @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1.
*
* Useful when computing the complement for values with some level of relative error, as it strips this error and
* prevents intermediate negative values.
*/
function complement(uint256 x) internal pure returns (uint256) {
return (x < ONE) ? (ONE - x) : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "../openzeppelin/IERC20.sol";
import "./BalancerErrors.sol";
import "../../vault/interfaces/IAsset.sol";
library InputHelpers {
function ensureInputLengthMatch(uint256 a, uint256 b) internal pure {
_require(a == b, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureInputLengthMatch(
uint256 a,
uint256 b,
uint256 c
) internal pure {
_require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureArrayIsSorted(IAsset[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(IERC20[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(address[] memory array) internal pure {
if (array.length < 2) {
return;
}
address previous = array[0];
for (uint256 i = 1; i < array.length; ++i) {
address current = array[i];
_require(previous < current, Errors.UNSORTED_ARRAY);
previous = current;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "./BalancerErrors.sol";
import "./ITemporarilyPausable.sol";
/**
* @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be
* used as an emergency switch in case a security vulnerability or threat is identified.
*
* The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be
* unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets
* system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful
* analysis later determines there was a false alarm.
*
* If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional
* Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time
* to react to an emergency, even if the threat is discovered shortly before the Pause Window expires.
*
* Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is
* irreversible.
*/
abstract contract TemporarilyPausable is ITemporarilyPausable {
// The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy.
// solhint-disable not-rely-on-time
uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days;
uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days;
uint256 private immutable _pauseWindowEndTime;
uint256 private immutable _bufferPeriodEndTime;
bool private _paused;
constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) {
_require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION);
_require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION);
uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration;
_pauseWindowEndTime = pauseWindowEndTime;
_bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration;
}
/**
* @dev Reverts if the contract is paused.
*/
modifier whenNotPaused() {
_ensureNotPaused();
_;
}
/**
* @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer
* Period.
*/
function getPausedState()
external
view
override
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
)
{
paused = !_isNotPaused();
pauseWindowEndTime = _getPauseWindowEndTime();
bufferPeriodEndTime = _getBufferPeriodEndTime();
}
/**
* @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and
* unpaused until the end of the Buffer Period.
*
* Once the Buffer Period expires, this function reverts unconditionally.
*/
function _setPaused(bool paused) internal {
if (paused) {
_require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED);
} else {
_require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED);
}
_paused = paused;
emit PausedStateChanged(paused);
}
/**
* @dev Reverts if the contract is paused.
*/
function _ensureNotPaused() internal view {
_require(_isNotPaused(), Errors.PAUSED);
}
/**
* @dev Returns true if the contract is unpaused.
*
* Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no
* longer accessed.
*/
function _isNotPaused() internal view returns (bool) {
// After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access.
return block.timestamp > _getBufferPeriodEndTime() || !_paused;
}
// These getters lead to reduced bytecode size by inlining the immutable variables in a single place.
function _getPauseWindowEndTime() private view returns (uint256) {
return _pauseWindowEndTime;
}
function _getBufferPeriodEndTime() private view returns (uint256) {
return _bufferPeriodEndTime;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.sol";
import "./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 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 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(msg.sender, 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(msg.sender, 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,
msg.sender,
_allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_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(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(
msg.sender,
spender,
_allowances[msg.sender][spender].sub(subtractedValue, Errors.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), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS);
_require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS);
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_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), Errors.ERC20_MINT_TO_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), Errors.ERC20_BURN_FROM_ZERO_ADDRESS);
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_ALLOWANCE);
_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), Errors.ERC20_APPROVE_FROM_ZERO_ADDRESS);
_require(spender != address(0), Errors.ERC20_APPROVE_TO_ZERO_ADDRESS);
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "../../lib/math/FixedPoint.sol";
import "../../lib/math/Math.sol";
import "../../lib/helpers/InputHelpers.sol";
/* solhint-disable private-vars-leading-underscore */
contract WeightedMath {
using FixedPoint for uint256;
// A minimum normalized weight imposes a maximum weight ratio. We need this due to limitations in the
// implementation of the power function, as these ratios are often exponents.
uint256 internal constant _MIN_WEIGHT = 0.01e18;
// Having a minimum normalized weight imposes a limit on the maximum number of tokens;
// i.e., the largest possible pool is one where all tokens have exactly the minimum weight.
uint256 internal constant _MAX_WEIGHTED_TOKENS = 100;
// Pool limits that arise from limitations in the fixed point power function (and the imposed 1:100 maximum weight
// ratio).
// Swap limits: amounts swapped may not be larger than this percentage of total balance.
uint256 internal constant _MAX_IN_RATIO = 0.3e18;
uint256 internal constant _MAX_OUT_RATIO = 0.3e18;
// Invariant growth limit: non-proportional joins cannot cause the invariant to increase by more than this ratio.
uint256 internal constant _MAX_INVARIANT_RATIO = 3e18;
// Invariant shrink limit: non-proportional exits cannot cause the invariant to decrease by less than this ratio.
uint256 internal constant _MIN_INVARIANT_RATIO = 0.7e18;
// Invariant is used to collect protocol swap fees by comparing its value between two times.
// So we can round always to the same direction. It is also used to initiate the BPT amount
// and, because there is a minimum BPT, we round down the invariant.
function _calculateInvariant(uint256[] memory normalizedWeights, uint256[] memory balances)
internal
pure
returns (uint256 invariant)
{
/**********************************************************************************************
// invariant _____ //
// wi = weight index i | | wi //
// bi = balance index i | | bi ^ = i //
// i = invariant //
**********************************************************************************************/
invariant = FixedPoint.ONE;
for (uint256 i = 0; i < normalizedWeights.length; i++) {
invariant = invariant.mulDown(balances[i].powDown(normalizedWeights[i]));
}
_require(invariant > 0, Errors.ZERO_INVARIANT);
}
// Computes how many tokens can be taken out of a pool if `amountIn` are sent, given the
// current balances and weights.
function _calcOutGivenIn(
uint256 balanceIn,
uint256 weightIn,
uint256 balanceOut,
uint256 weightOut,
uint256 amountIn
) internal pure returns (uint256) {
/**********************************************************************************************
// outGivenIn //
// aO = amountOut //
// bO = balanceOut //
// bI = balanceIn / / bI \ (wI / wO) \ //
// aI = amountIn aO = bO * | 1 - | -------------------------- | ^ | //
// wI = weightIn \ \ ( bI + aI ) / / //
// wO = weightOut //
**********************************************************************************************/
// Amount out, so we round down overall.
// The multiplication rounds down, and the subtrahend (power) rounds up (so the base rounds up too).
// Because bI / (bI + aI) <= 1, the exponent rounds down.
// Cannot exceed maximum in ratio
_require(amountIn <= balanceIn.mulDown(_MAX_IN_RATIO), Errors.MAX_IN_RATIO);
uint256 denominator = balanceIn.add(amountIn);
uint256 base = balanceIn.divUp(denominator);
uint256 exponent = weightIn.divDown(weightOut);
uint256 power = base.powUp(exponent);
return balanceOut.mulDown(power.complement());
}
// Computes how many tokens must be sent to a pool in order to take `amountOut`, given the
// current balances and weights.
function _calcInGivenOut(
uint256 balanceIn,
uint256 weightIn,
uint256 balanceOut,
uint256 weightOut,
uint256 amountOut
) internal pure returns (uint256) {
/**********************************************************************************************
// inGivenOut //
// aO = amountOut //
// bO = balanceOut //
// bI = balanceIn / / bO \ (wO / wI) \ //
// aI = amountIn aI = bI * | | -------------------------- | ^ - 1 | //
// wI = weightIn \ \ ( bO - aO ) / / //
// wO = weightOut //
**********************************************************************************************/
// Amount in, so we round up overall.
// The multiplication rounds up, and the power rounds up (so the base rounds up too).
// Because b0 / (b0 - a0) >= 1, the exponent rounds up.
// Cannot exceed maximum out ratio
_require(amountOut <= balanceOut.mulDown(_MAX_OUT_RATIO), Errors.MAX_OUT_RATIO);
uint256 base = balanceOut.divUp(balanceOut.sub(amountOut));
uint256 exponent = weightOut.divUp(weightIn);
uint256 power = base.powUp(exponent);
// Because the base is larger than one (and the power rounds up), the power should always be larger than one, so
// the following subtraction should never revert.
uint256 ratio = power.sub(FixedPoint.ONE);
return balanceIn.mulUp(ratio);
}
function _calcBptOutGivenExactTokensIn(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory amountsIn,
uint256 bptTotalSupply,
uint256 swapFee
) internal pure returns (uint256) {
// BPT out, so we round down overall.
uint256[] memory balanceRatiosWithFee = new uint256[](amountsIn.length);
uint256 invariantRatioWithFees = 0;
for (uint256 i = 0; i < balances.length; i++) {
balanceRatiosWithFee[i] = balances[i].add(amountsIn[i]).divDown(balances[i]);
invariantRatioWithFees = invariantRatioWithFees.add(balanceRatiosWithFee[i].mulDown(normalizedWeights[i]));
}
uint256 invariantRatio = FixedPoint.ONE;
for (uint256 i = 0; i < balances.length; i++) {
uint256 amountInWithoutFee;
if (balanceRatiosWithFee[i] > invariantRatioWithFees) {
uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithFees.sub(FixedPoint.ONE));
uint256 taxableAmount = amountsIn[i].sub(nonTaxableAmount);
amountInWithoutFee = nonTaxableAmount.add(taxableAmount.mulDown(FixedPoint.ONE.sub(swapFee)));
} else {
amountInWithoutFee = amountsIn[i];
}
uint256 balanceRatio = balances[i].add(amountInWithoutFee).divDown(balances[i]);
invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i]));
}
if (invariantRatio >= FixedPoint.ONE) {
return bptTotalSupply.mulDown(invariantRatio.sub(FixedPoint.ONE));
} else {
return 0;
}
}
function _calcTokenInGivenExactBptOut(
uint256 balance,
uint256 normalizedWeight,
uint256 bptAmountOut,
uint256 bptTotalSupply,
uint256 swapFee
) internal pure returns (uint256) {
/******************************************************************************************
// tokenInForExactBPTOut //
// a = amountIn //
// b = balance / / totalBPT + bptOut \ (1 / w) \ //
// bptOut = bptAmountOut a = b * | | -------------------------- | ^ - 1 | //
// bpt = totalBPT \ \ totalBPT / / //
// w = weight //
******************************************************************************************/
// Token in, so we round up overall.
// Calculate the factor by which the invariant will increase after minting BPTAmountOut
uint256 invariantRatio = bptTotalSupply.add(bptAmountOut).divUp(bptTotalSupply);
_require(invariantRatio <= _MAX_INVARIANT_RATIO, Errors.MAX_OUT_BPT_FOR_TOKEN_IN);
// Calculate by how much the token balance has to increase to match the invariantRatio
uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divUp(normalizedWeight));
uint256 amountInWithoutFee = balance.mulUp(balanceRatio.sub(FixedPoint.ONE));
// We can now compute how much extra balance is being deposited and used in virtual swaps, and charge swap fees
// accordingly.
uint256 taxablePercentage = normalizedWeight.complement();
uint256 taxableAmount = amountInWithoutFee.mulUp(taxablePercentage);
uint256 nonTaxableAmount = amountInWithoutFee.sub(taxableAmount);
return nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement()));
}
function _calcBptInGivenExactTokensOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory amountsOut,
uint256 bptTotalSupply,
uint256 swapFee
) internal pure returns (uint256) {
// BPT in, so we round up overall.
uint256[] memory balanceRatiosWithoutFee = new uint256[](amountsOut.length);
uint256 invariantRatioWithoutFees = 0;
for (uint256 i = 0; i < balances.length; i++) {
balanceRatiosWithoutFee[i] = balances[i].sub(amountsOut[i]).divUp(balances[i]);
invariantRatioWithoutFees = invariantRatioWithoutFees.add(
balanceRatiosWithoutFee[i].mulUp(normalizedWeights[i])
);
}
uint256 invariantRatio = FixedPoint.ONE;
for (uint256 i = 0; i < balances.length; i++) {
// Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it to
// 'token out'. This results in slightly larger price impact.
uint256 amountOutWithFee;
if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) {
uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithoutFees.complement());
uint256 taxableAmount = amountsOut[i].sub(nonTaxableAmount);
amountOutWithFee = nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement()));
} else {
amountOutWithFee = amountsOut[i];
}
uint256 balanceRatio = balances[i].sub(amountOutWithFee).divDown(balances[i]);
invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i]));
}
return bptTotalSupply.mulUp(invariantRatio.complement());
}
function _calcTokenOutGivenExactBptIn(
uint256 balance,
uint256 normalizedWeight,
uint256 bptAmountIn,
uint256 bptTotalSupply,
uint256 swapFee
) internal pure returns (uint256) {
/*****************************************************************************************
// exactBPTInForTokenOut //
// a = amountOut //
// b = balance / / totalBPT - bptIn \ (1 / w) \ //
// bptIn = bptAmountIn a = b * | 1 - | -------------------------- | ^ | //
// bpt = totalBPT \ \ totalBPT / / //
// w = weight //
*****************************************************************************************/
// Token out, so we round down overall. The multiplication rounds down, but the power rounds up (so the base
// rounds up). Because (totalBPT - bptIn) / totalBPT <= 1, the exponent rounds down.
// Calculate the factor by which the invariant will decrease after burning BPTAmountIn
uint256 invariantRatio = bptTotalSupply.sub(bptAmountIn).divUp(bptTotalSupply);
_require(invariantRatio >= _MIN_INVARIANT_RATIO, Errors.MIN_BPT_IN_FOR_TOKEN_OUT);
// Calculate by how much the token balance has to decrease to match invariantRatio
uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divDown(normalizedWeight));
// Because of rounding up, balanceRatio can be greater than one. Using complement prevents reverts.
uint256 amountOutWithoutFee = balance.mulDown(balanceRatio.complement());
// We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result
// in swap fees.
uint256 taxablePercentage = normalizedWeight.complement();
// Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it
// to 'token out'. This results in slightly larger price impact. Fees are rounded up.
uint256 taxableAmount = amountOutWithoutFee.mulUp(taxablePercentage);
uint256 nonTaxableAmount = amountOutWithoutFee.sub(taxableAmount);
return nonTaxableAmount.add(taxableAmount.mulDown(swapFee.complement()));
}
function _calcTokensOutGivenExactBptIn(
uint256[] memory balances,
uint256 bptAmountIn,
uint256 totalBPT
) internal pure returns (uint256[] memory) {
/**********************************************************************************************
// exactBPTInForTokensOut //
// (per token) //
// aO = amountOut / bptIn \ //
// b = balance a0 = b * | --------------------- | //
// bptIn = bptAmountIn \ totalBPT / //
// bpt = totalBPT //
**********************************************************************************************/
// Since we're computing an amount out, we round down overall. This means rounding down on both the
// multiplication and division.
uint256 bptRatio = bptAmountIn.divDown(totalBPT);
uint256[] memory amountsOut = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
amountsOut[i] = balances[i].mulDown(bptRatio);
}
return amountsOut;
}
function _calcDueTokenProtocolSwapFeeAmount(
uint256 balance,
uint256 normalizedWeight,
uint256 previousInvariant,
uint256 currentInvariant,
uint256 protocolSwapFeePercentage
) internal pure returns (uint256) {
/*********************************************************************************
/* protocolSwapFeePercentage * balanceToken * ( 1 - (previousInvariant / currentInvariant) ^ (1 / weightToken))
*********************************************************************************/
if (currentInvariant <= previousInvariant) {
// This shouldn't happen outside of rounding errors, but have this safeguard nonetheless to prevent the Pool
// from entering a locked state in which joins and exits revert while computing accumulated swap fees.
return 0;
}
// We round down to prevent issues in the Pool's accounting, even if it means paying slightly less in protocol
// fees to the Vault.
// Fee percentage and balance multiplications round down, while the subtrahend (power) rounds up (as does the
// base). Because previousInvariant / currentInvariant <= 1, the exponent rounds down.
uint256 base = previousInvariant.divUp(currentInvariant);
uint256 exponent = FixedPoint.ONE.divDown(normalizedWeight);
// Because the exponent is larger than one, the base of the power function has a lower bound. We cap to this
// value to avoid numeric issues, which means in the extreme case (where the invariant growth is larger than
// 1 / min exponent) the Pool will pay less in protocol fees than it should.
base = Math.max(base, FixedPoint.MIN_POW_BASE_FREE_EXPONENT);
uint256 power = base.powUp(exponent);
uint256 tokenAccruedFees = balance.mulDown(power.complement());
return tokenAccruedFees.mulDown(protocolSwapFeePercentage);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "../../lib/math//LogExpMath.sol";
import "../../lib/math/FixedPoint.sol";
import "../../lib/math/Math.sol";
import "../../lib/helpers/InputHelpers.sol";
/* solhint-disable private-vars-leading-underscore */
contract WeightedOracleMath {
using FixedPoint for uint256;
int256 private constant _LOG_COMPRESSION_FACTOR = 1e14;
int256 private constant _HALF_LOG_COMPRESSION_FACTOR = 0.5e14;
/**
* @dev Calculates the logarithm of the spot price of token B in token A.
*
* The return value is a 4 decimal fixed-point number: use `_fromLowResLog` to recover the original value.
*/
function _calcLogSpotPrice(
uint256 normalizedWeightA,
uint256 balanceA,
uint256 normalizedWeightB,
uint256 balanceB
) internal pure returns (int256) {
// Max balances are 2^112 and min weights are 0.01, so the division never overflows.
// The rounding direction is irrelevant as we're about to introduce a much larger error when converting to log
// space. We use `divUp` as it prevents the result from being zero, which would make the logarithm revert. A
// result of zero is therefore only possible with zero balances, which are prevented via other means.
uint256 spotPrice = balanceA.divUp(normalizedWeightA).divUp(balanceB.divUp(normalizedWeightB));
return _toLowResLog(spotPrice);
}
/**
* @dev Calculates the price of BPT in a token. `logBptTotalSupply` should be the result of calling `_toLowResLog`
* with the current BPT supply.
*
* The return value is a 4 decimal fixed-point number: use `_fromLowResLog` to recover the original value.
*/
function _calcLogBPTPrice(
uint256 normalizedWeight,
uint256 balance,
int256 logBptTotalSupply
) internal pure returns (int256) {
// BPT price = (balance / weight) / total supply
// Since we already have ln(total supply) and want to compute ln(BPT price), we perform the computation in log
// space directly: ln(BPT price) = ln(balance / weight) - ln(total supply)
// The rounding direction is irrelevant as we're about to introduce a much larger error when converting to log
// space. We use `divUp` as it prevents the result from being zero, which would make the logarithm revert. A
// result of zero is therefore only possible with zero balances, which are prevented via other means.
int256 logBalanceOverWeight = _toLowResLog(balance.divUp(normalizedWeight));
// Because we're subtracting two values in log space, this value has a larger error (+-0.0001 instead of
// +-0.00005), which results in a final larger relative error of around 0.1%.
return logBalanceOverWeight - logBptTotalSupply;
}
/**
* @dev Returns the natural logarithm of `value`, dropping most of the decimal places to arrive at a value that,
* when passed to `_fromLowResLog`, will have a maximum relative error of ~0.05% compared to `value`.
*
* Values returned from this function should not be mixed with other fixed-point values (as they have a different
* number of digits), but can be added or subtracted. Use `_fromLowResLog` to undo this process and return to an
* 18 decimal places fixed point value.
*
* Because so much precision is lost, the logarithmic values can be stored using much fewer bits than the original
* value required.
*/
function _toLowResLog(uint256 value) internal pure returns (int256) {
int256 ln = LogExpMath.ln(int256(value));
// Rounding division for signed numerator
return
(ln > 0 ? ln + _HALF_LOG_COMPRESSION_FACTOR : ln - _HALF_LOG_COMPRESSION_FACTOR) / _LOG_COMPRESSION_FACTOR;
}
/**
* @dev Restores `value` from logarithmic space. `value` is expected to be the result of a call to `_toLowResLog`,
* any other function that returns 4 decimals fixed point logarithms, or the sum of such values.
*/
function _fromLowResLog(int256 value) internal pure returns (uint256) {
return uint256(LogExpMath.exp(value * _LOG_COMPRESSION_FACTOR));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/helpers/WordCodec.sol";
/**
* @dev This module provides an interface to store seemingly unrelated pieces of information, in particular used by
* Weighted Pools of 2 tokens with a price oracle.
*
* These pieces of information are all kept together in a single storage slot to reduce the number of storage reads. In
* particular, we not only store configuration values (such as the swap fee percentage), but also cache
* reduced-precision versions of the total BPT supply and invariant, which lets us not access nor compute these values
* when producing oracle updates during a swap.
*
* Data is stored with the following structure:
*
* [ swap fee pct | oracle enabled | oracle index | oracle sample initial timestamp | log supply | log invariant ]
* [ uint64 | bool | uint10 | uint31 | int22 | int22 ]
*
* Note that we are not using the most-significant 106 bits.
*/
library WeightedPool2TokensMiscData {
using WordCodec for bytes32;
using WordCodec for uint256;
uint256 private constant _LOG_INVARIANT_OFFSET = 0;
uint256 private constant _LOG_TOTAL_SUPPLY_OFFSET = 22;
uint256 private constant _ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET = 44;
uint256 private constant _ORACLE_INDEX_OFFSET = 75;
uint256 private constant _ORACLE_ENABLED_OFFSET = 85;
uint256 private constant _SWAP_FEE_PERCENTAGE_OFFSET = 86;
/**
* @dev Returns the cached logarithm of the invariant.
*/
function logInvariant(bytes32 data) internal pure returns (int256) {
return data.decodeInt22(_LOG_INVARIANT_OFFSET);
}
/**
* @dev Returns the cached logarithm of the total supply.
*/
function logTotalSupply(bytes32 data) internal pure returns (int256) {
return data.decodeInt22(_LOG_TOTAL_SUPPLY_OFFSET);
}
/**
* @dev Returns the timestamp of the creation of the oracle's latest sample.
*/
function oracleSampleCreationTimestamp(bytes32 data) internal pure returns (uint256) {
return data.decodeUint31(_ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET);
}
/**
* @dev Returns the index of the oracle's latest sample.
*/
function oracleIndex(bytes32 data) internal pure returns (uint256) {
return data.decodeUint10(_ORACLE_INDEX_OFFSET);
}
/**
* @dev Returns true if the oracle is enabled.
*/
function oracleEnabled(bytes32 data) internal pure returns (bool) {
return data.decodeBool(_ORACLE_ENABLED_OFFSET);
}
/**
* @dev Returns the swap fee percentage.
*/
function swapFeePercentage(bytes32 data) internal pure returns (uint256) {
return data.decodeUint64(_SWAP_FEE_PERCENTAGE_OFFSET);
}
/**
* @dev Sets the logarithm of the invariant in `data`, returning the updated value.
*/
function setLogInvariant(bytes32 data, int256 _logInvariant) internal pure returns (bytes32) {
return data.insertInt22(_logInvariant, _LOG_INVARIANT_OFFSET);
}
/**
* @dev Sets the logarithm of the total supply in `data`, returning the updated value.
*/
function setLogTotalSupply(bytes32 data, int256 _logTotalSupply) internal pure returns (bytes32) {
return data.insertInt22(_logTotalSupply, _LOG_TOTAL_SUPPLY_OFFSET);
}
/**
* @dev Sets the timestamp of the creation of the oracle's latest sample in `data`, returning the updated value.
*/
function setOracleSampleCreationTimestamp(bytes32 data, uint256 _initialTimestamp) internal pure returns (bytes32) {
return data.insertUint31(_initialTimestamp, _ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET);
}
/**
* @dev Sets the index of the oracle's latest sample in `data`, returning the updated value.
*/
function setOracleIndex(bytes32 data, uint256 _oracleIndex) internal pure returns (bytes32) {
return data.insertUint10(_oracleIndex, _ORACLE_INDEX_OFFSET);
}
/**
* @dev Enables or disables the oracle in `data`, returning the updated value.
*/
function setOracleEnabled(bytes32 data, bool _oracleEnabled) internal pure returns (bytes32) {
return data.insertBoolean(_oracleEnabled, _ORACLE_ENABLED_OFFSET);
}
/**
* @dev Sets the swap fee percentage in `data`, returning the updated value.
*/
function setSwapFeePercentage(bytes32 data, uint256 _swapFeePercentage) internal pure returns (bytes32) {
return data.insertUint64(_swapFeePercentage, _SWAP_FEE_PERCENTAGE_OFFSET);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "../../lib/openzeppelin/IERC20.sol";
import "./WeightedPool.sol";
library WeightedPoolUserDataHelpers {
function joinKind(bytes memory self) internal pure returns (WeightedPool.JoinKind) {
return abi.decode(self, (WeightedPool.JoinKind));
}
function exitKind(bytes memory self) internal pure returns (WeightedPool.ExitKind) {
return abi.decode(self, (WeightedPool.ExitKind));
}
// Joins
function initialAmountsIn(bytes memory self) internal pure returns (uint256[] memory amountsIn) {
(, amountsIn) = abi.decode(self, (WeightedPool.JoinKind, uint256[]));
}
function exactTokensInForBptOut(bytes memory self)
internal
pure
returns (uint256[] memory amountsIn, uint256 minBPTAmountOut)
{
(, amountsIn, minBPTAmountOut) = abi.decode(self, (WeightedPool.JoinKind, uint256[], uint256));
}
function tokenInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut, uint256 tokenIndex) {
(, bptAmountOut, tokenIndex) = abi.decode(self, (WeightedPool.JoinKind, uint256, uint256));
}
// Exits
function exactBptInForTokenOut(bytes memory self) internal pure returns (uint256 bptAmountIn, uint256 tokenIndex) {
(, bptAmountIn, tokenIndex) = abi.decode(self, (WeightedPool.ExitKind, uint256, uint256));
}
function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) {
(, bptAmountIn) = abi.decode(self, (WeightedPool.ExitKind, uint256));
}
function bptInForExactTokensOut(bytes memory self)
internal
pure
returns (uint256[] memory amountsOut, uint256 maxBPTAmountIn)
{
(, amountsOut, maxBPTAmountIn) = abi.decode(self, (WeightedPool.ExitKind, uint256[], uint256));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "../lib/math/Math.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/IERC20Permit.sol";
import "../lib/openzeppelin/EIP712.sol";
/**
* @title Highly opinionated token implementation
* @author Balancer Labs
* @dev
* - Includes functions to increase and decrease allowance as a workaround
* for the well-known issue with `approve`:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* - Allows for 'infinite allowance', where an allowance of 0xff..ff is not
* decreased by calls to transferFrom
* - Lets a token holder use `transferFrom` to send their own tokens,
* without first setting allowance
* - Emits 'Approval' events whenever allowance is changed by `transferFrom`
*/
contract BalancerPoolToken is IERC20, IERC20Permit, EIP712 {
using Math for uint256;
// State variables
uint8 private constant _DECIMALS = 18;
mapping(address => uint256) private _balance;
mapping(address => mapping(address => uint256)) private _allowance;
uint256 private _totalSupply;
string private _name;
string private _symbol;
mapping(address => uint256) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPE_HASH = keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
// Function declarations
constructor(string memory tokenName, string memory tokenSymbol) EIP712(tokenName, "1") {
_name = tokenName;
_symbol = tokenSymbol;
}
// External functions
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowance[owner][spender];
}
function balanceOf(address account) external view override returns (uint256) {
return _balance[account];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_setAllowance(msg.sender, spender, amount);
return true;
}
function increaseApproval(address spender, uint256 amount) external returns (bool) {
_setAllowance(msg.sender, spender, _allowance[msg.sender][spender].add(amount));
return true;
}
function decreaseApproval(address spender, uint256 amount) external returns (bool) {
uint256 currentAllowance = _allowance[msg.sender][spender];
if (amount >= currentAllowance) {
_setAllowance(msg.sender, spender, 0);
} else {
_setAllowance(msg.sender, spender, currentAllowance.sub(amount));
}
return true;
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_move(msg.sender, recipient, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
uint256 currentAllowance = _allowance[sender][msg.sender];
_require(msg.sender == sender || currentAllowance >= amount, Errors.INSUFFICIENT_ALLOWANCE);
_move(sender, recipient, amount);
if (msg.sender != sender && currentAllowance != uint256(-1)) {
// Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount
_setAllowance(sender, msg.sender, currentAllowance - amount);
}
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
// solhint-disable-next-line not-rely-on-time
_require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT);
uint256 nonce = _nonces[owner];
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPE_HASH, owner, spender, value, nonce, deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ecrecover(hash, v, r, s);
_require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE);
_nonces[owner] = nonce + 1;
_setAllowance(owner, spender, value);
}
// Public functions
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _DECIMALS;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function nonces(address owner) external view override returns (uint256) {
return _nonces[owner];
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
// Internal functions
function _mintPoolTokens(address recipient, uint256 amount) internal {
_balance[recipient] = _balance[recipient].add(amount);
_totalSupply = _totalSupply.add(amount);
emit Transfer(address(0), recipient, amount);
}
function _burnPoolTokens(address sender, uint256 amount) internal {
uint256 currentBalance = _balance[sender];
_require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE);
_balance[sender] = currentBalance - amount;
_totalSupply = _totalSupply.sub(amount);
emit Transfer(sender, address(0), amount);
}
function _move(
address sender,
address recipient,
uint256 amount
) internal {
uint256 currentBalance = _balance[sender];
_require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE);
// Prohibit transfers to the zero address to avoid confusion with the
// Transfer event emitted by `_burnPoolTokens`
_require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS);
_balance[sender] = currentBalance - amount;
_balance[recipient] = _balance[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
// Private functions
function _setAllowance(
address owner,
address spender,
uint256 amount
) private {
_allowance[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "../lib/helpers/Authentication.sol";
import "../vault/interfaces/IAuthorizer.sol";
import "./BasePool.sol";
/**
* @dev Base authorization layer implementation for Pools.
*
* The owner account can call some of the permissioned functions - access control of the rest is delegated to the
* Authorizer. Note that this owner is immutable: more sophisticated permission schemes, such as multiple ownership,
* granular roles, etc., could be built on top of this by making the owner a smart contract.
*
* Access control of all other permissioned functions is delegated to an Authorizer. It is also possible to delegate
* control of *all* permissioned functions to the Authorizer by setting the owner address to `_DELEGATE_OWNER`.
*/
abstract contract BasePoolAuthorization is Authentication {
address private immutable _owner;
address private constant _DELEGATE_OWNER = 0xBA1BA1ba1BA1bA1bA1Ba1BA1ba1BA1bA1ba1ba1B;
constructor(address owner) {
_owner = owner;
}
function getOwner() public view returns (address) {
return _owner;
}
function getAuthorizer() external view returns (IAuthorizer) {
return _getAuthorizer();
}
function _canPerform(bytes32 actionId, address account) internal view override returns (bool) {
if ((getOwner() != _DELEGATE_OWNER) && _isOwnerOnlyAction(actionId)) {
// Only the owner can perform "owner only" actions, unless the owner is delegated.
return msg.sender == getOwner();
} else {
// Non-owner actions are always processed via the Authorizer, as "owner only" ones are when delegated.
return _getAuthorizer().canPerform(actionId, account, address(this));
}
}
function _isOwnerOnlyAction(bytes32 actionId) private view returns (bool) {
// This implementation hardcodes the setSwapFeePercentage action identifier.
return actionId == getActionId(BasePool.setSwapFeePercentage.selector);
}
function _getAuthorizer() internal view virtual returns (IAuthorizer);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "./Buffer.sol";
import "./Samples.sol";
import "../../lib/helpers/BalancerErrors.sol";
import "./IWeightedPoolPriceOracle.sol";
import "../IPriceOracle.sol";
/**
* @dev This module allows Pools to access historical pricing information.
*
* It uses a 1024 long circular buffer to store past data, where the data within each sample is the result of
* accumulating live data for no more than two minutes. Therefore, assuming the worst case scenario where new data is
* updated in every single block, the oldest samples in the buffer (and therefore largest queryable period) will
* be slightly over 34 hours old.
*
* Usage of this module requires the caller to keep track of two variables: the latest circular buffer index, and the
* timestamp when the index last changed.
*/
contract PoolPriceOracle is IWeightedPoolPriceOracle {
using Buffer for uint256;
using Samples for bytes32;
// Each sample in the buffer accumulates information for up to 2 minutes. This is simply to reduce the size of the
// buffer: small time deviations will not have any significant effect.
// solhint-disable not-rely-on-time
uint256 private constant _MAX_SAMPLE_DURATION = 2 minutes;
// We use a mapping to simulate an array: the buffer won't grow or shrink, and since we will always use valid
// indexes using a mapping saves gas by skipping the bounds checks.
mapping(uint256 => bytes32) internal _samples;
function getSample(uint256 index)
external
view
override
returns (
int256 logPairPrice,
int256 accLogPairPrice,
int256 logBptPrice,
int256 accLogBptPrice,
int256 logInvariant,
int256 accLogInvariant,
uint256 timestamp
)
{
_require(index < Buffer.SIZE, Errors.ORACLE_INVALID_INDEX);
bytes32 sample = _getSample(index);
return sample.unpack();
}
function getTotalSamples() external pure override returns (uint256) {
return Buffer.SIZE;
}
/**
* @dev Processes new price and invariant data, updating the latest sample or creating a new one.
*
* Receives the new logarithms of values to store: `logPairPrice`, `logBptPrice` and `logInvariant`, as well the
* index of the latest sample and the timestamp of its creation.
*
* Returns the index of the latest sample. If different from `latestIndex`, the caller should also store the
* timestamp, and pass it on future calls to this function.
*/
function _processPriceData(
uint256 latestSampleCreationTimestamp,
uint256 latestIndex,
int256 logPairPrice,
int256 logBptPrice,
int256 logInvariant
) internal returns (uint256) {
// Read latest sample, and compute the next one by updating it with the newly received data.
bytes32 sample = _getSample(latestIndex).update(logPairPrice, logBptPrice, logInvariant, block.timestamp);
// We create a new sample if more than _MAX_SAMPLE_DURATION seconds have elapsed since the creation of the
// latest one. In other words, no sample accumulates data over a period larger than _MAX_SAMPLE_DURATION.
bool newSample = block.timestamp - latestSampleCreationTimestamp >= _MAX_SAMPLE_DURATION;
latestIndex = newSample ? latestIndex.next() : latestIndex;
// Store the updated or new sample.
_samples[latestIndex] = sample;
return latestIndex;
}
/**
* @dev Returns the instant value for `variable` in the sample pointed to by `index`.
*/
function _getInstantValue(IPriceOracle.Variable variable, uint256 index) internal view returns (int256) {
bytes32 sample = _getSample(index);
_require(sample.timestamp() > 0, Errors.ORACLE_NOT_INITIALIZED);
return sample.instant(variable);
}
/**
* @dev Returns the value of the accumulator for `variable` `ago` seconds ago. `latestIndex` must be the index of
* the latest sample in the buffer.
*
* Reverts under the following conditions:
* - if the buffer is empty.
* - if querying past information and the buffer has not been fully initialized.
* - if querying older information than available in the buffer. Note that a full buffer guarantees queries for the
* past 34 hours will not revert.
*
* If requesting information for a timestamp later than the latest one, it is extrapolated using the latest
* available data.
*
* When no exact information is available for the requested past timestamp (as usually happens, since at most one
* timestamp is stored every two minutes), it is estimated by performing linear interpolation using the closest
* values. This process is guaranteed to complete performing at most 10 storage reads.
*/
function _getPastAccumulator(
IPriceOracle.Variable variable,
uint256 latestIndex,
uint256 ago
) internal view returns (int256) {
// `ago` must not be before the epoch.
_require(block.timestamp >= ago, Errors.ORACLE_INVALID_SECONDS_QUERY);
uint256 lookUpTime = block.timestamp - ago;
bytes32 latestSample = _getSample(latestIndex);
uint256 latestTimestamp = latestSample.timestamp();
// The latest sample only has a non-zero timestamp if no data was ever processed and stored in the buffer.
_require(latestTimestamp > 0, Errors.ORACLE_NOT_INITIALIZED);
if (latestTimestamp <= lookUpTime) {
// The accumulator at times ahead of the latest one are computed by extrapolating the latest data. This is
// equivalent to the instant value not changing between the last timestamp and the look up time.
// We can use unchecked arithmetic since the accumulator can be represented in 53 bits, timestamps in 31
// bits, and the instant value in 22 bits.
uint256 elapsed = lookUpTime - latestTimestamp;
return latestSample.accumulator(variable) + (latestSample.instant(variable) * int256(elapsed));
} else {
// The look up time is before the latest sample, but we need to make sure that it is not before the oldest
// sample as well.
// Since we use a circular buffer, the oldest sample is simply the next one.
uint256 oldestIndex = latestIndex.next();
{
// Local scope used to prevent stack-too-deep errors.
bytes32 oldestSample = _getSample(oldestIndex);
uint256 oldestTimestamp = oldestSample.timestamp();
// For simplicity's sake, we only perform past queries if the buffer has been fully initialized. This
// means the oldest sample must have a non-zero timestamp.
_require(oldestTimestamp > 0, Errors.ORACLE_NOT_INITIALIZED);
// The only remaining condition to check is for the look up time to be between the oldest and latest
// timestamps.
_require(oldestTimestamp <= lookUpTime, Errors.ORACLE_QUERY_TOO_OLD);
}
// Perform binary search to find nearest samples to the desired timestamp.
(bytes32 prev, bytes32 next) = _findNearestSample(lookUpTime, oldestIndex);
// `next`'s timestamp is guaranteed to be larger than `prev`'s, so we can skip checked arithmetic.
uint256 samplesTimeDiff = next.timestamp() - prev.timestamp();
if (samplesTimeDiff > 0) {
// We estimate the accumulator at the requested look up time by interpolating linearly between the
// previous and next accumulators.
// We can use unchecked arithmetic since the accumulators can be represented in 53 bits, and timestamps
// in 31 bits.
int256 samplesAccDiff = next.accumulator(variable) - prev.accumulator(variable);
uint256 elapsed = lookUpTime - prev.timestamp();
return prev.accumulator(variable) + ((samplesAccDiff * int256(elapsed)) / int256(samplesTimeDiff));
} else {
// Rarely, one of the samples will have the exact requested look up time, which is indicated by `prev`
// and `next` being the same. In this case, we simply return the accumulator at that point in time.
return prev.accumulator(variable);
}
}
}
/**
* @dev Finds the two samples with timestamps before and after `lookUpDate`. If one of the samples matches exactly,
* both `prev` and `next` will be it. `offset` is the index of the oldest sample in the buffer.
*
* Assumes `lookUpDate` is greater or equal than the timestamp of the oldest sample, and less or equal than the
* timestamp of the latest sample.
*/
function _findNearestSample(uint256 lookUpDate, uint256 offset) internal view returns (bytes32 prev, bytes32 next) {
// We're going to perform a binary search in the circular buffer, which requires it to be sorted. To achieve
// this, we offset all buffer accesses by `offset`, making the first element the oldest one.
// Auxiliary variables in a typical binary search: we will look at some value `mid` between `low` and `high`,
// periodically increasing `low` or decreasing `high` until we either find a match or determine the element is
// not in the array.
uint256 low = 0;
uint256 high = Buffer.SIZE - 1;
uint256 mid;
// If the search fails and no sample has a timestamp of `lookUpDate` (as is the most common scenario), `sample`
// will be either the sample with the largest timestamp smaller than `lookUpDate`, or the one with the smallest
// timestamp larger than `lookUpDate`.
bytes32 sample;
uint256 sampleTimestamp;
while (low <= high) {
// Mid is the floor of the average.
uint256 midWithoutOffset = (high + low) / 2;
// Recall that the buffer is not actually sorted: we need to apply the offset to access it in a sorted way.
mid = midWithoutOffset.add(offset);
sample = _getSample(mid);
sampleTimestamp = sample.timestamp();
if (sampleTimestamp < lookUpDate) {
// If the mid sample is bellow the look up date, then increase the low index to start from there.
low = midWithoutOffset + 1;
} else if (sampleTimestamp > lookUpDate) {
// If the mid sample is above the look up date, then decrease the high index to start from there.
// We can skip checked arithmetic: it is impossible for `high` to ever be 0, as a scenario where `low`
// equals 0 and `high` equals 1 would result in `low` increasing to 1 in the previous `if` clause.
high = midWithoutOffset - 1;
} else {
// sampleTimestamp == lookUpDate
// If we have an exact match, return the sample as both `prev` and `next`.
return (sample, sample);
}
}
// In case we reach here, it means we didn't find exactly the sample we where looking for.
return sampleTimestamp < lookUpDate ? (sample, _getSample(mid.next())) : (_getSample(mid.prev()), sample);
}
/**
* @dev Returns the sample that corresponds to a given `index`.
*
* Using this function instead of accessing storage directly results in denser bytecode (since the storage slot is
* only computed here).
*/
function _getSample(uint256 index) internal view returns (bytes32) {
return _samples[index];
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
library Buffer {
// The buffer is a circular storage structure with 1024 slots.
// solhint-disable-next-line private-vars-leading-underscore
uint256 internal constant SIZE = 1024;
/**
* @dev Returns the index of the element before the one pointed by `index`.
*/
function prev(uint256 index) internal pure returns (uint256) {
return sub(index, 1);
}
/**
* @dev Returns the index of the element after the one pointed by `index`.
*/
function next(uint256 index) internal pure returns (uint256) {
return add(index, 1);
}
/**
* @dev Returns the index of an element `offset` slots after the one pointed by `index`.
*/
function add(uint256 index, uint256 offset) internal pure returns (uint256) {
return (index + offset) % SIZE;
}
/**
* @dev Returns the index of an element `offset` slots before the one pointed by `index`.
*/
function sub(uint256 index, uint256 offset) internal pure returns (uint256) {
return (index + SIZE - offset) % SIZE;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant
* to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IMinimalSwapInfoPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
/**
* @dev Interface for querying historical data from a Pool that can be used as a Price Oracle.
*
* This lets third parties retrieve average prices of tokens held by a Pool over a given period of time, as well as the
* price of the Pool share token (BPT) and invariant. Since the invariant is a sensible measure of Pool liquidity, it
* can be used to compare two different price sources, and choose the most liquid one.
*
* Once the oracle is fully initialized, all queries are guaranteed to succeed as long as they require no data that
* is not older than the largest safe query window.
*/
interface IPriceOracle {
// The three values that can be queried:
//
// - PAIR_PRICE: the price of the tokens in the Pool, expressed as the price of the second token in units of the
// first token. For example, if token A is worth $2, and token B is worth $4, the pair price will be 2.0.
// Note that the price is computed *including* the tokens decimals. This means that the pair price of a Pool with
// DAI and USDC will be close to 1.0, despite DAI having 18 decimals and USDC 6.
//
// - BPT_PRICE: the price of the Pool share token (BPT), in units of the first token.
// Note that the price is computed *including* the tokens decimals. This means that the BPT price of a Pool with
// USDC in which BPT is worth $5 will be 5.0, despite the BPT having 18 decimals and USDC 6.
//
// - INVARIANT: the value of the Pool's invariant, which serves as a measure of its liquidity.
enum Variable { PAIR_PRICE, BPT_PRICE, INVARIANT }
/**
* @dev Returns the time average weighted price corresponding to each of `queries`. Prices are represented as 18
* decimal fixed point values.
*/
function getTimeWeightedAverage(OracleAverageQuery[] memory queries)
external
view
returns (uint256[] memory results);
/**
* @dev Returns latest sample of `variable`. Prices are represented as 18 decimal fixed point values.
*/
function getLatest(Variable variable) external view returns (uint256);
/**
* @dev Information for a Time Weighted Average query.
*
* Each query computes the average over a window of duration `secs` seconds that ended `ago` seconds ago. For
* example, the average over the past 30 minutes is computed by settings secs to 1800 and ago to 0. If secs is 1800
* and ago is 1800 as well, the average between 60 and 30 minutes ago is computed instead.
*/
struct OracleAverageQuery {
Variable variable;
uint256 secs;
uint256 ago;
}
/**
* @dev Returns largest time window that can be safely queried, where 'safely' means the Oracle is guaranteed to be
* able to produce a result and not revert.
*
* If a query has a non-zero `ago` value, then `secs + ago` (the oldest point in time) must be smaller than this
* value for 'safe' queries.
*/
function getLargestSafeQueryWindow() external view returns (uint256);
/**
* @dev Returns the accumulators corresponding to each of `queries`.
*/
function getPastAccumulators(OracleAccumulatorQuery[] memory queries)
external
view
returns (int256[] memory results);
/**
* @dev Information for an Accumulator query.
*
* Each query estimates the accumulator at a time `ago` seconds ago.
*/
struct OracleAccumulatorQuery {
Variable variable;
uint256 ago;
}
}
// SPDX-License-Identifier: MIT
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the “Software”), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/* solhint-disable */
/**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2ˆ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2ˆ6
int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2ˆ5
int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
int256 constant x3 = 1600000000000000000000; // 2ˆ4
int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
int256 constant x4 = 800000000000000000000; // 2ˆ3
int256 constant a4 = 298095798704172827474000; // eˆ(x4)
int256 constant x5 = 400000000000000000000; // 2ˆ2
int256 constant a5 = 5459815003314423907810; // eˆ(x5)
int256 constant x6 = 200000000000000000000; // 2ˆ1
int256 constant a6 = 738905609893065022723; // eˆ(x6)
int256 constant x7 = 100000000000000000000; // 2ˆ0
int256 constant a7 = 271828182845904523536; // eˆ(x7)
int256 constant x8 = 50000000000000000000; // 2ˆ-1
int256 constant a8 = 164872127070012814685; // eˆ(x8)
int256 constant x9 = 25000000000000000000; // 2ˆ-2
int256 constant a9 = 128402541668774148407; // eˆ(x9)
int256 constant x10 = 12500000000000000000; // 2ˆ-3
int256 constant a10 = 113314845306682631683; // eˆ(x10)
int256 constant x11 = 6250000000000000000; // 2ˆ-4
int256 constant a11 = 106449445891785942956; // eˆ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
_require(x < 2**255, Errors.X_OUT_OF_BOUNDS);
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
_require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS);
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = _ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = _ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
_require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
Errors.PRODUCT_OUT_OF_BOUNDS
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
_require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT);
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = _ln_36(base);
} else {
logBase = _ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = _ln_36(arg);
} else {
logArg = _ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
_require(a > 0, Errors.OUT_OF_BOUNDS);
if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
return _ln_36(a) / ONE_18;
} else {
return _ln(a);
}
}
/**
* @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function _ln(int256 a) private pure returns (int256) {
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-_ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function _ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
// solhint-disable
/**
* @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are
* supported.
*/
function _require(bool condition, uint256 errorCode) pure {
if (!condition) _revert(errorCode);
}
/**
* @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
*/
function _revert(uint256 errorCode) pure {
// We're going to dynamically create a revert string based on the error code, with the following format:
// 'BAL#{errorCode}'
// where the code is left-padded with zeroes to three digits (so they range from 000 to 999).
//
// We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a
// number (8 to 16 bits) than the individual string characters.
//
// The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a
// much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a
// safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
assembly {
// First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999
// range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for
// the '0' character.
let units := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let tenths := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let hundreds := add(mod(errorCode, 10), 0x30)
// With the individual characters, we can now construct the full string. The "BAL#" part is a known constant
// (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
// characters to it, each shifted by a multiple of 8.
// The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
// per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
// array).
let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds))))
// We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded
// message will have the following layout:
// [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]
// The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We
// also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
// Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
// The string length is fixed: 7 characters.
mstore(0x24, 7)
// Finally, the string itself is stored.
mstore(0x44, revertReason)
// Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of
// the encoded message is therefore 4 + 32 + 32 + 32 = 100.
revert(0, 100)
}
}
library Errors {
// Math
uint256 internal constant ADD_OVERFLOW = 0;
uint256 internal constant SUB_OVERFLOW = 1;
uint256 internal constant SUB_UNDERFLOW = 2;
uint256 internal constant MUL_OVERFLOW = 3;
uint256 internal constant ZERO_DIVISION = 4;
uint256 internal constant DIV_INTERNAL = 5;
uint256 internal constant X_OUT_OF_BOUNDS = 6;
uint256 internal constant Y_OUT_OF_BOUNDS = 7;
uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;
uint256 internal constant INVALID_EXPONENT = 9;
// Input
uint256 internal constant OUT_OF_BOUNDS = 100;
uint256 internal constant UNSORTED_ARRAY = 101;
uint256 internal constant UNSORTED_TOKENS = 102;
uint256 internal constant INPUT_LENGTH_MISMATCH = 103;
uint256 internal constant ZERO_TOKEN = 104;
// Shared pools
uint256 internal constant MIN_TOKENS = 200;
uint256 internal constant MAX_TOKENS = 201;
uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;
uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;
uint256 internal constant MINIMUM_BPT = 204;
uint256 internal constant CALLER_NOT_VAULT = 205;
uint256 internal constant UNINITIALIZED = 206;
uint256 internal constant BPT_IN_MAX_AMOUNT = 207;
uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;
uint256 internal constant EXPIRED_PERMIT = 209;
// Pools
uint256 internal constant MIN_AMP = 300;
uint256 internal constant MAX_AMP = 301;
uint256 internal constant MIN_WEIGHT = 302;
uint256 internal constant MAX_STABLE_TOKENS = 303;
uint256 internal constant MAX_IN_RATIO = 304;
uint256 internal constant MAX_OUT_RATIO = 305;
uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;
uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;
uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;
uint256 internal constant INVALID_TOKEN = 309;
uint256 internal constant UNHANDLED_JOIN_KIND = 310;
uint256 internal constant ZERO_INVARIANT = 311;
uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312;
uint256 internal constant ORACLE_NOT_INITIALIZED = 313;
uint256 internal constant ORACLE_QUERY_TOO_OLD = 314;
uint256 internal constant ORACLE_INVALID_INDEX = 315;
uint256 internal constant ORACLE_BAD_SECS = 316;
// Lib
uint256 internal constant REENTRANCY = 400;
uint256 internal constant SENDER_NOT_ALLOWED = 401;
uint256 internal constant PAUSED = 402;
uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;
uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;
uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;
uint256 internal constant INSUFFICIENT_BALANCE = 406;
uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;
uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;
uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;
uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;
uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;
uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;
uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;
uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;
uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;
uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;
uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;
uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;
uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;
uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;
uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;
uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;
uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;
// Vault
uint256 internal constant INVALID_POOL_ID = 500;
uint256 internal constant CALLER_NOT_POOL = 501;
uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;
uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;
uint256 internal constant INVALID_SIGNATURE = 504;
uint256 internal constant EXIT_BELOW_MIN = 505;
uint256 internal constant JOIN_ABOVE_MAX = 506;
uint256 internal constant SWAP_LIMIT = 507;
uint256 internal constant SWAP_DEADLINE = 508;
uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;
uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;
uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;
uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;
uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;
uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;
uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;
uint256 internal constant INSUFFICIENT_ETH = 516;
uint256 internal constant UNALLOCATED_ETH = 517;
uint256 internal constant ETH_TRANSFER = 518;
uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;
uint256 internal constant TOKENS_MISMATCH = 520;
uint256 internal constant TOKEN_NOT_REGISTERED = 521;
uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;
uint256 internal constant TOKENS_ALREADY_SET = 523;
uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;
uint256 internal constant NONZERO_TOKEN_BALANCE = 525;
uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;
uint256 internal constant POOL_NO_TOKENS = 527;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;
// Fees
uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;
uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
/**
* @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
* address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
* types.
*
* This concept is unrelated to a Pool's Asset Managers.
*/
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
/**
* @dev Interface for the TemporarilyPausable helper.
*/
interface ITemporarilyPausable {
/**
* @dev Emitted every time the pause state changes by `_setPaused`.
*/
event PausedStateChanged(bool paused);
/**
* @dev Returns the current paused state.
*/
function getPausedState()
external
view
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_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, Errors.SUB_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, uint256 errorCode) internal pure returns (uint256) {
_require(b <= a, errorCode);
uint256 c = a - b;
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
* Adapted from OpenZeppelin's SafeMath library
*/
library Math {
/**
* @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting 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), Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting 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), Errors.SUB_OVERFLOW);
return c;
}
/**
* @dev Returns the largest of two numbers of 256 bits.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers of 256 bits.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
_require(a == 0 || c / a == b, Errors.MUL_OVERFLOW);
return c;
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
return a / b;
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
return 1 + (a - 1) / b;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
/**
* @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in
* a single storage slot, saving gas by performing less storage accesses.
*
* Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two
* 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128.
*/
library WordCodec {
// Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word,
// or to insert a new one replacing the old.
uint256 private constant _MASK_1 = 2**(1) - 1;
uint256 private constant _MASK_10 = 2**(10) - 1;
uint256 private constant _MASK_22 = 2**(22) - 1;
uint256 private constant _MASK_31 = 2**(31) - 1;
uint256 private constant _MASK_53 = 2**(53) - 1;
uint256 private constant _MASK_64 = 2**(64) - 1;
// Largest positive values that can be represented as N bits signed integers.
int256 private constant _MAX_INT_22 = 2**(21) - 1;
int256 private constant _MAX_INT_53 = 2**(52) - 1;
// In-place insertion
/**
* @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new
* word.
*/
function insertBoolean(
bytes32 word,
bool value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_1 << offset));
return clearedWord | bytes32(uint256(value ? 1 : 0) << offset);
}
// Unsigned
/**
* @dev Inserts a 10 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` can be represented using 10 bits.
*/
function insertUint10(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_10 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` can be represented using 31 bits.
*/
function insertUint31(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_31 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 64 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` can be represented using 64 bits.
*/
function insertUint64(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_64 << offset));
return clearedWord | bytes32(value << offset);
}
// Signed
/**
* @dev Inserts a 22 bits signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` can be represented using 22 bits.
*/
function insertInt22(
bytes32 word,
int256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_22 << offset));
// Integer values need masking to remove the upper bits of negative values.
return clearedWord | bytes32((uint256(value) & _MASK_22) << offset);
}
// Encoding
// Unsigned
/**
* @dev Encodes a 31 bit unsigned integer shifted by an offset.
*
* The return value can be logically ORed with other encoded values to form a 256 bit word.
*/
function encodeUint31(uint256 value, uint256 offset) internal pure returns (bytes32) {
return bytes32(value << offset);
}
// Signed
/**
* @dev Encodes a 22 bits signed integer shifted by an offset.
*
* The return value can be logically ORed with other encoded values to form a 256 bit word.
*/
function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) {
// Integer values need masking to remove the upper bits of negative values.
return bytes32((uint256(value) & _MASK_22) << offset);
}
/**
* @dev Encodes a 53 bits signed integer shifted by an offset.
*
* The return value can be logically ORed with other encoded values to form a 256 bit word.
*/
function encodeInt53(int256 value, uint256 offset) internal pure returns (bytes32) {
// Integer values need masking to remove the upper bits of negative values.
return bytes32((uint256(value) & _MASK_53) << offset);
}
// Decoding
/**
* @dev Decodes and returns a boolean shifted by an offset from a 256 bit word.
*/
function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool) {
return (uint256(word >> offset) & _MASK_1) == 1;
}
// Unsigned
/**
* @dev Decodes and returns a 10 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint10(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_10;
}
/**
* @dev Decodes and returns a 31 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint31(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_31;
}
/**
* @dev Decodes and returns a 64 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint64(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_64;
}
// Signed
/**
* @dev Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word.
*/
function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) {
int256 value = int256(uint256(word >> offset) & _MASK_22);
// In case the decoded value is greater than the max positive integer that can be represented with 22 bits,
// we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit
// representation.
return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value;
}
/**
* @dev Decodes and returns a 53 bits signed integer shifted by an offset from a 256 bit word.
*/
function decodeInt53(bytes32 word, uint256 offset) internal pure returns (int256) {
int256 value = int256(uint256(word >> offset) & _MASK_53);
// In case the decoded value is greater than the max positive integer that can be represented with 53 bits,
// we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit
// representation.
return value > _MAX_INT_53 ? (value | int256(~_MASK_53)) : value;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/math/FixedPoint.sol";
import "../../lib/helpers/InputHelpers.sol";
import "../BaseMinimalSwapInfoPool.sol";
import "./WeightedMath.sol";
import "./WeightedPoolUserDataHelpers.sol";
// This contract relies on tons of immutable state variables to perform efficient lookup, without resorting to storage
// reads. Because immutable arrays are not supported, we instead declare a fixed set of state variables plus total
// count, resulting in a large number of state variables.
contract WeightedPool is BaseMinimalSwapInfoPool, WeightedMath {
using FixedPoint for uint256;
using WeightedPoolUserDataHelpers for bytes;
// The protocol fees will always be charged using the token associated with the max weight in the pool.
// Since these Pools will register tokens only once, we can assume this index will be constant.
uint256 private immutable _maxWeightTokenIndex;
uint256 private immutable _normalizedWeight0;
uint256 private immutable _normalizedWeight1;
uint256 private immutable _normalizedWeight2;
uint256 private immutable _normalizedWeight3;
uint256 private immutable _normalizedWeight4;
uint256 private immutable _normalizedWeight5;
uint256 private immutable _normalizedWeight6;
uint256 private immutable _normalizedWeight7;
uint256 private _lastInvariant;
enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT }
enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT }
constructor(
IVault vault,
string memory name,
string memory symbol,
IERC20[] memory tokens,
uint256[] memory normalizedWeights,
uint256 swapFeePercentage,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration,
address owner
)
BaseMinimalSwapInfoPool(
vault,
name,
symbol,
tokens,
swapFeePercentage,
pauseWindowDuration,
bufferPeriodDuration,
owner
)
{
uint256 numTokens = tokens.length;
InputHelpers.ensureInputLengthMatch(numTokens, normalizedWeights.length);
// Ensure each normalized weight is above them minimum and find the token index of the maximum weight
uint256 normalizedSum = 0;
uint256 maxWeightTokenIndex = 0;
uint256 maxNormalizedWeight = 0;
for (uint8 i = 0; i < numTokens; i++) {
uint256 normalizedWeight = normalizedWeights[i];
_require(normalizedWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT);
normalizedSum = normalizedSum.add(normalizedWeight);
if (normalizedWeight > maxNormalizedWeight) {
maxWeightTokenIndex = i;
maxNormalizedWeight = normalizedWeight;
}
}
// Ensure that the normalized weights sum to ONE
_require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT);
_maxWeightTokenIndex = maxWeightTokenIndex;
_normalizedWeight0 = normalizedWeights.length > 0 ? normalizedWeights[0] : 0;
_normalizedWeight1 = normalizedWeights.length > 1 ? normalizedWeights[1] : 0;
_normalizedWeight2 = normalizedWeights.length > 2 ? normalizedWeights[2] : 0;
_normalizedWeight3 = normalizedWeights.length > 3 ? normalizedWeights[3] : 0;
_normalizedWeight4 = normalizedWeights.length > 4 ? normalizedWeights[4] : 0;
_normalizedWeight5 = normalizedWeights.length > 5 ? normalizedWeights[5] : 0;
_normalizedWeight6 = normalizedWeights.length > 6 ? normalizedWeights[6] : 0;
_normalizedWeight7 = normalizedWeights.length > 7 ? normalizedWeights[7] : 0;
}
function _normalizedWeight(IERC20 token) internal view virtual returns (uint256) {
// prettier-ignore
if (token == _token0) { return _normalizedWeight0; }
else if (token == _token1) { return _normalizedWeight1; }
else if (token == _token2) { return _normalizedWeight2; }
else if (token == _token3) { return _normalizedWeight3; }
else if (token == _token4) { return _normalizedWeight4; }
else if (token == _token5) { return _normalizedWeight5; }
else if (token == _token6) { return _normalizedWeight6; }
else if (token == _token7) { return _normalizedWeight7; }
else {
_revert(Errors.INVALID_TOKEN);
}
}
function _normalizedWeights() internal view virtual returns (uint256[] memory) {
uint256 totalTokens = _getTotalTokens();
uint256[] memory normalizedWeights = new uint256[](totalTokens);
// prettier-ignore
{
if (totalTokens > 0) { normalizedWeights[0] = _normalizedWeight0; } else { return normalizedWeights; }
if (totalTokens > 1) { normalizedWeights[1] = _normalizedWeight1; } else { return normalizedWeights; }
if (totalTokens > 2) { normalizedWeights[2] = _normalizedWeight2; } else { return normalizedWeights; }
if (totalTokens > 3) { normalizedWeights[3] = _normalizedWeight3; } else { return normalizedWeights; }
if (totalTokens > 4) { normalizedWeights[4] = _normalizedWeight4; } else { return normalizedWeights; }
if (totalTokens > 5) { normalizedWeights[5] = _normalizedWeight5; } else { return normalizedWeights; }
if (totalTokens > 6) { normalizedWeights[6] = _normalizedWeight6; } else { return normalizedWeights; }
if (totalTokens > 7) { normalizedWeights[7] = _normalizedWeight7; } else { return normalizedWeights; }
}
return normalizedWeights;
}
function getLastInvariant() external view returns (uint256) {
return _lastInvariant;
}
/**
* @dev Returns the current value of the invariant.
*/
function getInvariant() public view returns (uint256) {
(, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId());
// Since the Pool hooks always work with upscaled balances, we manually
// upscale here for consistency
_upscaleArray(balances, _scalingFactors());
uint256[] memory normalizedWeights = _normalizedWeights();
return WeightedMath._calculateInvariant(normalizedWeights, balances);
}
function getNormalizedWeights() external view returns (uint256[] memory) {
return _normalizedWeights();
}
// Base Pool handlers
// Swap
function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) internal view virtual override whenNotPaused returns (uint256) {
// Swaps are disabled while the contract is paused.
return
WeightedMath._calcOutGivenIn(
currentBalanceTokenIn,
_normalizedWeight(swapRequest.tokenIn),
currentBalanceTokenOut,
_normalizedWeight(swapRequest.tokenOut),
swapRequest.amount
);
}
function _onSwapGivenOut(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) internal view virtual override whenNotPaused returns (uint256) {
// Swaps are disabled while the contract is paused.
return
WeightedMath._calcInGivenOut(
currentBalanceTokenIn,
_normalizedWeight(swapRequest.tokenIn),
currentBalanceTokenOut,
_normalizedWeight(swapRequest.tokenOut),
swapRequest.amount
);
}
// Initialize
function _onInitializePool(
bytes32,
address,
address,
bytes memory userData
) internal virtual override whenNotPaused returns (uint256, uint256[] memory) {
// It would be strange for the Pool to be paused before it is initialized, but for consistency we prevent
// initialization in this case.
WeightedPool.JoinKind kind = userData.joinKind();
_require(kind == WeightedPool.JoinKind.INIT, Errors.UNINITIALIZED);
uint256[] memory amountsIn = userData.initialAmountsIn();
InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length);
_upscaleArray(amountsIn, _scalingFactors());
uint256[] memory normalizedWeights = _normalizedWeights();
uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn);
// Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more
// consistent in Pools with similar compositions but different number of tokens.
uint256 bptAmountOut = Math.mul(invariantAfterJoin, _getTotalTokens());
_lastInvariant = invariantAfterJoin;
return (bptAmountOut, amountsIn);
}
// Join
function _onJoinPool(
bytes32,
address,
address,
uint256[] memory balances,
uint256,
uint256 protocolSwapFeePercentage,
bytes memory userData
)
internal
virtual
override
whenNotPaused
returns (
uint256,
uint256[] memory,
uint256[] memory
)
{
// All joins are disabled while the contract is paused.
uint256[] memory normalizedWeights = _normalizedWeights();
// Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join
// or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas
// computing them on each individual swap
uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances);
uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(
balances,
normalizedWeights,
_lastInvariant,
invariantBeforeJoin,
protocolSwapFeePercentage
);
// Update current balances by subtracting the protocol fee amounts
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub);
(uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData);
// Update the invariant with the balances the Pool will have after the join, in order to compute the
// protocol swap fee amounts due in future joins and exits.
_lastInvariant = _invariantAfterJoin(balances, amountsIn, normalizedWeights);
return (bptAmountOut, amountsIn, dueProtocolFeeAmounts);
}
function _doJoin(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
JoinKind kind = userData.joinKind();
if (kind == JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) {
return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData);
} else if (kind == JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) {
return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData);
} else {
_revert(Errors.UNHANDLED_JOIN_KIND);
}
}
function _joinExactTokensInForBPTOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
(uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut();
InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length);
_upscaleArray(amountsIn, _scalingFactors());
uint256 bptAmountOut = WeightedMath._calcBptOutGivenExactTokensIn(
balances,
normalizedWeights,
amountsIn,
totalSupply(),
_swapFeePercentage
);
_require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT);
return (bptAmountOut, amountsIn);
}
function _joinTokenInForExactBPTOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
(uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut();
// Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`.
_require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS);
uint256[] memory amountsIn = new uint256[](_getTotalTokens());
amountsIn[tokenIndex] = WeightedMath._calcTokenInGivenExactBptOut(
balances[tokenIndex],
normalizedWeights[tokenIndex],
bptAmountOut,
totalSupply(),
_swapFeePercentage
);
return (bptAmountOut, amountsIn);
}
// Exit
function _onExitPool(
bytes32,
address,
address,
uint256[] memory balances,
uint256,
uint256 protocolSwapFeePercentage,
bytes memory userData
)
internal
virtual
override
returns (
uint256 bptAmountIn,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
)
{
// Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens
// out) remain functional.
uint256[] memory normalizedWeights = _normalizedWeights();
if (_isNotPaused()) {
// Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous
// join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids
// spending gas calculating the fees on each individual swap.
uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances);
dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(
balances,
normalizedWeights,
_lastInvariant,
invariantBeforeExit,
protocolSwapFeePercentage
);
// Update current balances by subtracting the protocol fee amounts
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub);
} else {
// If the contract is paused, swap protocol fee amounts are not charged to avoid extra calculations and
// reduce the potential for errors.
dueProtocolFeeAmounts = new uint256[](_getTotalTokens());
}
(bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData);
// Update the invariant with the balances the Pool will have after the exit, in order to compute the
// protocol swap fees due in future joins and exits.
_lastInvariant = _invariantAfterExit(balances, amountsOut, normalizedWeights);
return (bptAmountIn, amountsOut, dueProtocolFeeAmounts);
}
function _doExit(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view returns (uint256, uint256[] memory) {
ExitKind kind = userData.exitKind();
if (kind == ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) {
return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData);
} else if (kind == ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) {
return _exitExactBPTInForTokensOut(balances, userData);
} else {
// ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT
return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData);
}
}
function _exitExactBPTInForTokenOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view whenNotPaused returns (uint256, uint256[] memory) {
// This exit function is disabled if the contract is paused.
(uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut();
// Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
_require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS);
// We exit in a single token, so we initialize amountsOut with zeros
uint256[] memory amountsOut = new uint256[](_getTotalTokens());
// And then assign the result to the selected token
amountsOut[tokenIndex] = WeightedMath._calcTokenOutGivenExactBptIn(
balances[tokenIndex],
normalizedWeights[tokenIndex],
bptAmountIn,
totalSupply(),
_swapFeePercentage
);
return (bptAmountIn, amountsOut);
}
function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData)
private
view
returns (uint256, uint256[] memory)
{
// This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted
// in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency.
// This particular exit function is the only one that remains available because it is the simplest one, and
// therefore the one with the lowest likelihood of errors.
uint256 bptAmountIn = userData.exactBptInForTokensOut();
// Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply());
return (bptAmountIn, amountsOut);
}
function _exitBPTInForExactTokensOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private view whenNotPaused returns (uint256, uint256[] memory) {
// This exit function is disabled if the contract is paused.
(uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut();
InputHelpers.ensureInputLengthMatch(amountsOut.length, _getTotalTokens());
_upscaleArray(amountsOut, _scalingFactors());
uint256 bptAmountIn = WeightedMath._calcBptInGivenExactTokensOut(
balances,
normalizedWeights,
amountsOut,
totalSupply(),
_swapFeePercentage
);
_require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT);
return (bptAmountIn, amountsOut);
}
// Helpers
function _getDueProtocolFeeAmounts(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256 previousInvariant,
uint256 currentInvariant,
uint256 protocolSwapFeePercentage
) private view returns (uint256[] memory) {
// Initialize with zeros
uint256[] memory dueProtocolFeeAmounts = new uint256[](_getTotalTokens());
// Early return if the protocol swap fee percentage is zero, saving gas.
if (protocolSwapFeePercentage == 0) {
return dueProtocolFeeAmounts;
}
// The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the
// token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool.
dueProtocolFeeAmounts[_maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount(
balances[_maxWeightTokenIndex],
normalizedWeights[_maxWeightTokenIndex],
previousInvariant,
currentInvariant,
protocolSwapFeePercentage
);
return dueProtocolFeeAmounts;
}
/**
* @dev Returns the value of the invariant given `balances`, assuming they are increased by `amountsIn`. All
* amounts are expected to be upscaled.
*/
function _invariantAfterJoin(
uint256[] memory balances,
uint256[] memory amountsIn,
uint256[] memory normalizedWeights
) private view returns (uint256) {
_mutateAmounts(balances, amountsIn, FixedPoint.add);
return WeightedMath._calculateInvariant(normalizedWeights, balances);
}
function _invariantAfterExit(
uint256[] memory balances,
uint256[] memory amountsOut,
uint256[] memory normalizedWeights
) private view returns (uint256) {
_mutateAmounts(balances, amountsOut, FixedPoint.sub);
return WeightedMath._calculateInvariant(normalizedWeights, balances);
}
/**
* @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`.
*
* Equivalent to `amounts = amounts.map(mutation)`.
*/
function _mutateAmounts(
uint256[] memory toMutate,
uint256[] memory arguments,
function(uint256, uint256) pure returns (uint256) mutation
) private view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
toMutate[i] = mutation(toMutate[i], arguments[i]);
}
}
/**
* @dev This function returns the appreciation of one BPT relative to the
* underlying tokens. This starts at 1 when the pool is created and grows over time
*/
function getRate() public view returns (uint256) {
// The initial BPT supply is equal to the invariant times the number of tokens.
return Math.mul(getInvariant(), _getTotalTokens()).divDown(totalSupply());
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "./BasePool.sol";
import "../vault/interfaces/IMinimalSwapInfoPool.sol";
/**
* @dev Extension of `BasePool`, adding a handler for `IMinimalSwapInfoPool.onSwap`.
*
* Derived contracts must implement `_onSwapGivenIn` and `_onSwapGivenOut` along with `BasePool`'s virtual functions.
*/
abstract contract BaseMinimalSwapInfoPool is IMinimalSwapInfoPool, BasePool {
constructor(
IVault vault,
string memory name,
string memory symbol,
IERC20[] memory tokens,
uint256 swapFeePercentage,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration,
address owner
)
BasePool(
vault,
tokens.length == 2 ? IVault.PoolSpecialization.TWO_TOKEN : IVault.PoolSpecialization.MINIMAL_SWAP_INFO,
name,
symbol,
tokens,
swapFeePercentage,
pauseWindowDuration,
bufferPeriodDuration,
owner
)
{
// solhint-disable-previous-line no-empty-blocks
}
// Swap Hooks
function onSwap(
SwapRequest memory request,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) external view virtual override returns (uint256) {
uint256 scalingFactorTokenIn = _scalingFactor(request.tokenIn);
uint256 scalingFactorTokenOut = _scalingFactor(request.tokenOut);
if (request.kind == IVault.SwapKind.GIVEN_IN) {
// Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis.
request.amount = _subtractSwapFeeAmount(request.amount);
// All token amounts are upscaled.
balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn);
balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut);
request.amount = _upscale(request.amount, scalingFactorTokenIn);
uint256 amountOut = _onSwapGivenIn(request, balanceTokenIn, balanceTokenOut);
// amountOut tokens are exiting the Pool, so we round down.
return _downscaleDown(amountOut, scalingFactorTokenOut);
} else {
// All token amounts are upscaled.
balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn);
balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut);
request.amount = _upscale(request.amount, scalingFactorTokenOut);
uint256 amountIn = _onSwapGivenOut(request, balanceTokenIn, balanceTokenOut);
// amountIn tokens are entering the Pool, so we round up.
amountIn = _downscaleUp(amountIn, scalingFactorTokenIn);
// Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis.
return _addSwapFeeAmount(amountIn);
}
}
/*
* @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known.
*
* Returns the amount of tokens that will be taken from the Pool in return.
*
* All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. The swap fee has already
* been deducted from `swapRequest.amount`.
*
* The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the
* Vault.
*/
function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) internal view virtual returns (uint256);
/*
* @dev Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known.
*
* Returns the amount of tokens that will be granted to the Pool in return.
*
* All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled.
*
* The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap fee
* and returning it to the Vault.
*/
function _onSwapGivenOut(
SwapRequest memory swapRequest,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) internal view virtual returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/FixedPoint.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/helpers/TemporarilyPausable.sol";
import "../lib/openzeppelin/ERC20.sol";
import "./BalancerPoolToken.sol";
import "./BasePoolAuthorization.sol";
import "../vault/interfaces/IVault.sol";
import "../vault/interfaces/IBasePool.sol";
// This contract relies on tons of immutable state variables to perform efficient lookup, without resorting to storage
// reads. Because immutable arrays are not supported, we instead declare a fixed set of state variables plus a total
// count, resulting in a large number of state variables.
// solhint-disable max-states-count
/**
* @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with an immutable set
* of registered tokens, no Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism.
*
* Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that
* derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the
* `whenNotPaused` modifier.
*
* No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer.
*
* Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from
* BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces
* and implement the swap callbacks themselves.
*/
abstract contract BasePool is IBasePool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable {
using FixedPoint for uint256;
uint256 private constant _MIN_TOKENS = 2;
uint256 private constant _MAX_TOKENS = 8;
// 1e18 corresponds to 1.0, or a 100% fee
uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001%
uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10%
uint256 private constant _MINIMUM_BPT = 1e6;
uint256 internal _swapFeePercentage;
IVault private immutable _vault;
bytes32 private immutable _poolId;
uint256 private immutable _totalTokens;
IERC20 internal immutable _token0;
IERC20 internal immutable _token1;
IERC20 internal immutable _token2;
IERC20 internal immutable _token3;
IERC20 internal immutable _token4;
IERC20 internal immutable _token5;
IERC20 internal immutable _token6;
IERC20 internal immutable _token7;
// All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will
// not change throughout its lifetime, and store the corresponding scaling factor for each at construction time.
// These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported.
uint256 internal immutable _scalingFactor0;
uint256 internal immutable _scalingFactor1;
uint256 internal immutable _scalingFactor2;
uint256 internal immutable _scalingFactor3;
uint256 internal immutable _scalingFactor4;
uint256 internal immutable _scalingFactor5;
uint256 internal immutable _scalingFactor6;
uint256 internal immutable _scalingFactor7;
event SwapFeePercentageChanged(uint256 swapFeePercentage);
constructor(
IVault vault,
IVault.PoolSpecialization specialization,
string memory name,
string memory symbol,
IERC20[] memory tokens,
uint256 swapFeePercentage,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration,
address owner
)
// Base Pools are expected to be deployed using factories. By using the factory address as the action
// disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for
// simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in
// any Pool created by the same factory), while still making action identifiers unique among different factories
// if the selectors match, preventing accidental errors.
Authentication(bytes32(uint256(msg.sender)))
BalancerPoolToken(name, symbol)
BasePoolAuthorization(owner)
TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration)
{
_require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS);
_require(tokens.length <= _MAX_TOKENS, Errors.MAX_TOKENS);
// The Vault only requires the token list to be ordered for the Two Token Pools specialization. However,
// to make the developer experience consistent, we are requiring this condition for all the native pools.
// Also, since these Pools will register tokens only once, we can ensure the Pool tokens will follow the same
// order. We rely on this property to make Pools simpler to write, as it lets us assume that the
// order of token-specific parameters (such as token weights) will not change.
InputHelpers.ensureArrayIsSorted(tokens);
_setSwapFeePercentage(swapFeePercentage);
bytes32 poolId = vault.registerPool(specialization);
// Pass in zero addresses for Asset Managers
vault.registerTokens(poolId, tokens, new address[](tokens.length));
// Set immutable state variables - these cannot be read from during construction
_vault = vault;
_poolId = poolId;
_totalTokens = tokens.length;
// Immutable variables cannot be initialized inside an if statement, so we must do conditional assignments
_token0 = tokens.length > 0 ? tokens[0] : IERC20(0);
_token1 = tokens.length > 1 ? tokens[1] : IERC20(0);
_token2 = tokens.length > 2 ? tokens[2] : IERC20(0);
_token3 = tokens.length > 3 ? tokens[3] : IERC20(0);
_token4 = tokens.length > 4 ? tokens[4] : IERC20(0);
_token5 = tokens.length > 5 ? tokens[5] : IERC20(0);
_token6 = tokens.length > 6 ? tokens[6] : IERC20(0);
_token7 = tokens.length > 7 ? tokens[7] : IERC20(0);
_scalingFactor0 = tokens.length > 0 ? _computeScalingFactor(tokens[0]) : 0;
_scalingFactor1 = tokens.length > 1 ? _computeScalingFactor(tokens[1]) : 0;
_scalingFactor2 = tokens.length > 2 ? _computeScalingFactor(tokens[2]) : 0;
_scalingFactor3 = tokens.length > 3 ? _computeScalingFactor(tokens[3]) : 0;
_scalingFactor4 = tokens.length > 4 ? _computeScalingFactor(tokens[4]) : 0;
_scalingFactor5 = tokens.length > 5 ? _computeScalingFactor(tokens[5]) : 0;
_scalingFactor6 = tokens.length > 6 ? _computeScalingFactor(tokens[6]) : 0;
_scalingFactor7 = tokens.length > 7 ? _computeScalingFactor(tokens[7]) : 0;
}
// Getters / Setters
function getVault() public view returns (IVault) {
return _vault;
}
function getPoolId() public view returns (bytes32) {
return _poolId;
}
function _getTotalTokens() internal view returns (uint256) {
return _totalTokens;
}
function getSwapFeePercentage() external view returns (uint256) {
return _swapFeePercentage;
}
// Caller must be approved by the Vault's Authorizer
function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused {
_setSwapFeePercentage(swapFeePercentage);
}
function _setSwapFeePercentage(uint256 swapFeePercentage) private {
_require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE);
_require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE);
_swapFeePercentage = swapFeePercentage;
emit SwapFeePercentageChanged(swapFeePercentage);
}
// Caller must be approved by the Vault's Authorizer
function setPaused(bool paused) external authenticate {
_setPaused(paused);
}
// Join / Exit Hooks
modifier onlyVault(bytes32 poolId) {
_require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT);
_require(poolId == getPoolId(), Errors.INVALID_POOL_ID);
_;
}
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
uint256[] memory scalingFactors = _scalingFactors();
if (totalSupply() == 0) {
(uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool(poolId, sender, recipient, userData);
// On initialization, we lock _MINIMUM_BPT by minting it for the zero address. This BPT acts as a minimum
// as it will never be burned, which reduces potential issues with rounding, and also prevents the Pool from
// ever being fully drained.
_require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT);
_mintPoolTokens(address(0), _MINIMUM_BPT);
_mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT);
// amountsIn are amounts entering the Pool, so we round up.
_downscaleUpArray(amountsIn, scalingFactors);
return (amountsIn, new uint256[](_getTotalTokens()));
} else {
_upscaleArray(balances, scalingFactors);
(uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) = _onJoinPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData
);
// Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it.
_mintPoolTokens(recipient, bptAmountOut);
// amountsIn are amounts entering the Pool, so we round up.
_downscaleUpArray(amountsIn, scalingFactors);
// dueProtocolFeeAmounts are amounts exiting the Pool, so we round down.
_downscaleDownArray(dueProtocolFeeAmounts, scalingFactors);
return (amountsIn, dueProtocolFeeAmounts);
}
}
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
uint256[] memory scalingFactors = _scalingFactors();
_upscaleArray(balances, scalingFactors);
(uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData
);
// Note we no longer use `balances` after calling `_onExitPool`, which may mutate it.
_burnPoolTokens(sender, bptAmountIn);
// Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down.
_downscaleDownArray(amountsOut, scalingFactors);
_downscaleDownArray(dueProtocolFeeAmounts, scalingFactors);
return (amountsOut, dueProtocolFeeAmounts);
}
// Query functions
/**
* @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `sender` would have to supply.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryJoin(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptOut, uint256[] memory amountsIn) {
InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens());
_queryAction(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData,
_onJoinPool,
_downscaleUpArray
);
// The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement,
// and we don't need to return anything here - it just silences compiler warnings.
return (bptOut, amountsIn);
}
/**
* @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `recipient` would receive.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryExit(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptIn, uint256[] memory amountsOut) {
InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens());
_queryAction(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData,
_onExitPool,
_downscaleDownArray
);
// The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement,
// and we don't need to return anything here - it just silences compiler warnings.
return (bptIn, amountsOut);
}
// Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are
// upscaled.
/**
* @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero.
*
* Returns the amount of BPT to mint, and the token amounts the Pool will receive in return.
*
* Minted BPT will be sent to `recipient`, except for _MINIMUM_BPT, which will be deducted from this amount and sent
* to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP from
* ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire Pool's
* lifetime.
*
* The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will
* be downscaled (rounding up) before being returned to the Vault.
*/
function _onInitializePool(
bytes32 poolId,
address sender,
address recipient,
bytes memory userData
) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn);
/**
* @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`).
*
* Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of
* tokens to pay in protocol swap fees.
*
* Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when
* performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely.
*
* Minted BPT will be sent to `recipient`.
*
* The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will
* be downscaled (rounding up) before being returned to the Vault.
*
* Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These
* amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault.
*/
function _onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
)
internal
virtual
returns (
uint256 bptAmountOut,
uint256[] memory amountsIn,
uint256[] memory dueProtocolFeeAmounts
);
/**
* @dev Called whenever the Pool is exited.
*
* Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and
* the number of tokens to pay in protocol swap fees.
*
* Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when
* performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely.
*
* BPT will be burnt from `sender`.
*
* The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled
* (rounding down) before being returned to the Vault.
*
* Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These
* amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault.
*/
function _onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
)
internal
virtual
returns (
uint256 bptAmountIn,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
);
// Internal functions
/**
* @dev Adds swap fee amount to `amount`, returning a higher value.
*/
function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) {
// This returns amount + fee amount, so we round up (favoring a higher fee amount).
return amount.divUp(_swapFeePercentage.complement());
}
/**
* @dev Subtracts swap fee amount from `amount`, returning a lower value.
*/
function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) {
// This returns amount - fee amount, so we round up (favoring a higher fee amount).
uint256 feeAmount = amount.mulUp(_swapFeePercentage);
return amount.sub(feeAmount);
}
// Scaling
/**
* @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if
* it had 18 decimals.
*/
function _computeScalingFactor(IERC20 token) private view returns (uint256) {
// Tokens that don't implement the `decimals` method are not supported.
uint256 tokenDecimals = ERC20(address(token)).decimals();
// Tokens with more than 18 decimals are not supported.
uint256 decimalsDifference = Math.sub(18, tokenDecimals);
return 10**decimalsDifference;
}
/**
* @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the
* Pool.
*/
function _scalingFactor(IERC20 token) internal view returns (uint256) {
// prettier-ignore
if (token == _token0) { return _scalingFactor0; }
else if (token == _token1) { return _scalingFactor1; }
else if (token == _token2) { return _scalingFactor2; }
else if (token == _token3) { return _scalingFactor3; }
else if (token == _token4) { return _scalingFactor4; }
else if (token == _token5) { return _scalingFactor5; }
else if (token == _token6) { return _scalingFactor6; }
else if (token == _token7) { return _scalingFactor7; }
else {
_revert(Errors.INVALID_TOKEN);
}
}
/**
* @dev Returns all the scaling factors in the same order as the registered tokens. The Vault will always
* pass balances in this order when calling any of the Pool hooks
*/
function _scalingFactors() internal view returns (uint256[] memory) {
uint256 totalTokens = _getTotalTokens();
uint256[] memory scalingFactors = new uint256[](totalTokens);
// prettier-ignore
{
if (totalTokens > 0) { scalingFactors[0] = _scalingFactor0; } else { return scalingFactors; }
if (totalTokens > 1) { scalingFactors[1] = _scalingFactor1; } else { return scalingFactors; }
if (totalTokens > 2) { scalingFactors[2] = _scalingFactor2; } else { return scalingFactors; }
if (totalTokens > 3) { scalingFactors[3] = _scalingFactor3; } else { return scalingFactors; }
if (totalTokens > 4) { scalingFactors[4] = _scalingFactor4; } else { return scalingFactors; }
if (totalTokens > 5) { scalingFactors[5] = _scalingFactor5; } else { return scalingFactors; }
if (totalTokens > 6) { scalingFactors[6] = _scalingFactor6; } else { return scalingFactors; }
if (totalTokens > 7) { scalingFactors[7] = _scalingFactor7; } else { return scalingFactors; }
}
return scalingFactors;
}
/**
* @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed
* scaling or not.
*/
function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
return Math.mul(amount, scalingFactor);
}
/**
* @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates*
* the `amounts` array.
*/
function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = Math.mul(amounts[i], scalingFactors[i]);
}
}
/**
* @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on
* whether it needed scaling or not. The result is rounded down.
*/
function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
return Math.divDown(amount, scalingFactor);
}
/**
* @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead
* *mutates* the `amounts` array.
*/
function _downscaleDownArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = Math.divDown(amounts[i], scalingFactors[i]);
}
}
/**
* @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on
* whether it needed scaling or not. The result is rounded up.
*/
function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
return Math.divUp(amount, scalingFactor);
}
/**
* @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead
* *mutates* the `amounts` array.
*/
function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = Math.divUp(amounts[i], scalingFactors[i]);
}
}
function _getAuthorizer() internal view override returns (IAuthorizer) {
// Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which
// accounts can call permissioned functions: for example, to perform emergency pauses.
// If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under
// Governance control.
return getVault().getAuthorizer();
}
function _queryAction(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData,
function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory)
internal
returns (uint256, uint256[] memory, uint256[] memory) _action,
function(uint256[] memory, uint256[] memory) internal view _downscaleArray
) private {
// This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed
// explanation.
if (msg.sender != address(this)) {
// We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of
// the preceding if statement will be executed instead.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(msg.data);
// solhint-disable-next-line no-inline-assembly
assembly {
// This call should always revert to decode the bpt and token amounts from the revert reason
switch success
case 0 {
// Note we are manually writing the memory slot 0. We can safely overwrite whatever is
// stored there as we take full control of the execution and then immediately return.
// We copy the first 4 bytes to check if it matches with the expected signature, otherwise
// there was another revert reason and we should forward it.
returndatacopy(0, 0, 0x04)
let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
// If the first 4 bytes don't match with the expected signature, we forward the revert reason.
if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
// The returndata contains the signature, followed by the raw memory representation of the
// `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded
// representation of these.
// An ABI-encoded response will include one additional field to indicate the starting offset of
// the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the
// returndata.
//
// In returndata:
// [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ]
// [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ]
//
// We now need to return (ABI-encoded values):
// [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ]
// [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ]
// We copy 32 bytes for the `bptAmount` from returndata into memory.
// Note that we skip the first 4 bytes for the error signature
returndatacopy(0, 0x04, 32)
// The offsets are 32-bytes long, so the array of `tokenAmounts` will start after
// the initial 64 bytes.
mstore(0x20, 64)
// We now copy the raw memory array for the `tokenAmounts` from returndata into memory.
// Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also
// skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount.
returndatacopy(0x40, 0x24, sub(returndatasize(), 36))
// We finally return the ABI-encoded uint256 and the array, which has a total length equal to
// the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the
// error signature.
return(0, add(returndatasize(), 28))
}
default {
// This call should always revert, but we fail nonetheless if that didn't happen
invalid()
}
}
} else {
uint256[] memory scalingFactors = _scalingFactors();
_upscaleArray(balances, scalingFactors);
(uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData
);
_downscaleArray(tokenAmounts, scalingFactors);
// solhint-disable-next-line no-inline-assembly
assembly {
// We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of
// a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values
// Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32
let size := mul(mload(tokenAmounts), 32)
// We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there
// will be at least one available slot due to how the memory scratch space works.
// We can safely overwrite whatever is stored in this slot as we will revert immediately after that.
let start := sub(tokenAmounts, 0x20)
mstore(start, bptAmount)
// We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb
// We use the previous slot to `bptAmount`.
mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb)
start := sub(start, 0x04)
// When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return
// the `bptAmount`, the array 's length, and the error signature.
revert(start, add(size, 68))
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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 experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IWETH.sol";
import "./IAsset.sol";
import "./IAuthorizer.sol";
import "./IFlashLoanRecipient.sol";
import "../ProtocolFeesCollector.sol";
import "../../lib/helpers/ISignaturesValidator.sol";
import "../../lib/helpers/ITemporarilyPausable.sol";
pragma solidity ^0.7.0;
/**
* @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that
* don't override one of these declarations.
*/
interface IVault is ISignaturesValidator, ITemporarilyPausable {
// Generalities about the Vault:
//
// - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are
// transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling
// `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by
// calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning
// a boolean value: in these scenarios, a non-reverting call is assumed to be successful.
//
// - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.
// while execution control is transferred to a token contract during a swap) will result in a revert. View
// functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.
// Contracts calling view functions in the Vault must make sure the Vault has not already been entered.
//
// - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.
// Authorizer
//
// Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists
// outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller
// can perform a given action.
/**
* @dev Returns the Vault's Authorizer.
*/
function getAuthorizer() external view returns (IAuthorizer);
/**
* @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.
*
* Emits an `AuthorizerChanged` event.
*/
function setAuthorizer(IAuthorizer newAuthorizer) external;
/**
* @dev Emitted when a new authorizer is set by `setAuthorizer`.
*/
event AuthorizerChanged(IAuthorizer indexed newAuthorizer);
// Relayers
//
// Additionally, it is possible for an account to perform certain actions on behalf of another one, using their
// Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,
// and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield
// this power, two things must occur:
// - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This
// means that Balancer governance must approve each individual contract to act as a relayer for the intended
// functions.
// - Each user must approve the relayer to act on their behalf.
// This double protection means users cannot be tricked into approving malicious relayers (because they will not
// have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised
// Authorizer or governance drain user funds, since they would also need to be approved by each individual user.
/**
* @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
*/
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
/**
* @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
*
* Emits a `RelayerApprovalChanged` event.
*/
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
/**
* @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
*/
event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Returns `user`'s Internal Balance for a set of tokens.
*/
function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }
/**
* @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
* interacting with Pools using Internal Balance.
*
* Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
* address.
*/
event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
/**
* @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
*/
event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);
// Pools
//
// There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
// functionality:
//
// - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
// balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
// which increase with the number of registered tokens.
//
// - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
// balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
// constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
// independent of the number of registered tokens.
//
// - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
// minimal swap info Pools, these are called via IMinimalSwapInfoPool.
enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }
/**
* @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
* is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
* changed.
*
* The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
* depending on the chosen specialization setting. This contract is known as the Pool's contract.
*
* Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
* multiple Pools may share the same contract.
*
* Emits a `PoolRegistered` event.
*/
function registerPool(PoolSpecialization specialization) external returns (bytes32);
/**
* @dev Emitted when a Pool is registered by calling `registerPool`.
*/
event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);
/**
* @dev Returns a Pool's contract address and specialization setting.
*/
function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
/**
* @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
* exit by receiving registered tokens, and can only swap registered tokens.
*
* Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
* of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
* ascending order.
*
* The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
* Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
* depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
* expected to be highly secured smart contracts with sound design principles, and the decision to register an
* Asset Manager should not be made lightly.
*
* Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
* Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
* different Asset Manager.
*
* Emits a `TokensRegistered` event.
*/
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
/**
* @dev Emitted when a Pool registers tokens by calling `registerTokens`.
*/
event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);
/**
* @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
* balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
* must be deregistered in the same `deregisterTokens` call.
*
* A deregistered token can be re-registered later on, possibly with a different Asset Manager.
*
* Emits a `TokensDeregistered` event.
*/
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
/**
* @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
*/
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
/**
* @dev Returns detailed information for a Pool's registered token.
*
* `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
* withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
* equals the sum of `cash` and `managed`.
*
* Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
* `managed` or `total` balance to be greater than 2^112 - 1.
*
* `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
* join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
* example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
* change for this purpose, and will update `lastChangeBlock`.
*
* `assetManager` is the Pool's token Asset Manager.
*/
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
*/
event PoolBalanceChanged(
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
enum PoolBalanceChangeKind { JOIN, EXIT }
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind { GIVEN_IN, GIVEN_OUT }
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
*/
event Swap(
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
* simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
*
* Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
* the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
* receives are the same that an equivalent `batchSwap` call would receive.
*
* Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
* This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
* approve them for the Vault, or even know a user's address.
*
* Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
* eth_call instead of eth_sendTransaction.
*/
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
// Flash Loans
/**
* @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,
* and then reverting unless the tokens plus a proportional protocol fee have been returned.
*
* The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount
* for each token contract. `tokens` must be sorted in ascending order.
*
* The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the
* `receiveFlashLoan` call.
*
* Emits `FlashLoan` events.
*/
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
/**
* @dev Emitted for each individual flash loan performed by `flashLoan`.
*/
event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);
// Asset Management
//
// Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
// tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
// `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
// controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
// prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
// not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
//
// However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
// for example by lending unused tokens out for interest, or using them to participate in voting protocols.
//
// This concept is unrelated to the IAsset interface.
/**
* @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
*
* Pool Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different Pools and tokens, at once.
*
* For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
*/
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
/**
* Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
*
* Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
*
* Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
* The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
*/
enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }
/**
* @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
*/
event PoolBalanceManaged(
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
// Protocol Fees
//
// Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by
// permissioned accounts.
//
// There are two kinds of protocol fees:
//
// - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.
//
// - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including
// swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,
// Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the
// Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as
// exiting a Pool in debt without first paying their share.
/**
* @dev Returns the current protocol fee module.
*/
function getProtocolFeesCollector() external view returns (ProtocolFeesCollector);
/**
* @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
* error in some part of the system.
*
* The Vault can only be paused during an initial time period, after which pausing is forever disabled.
*
* While the contract is paused, the following features are disabled:
* - depositing and transferring internal balance
* - transferring external balance (using the Vault's allowance)
* - swaps
* - joining Pools
* - Asset Manager interactions
*
* Internal Balance can still be withdrawn, and Pools exited.
*/
function setPaused(bool paused) external;
/**
* @dev Returns the Vault's WETH instance.
*/
function WETH() external view returns (IWETH);
// solhint-disable-previous-line func-name-mixedcase
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "./IVault.sol";
import "./IPoolSwapStructs.sol";
/**
* @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not
* the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from
* either IGeneralPool or IMinimalSwapInfoPool
*/
interface IBasePool is IPoolSwapStructs {
/**
* @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of
* each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault.
* The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect
* the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`.
*
* Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join.
*
* `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account
* designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances
* for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as minting pool shares.
*/
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts);
/**
* @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many
* tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes
* to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`,
* as well as collect the reported amount in protocol fees, which the Pool should calculate based on
* `protocolSwapFeePercentage`.
*
* Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share.
*
* `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account
* to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token
* the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as burning pool shares.
*/
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
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) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
_TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
// Silence state mutability warning without generating bytecode.
// See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and
// https://github.com/ethereum/solidity/issues/2691
this;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "./BalancerErrors.sol";
import "./IAuthentication.sol";
/**
* @dev Building block for performing access control on external functions.
*
* This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied
* to external functions to only make them callable by authorized accounts.
*
* Derived contracts must implement the `_canPerform` function, which holds the actual access control logic.
*/
abstract contract Authentication is IAuthentication {
bytes32 private immutable _actionIdDisambiguator;
/**
* @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in
* multi contract systems.
*
* There are two main uses for it:
* - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers
* unique. The contract's own address is a good option.
* - if the contract belongs to a family that shares action identifiers for the same functions, an identifier
* shared by the entire family (and no other contract) should be used instead.
*/
constructor(bytes32 actionIdDisambiguator) {
_actionIdDisambiguator = actionIdDisambiguator;
}
/**
* @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions.
*/
modifier authenticate() {
_authenticateCaller();
_;
}
/**
* @dev Reverts unless the caller is allowed to call the entry point function.
*/
function _authenticateCaller() internal view {
bytes32 actionId = getActionId(msg.sig);
_require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED);
}
function getActionId(bytes4 selector) public view override returns (bytes32) {
// Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the
// function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of
// multiple contracts.
return keccak256(abi.encodePacked(_actionIdDisambiguator, selector));
}
function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
interface IAuthorizer {
/**
* @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.
*/
function canPerform(
bytes32 actionId,
address account,
address where
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
interface IAuthentication {
/**
* @dev Returns the action identifier associated with the external function described by `selector`.
*/
function getActionId(bytes4 selector) external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "../../lib/openzeppelin/IERC20.sol";
/**
* @dev Interface for the WETH token contract used internally for wrapping and unwrapping, to support
* sending and receiving ETH in joins, swaps, and internal balance deposits and withdrawals.
*/
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
// Inspired by Aave Protocol's IFlashLoanReceiver.
import "../../lib/openzeppelin/IERC20.sol";
interface IFlashLoanRecipient {
/**
* @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
*
* At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
* call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
* Vault, or else the entire flash loan will revert.
*
* `userData` is the same value passed in the `IVault.flashLoan` call.
*/
function receiveFlashLoan(
IERC20[] memory tokens,
uint256[] memory amounts,
uint256[] memory feeAmounts,
bytes memory userData
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "../lib/openzeppelin/IERC20.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/helpers/Authentication.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IAuthorizer.sol";
/**
* @dev This an auxiliary contract to the Vault, deployed by it during construction. It offloads some of the tasks the
* Vault performs to reduce its overall bytecode size.
*
* The current values for all protocol fee percentages are stored here, and any tokens charged as protocol fees are
* sent to this contract, where they may be withdrawn by authorized entities. All authorization tasks are delegated
* to the Vault's own authorizer.
*/
contract ProtocolFeesCollector is Authentication, ReentrancyGuard {
using SafeERC20 for IERC20;
// Absolute maximum fee percentages (1e18 = 100%, 1e16 = 1%).
uint256 private constant _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE = 50e16; // 50%
uint256 private constant _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE = 1e16; // 1%
IVault public immutable vault;
// All fee percentages are 18-decimal fixed point numbers.
// The swap fee is charged whenever a swap occurs, as a percentage of the fee charged by the Pool. These are not
// actually charged on each individual swap: the `Vault` relies on the Pools being honest and reporting fees due
// when users join and exit them.
uint256 private _swapFeePercentage;
// The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent.
uint256 private _flashLoanFeePercentage;
event SwapFeePercentageChanged(uint256 newSwapFeePercentage);
event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);
constructor(IVault _vault)
// The ProtocolFeesCollector is a singleton, so it simply uses its own address to disambiguate action
// identifiers.
Authentication(bytes32(uint256(address(this))))
{
vault = _vault;
}
function withdrawCollectedFees(
IERC20[] calldata tokens,
uint256[] calldata amounts,
address recipient
) external nonReentrant authenticate {
InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 amount = amounts[i];
token.safeTransfer(recipient, amount);
}
}
function setSwapFeePercentage(uint256 newSwapFeePercentage) external authenticate {
_require(newSwapFeePercentage <= _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE, Errors.SWAP_FEE_PERCENTAGE_TOO_HIGH);
_swapFeePercentage = newSwapFeePercentage;
emit SwapFeePercentageChanged(newSwapFeePercentage);
}
function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external authenticate {
_require(
newFlashLoanFeePercentage <= _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE,
Errors.FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH
);
_flashLoanFeePercentage = newFlashLoanFeePercentage;
emit FlashLoanFeePercentageChanged(newFlashLoanFeePercentage);
}
function getSwapFeePercentage() external view returns (uint256) {
return _swapFeePercentage;
}
function getFlashLoanFeePercentage() external view returns (uint256) {
return _flashLoanFeePercentage;
}
function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts) {
feeAmounts = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
feeAmounts[i] = tokens[i].balanceOf(address(this));
}
}
function getAuthorizer() external view returns (IAuthorizer) {
return _getAuthorizer();
}
function _canPerform(bytes32 actionId, address account) internal view override returns (bool) {
return _getAuthorizer().canPerform(actionId, account, address(this));
}
function _getAuthorizer() internal view returns (IAuthorizer) {
return vault.getAuthorizer();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
/**
* @dev Interface for the SignatureValidator helper, used to support meta-transactions.
*/
interface ISignaturesValidator {
/**
* @dev Returns the EIP712 domain separator.
*/
function getDomainSeparator() external view returns (bytes32);
/**
* @dev Returns the next nonce used by an address to sign messages.
*/
function getNextNonce(address user) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size.
// Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using
// private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.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 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() {
_enterNonReentrant();
_;
_exitNonReentrant();
}
function _enterNonReentrant() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
_require(_status != _ENTERED, Errors.REENTRANCY);
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _exitNonReentrant() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce gas costs.
// The `safeTransfer` and `safeTransferFrom` functions assume that `token` is a contract (an account with code), and
// work differently from the OpenZeppelin version if it is not.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.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 {
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
*
* WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert.
*/
function _callOptionalReturn(address 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.
(bool success, bytes memory returndata) = token.call(data);
// If the low-level call didn't succeed we return whatever was returned from it.
assembly {
if eq(success, 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
// Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs
_require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IVault.sol";
interface IPoolSwapStructs {
// This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and
// IMinimalSwapInfoPool.
//
// This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or
// 'given out') which indicates whether or not the amount sent by the pool is known.
//
// The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take
// in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`.
//
// All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in
// some Pools.
//
// `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than
// one Pool.
//
// The meaning of `lastChangeBlock` depends on the Pool specialization:
// - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total
// balance.
// - General: the last block in which *any* of the Pool's registered tokens changed its total balance.
//
// `from` is the origin address for the funds the Pool receives, and `to` is the destination address
// where the Pool sends the outgoing tokens.
//
// `userData` is extra data provided by the caller - typically a signature from a trusted party.
struct SwapRequest {
IVault.SwapKind kind;
IERC20 tokenIn;
IERC20 tokenOut;
uint256 amount;
// Misc data
bytes32 poolId;
uint256 lastChangeBlock;
address from;
address to;
bytes userData;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "../../lib/helpers/WordCodec.sol";
import "../IPriceOracle.sol";
/**
* @dev This library provides functions to help manipulating samples for Pool Price Oracles. It handles updates,
* encoding, and decoding of samples.
*
* Each sample holds the timestamp of its last update, plus information about three pieces of data: the price pair, the
* price of BPT (the associated Pool token), and the invariant.
*
* Prices and invariant are not stored directly: instead, we store their logarithm. These are known as the 'instant'
* values: the exact value at that timestamp.
*
* Additionally, for each value we keep an accumulator with the sum of all past values, each weighted by the time
* elapsed since the previous update. This lets us later subtract accumulators at different points in time and divide by
* the time elapsed between them, arriving at the geometric mean of the values (also known as log-average).
*
* All samples are stored in a single 256 bit word with the following structure:
*
* [ log pair price | bpt price | invariant ]
* [ instant | accumulator | instant | accumulator | instant | accumulator | timestamp ]
* [ int22 | int53 | int22 | int53 | int22 | int53 | uint31 ]
* MSB LSB
*
* Assuming the timestamp doesn't overflow (which holds until the year 2038), the largest elapsed time is 2^31, which
* means the largest possible accumulator value is 2^21 * 2^31, which can be represented using a signed 53 bit integer.
*/
library Samples {
using WordCodec for int256;
using WordCodec for uint256;
using WordCodec for bytes32;
uint256 internal constant _TIMESTAMP_OFFSET = 0;
uint256 internal constant _ACC_LOG_INVARIANT_OFFSET = 31;
uint256 internal constant _INST_LOG_INVARIANT_OFFSET = 84;
uint256 internal constant _ACC_LOG_BPT_PRICE_OFFSET = 106;
uint256 internal constant _INST_LOG_BPT_PRICE_OFFSET = 159;
uint256 internal constant _ACC_LOG_PAIR_PRICE_OFFSET = 181;
uint256 internal constant _INST_LOG_PAIR_PRICE_OFFSET = 234;
/**
* @dev Updates a sample, accumulating the new data based on the elapsed time since the previous update. Returns the
* updated sample.
*
* IMPORTANT: This function does not perform any arithmetic checks. In particular, it assumes the caller will never
* pass values that cannot be represented as 22 bit signed integers. Additionally, it also assumes
* `currentTimestamp` is greater than `sample`'s timestamp.
*/
function update(
bytes32 sample,
int256 instLogPairPrice,
int256 instLogBptPrice,
int256 instLogInvariant,
uint256 currentTimestamp
) internal pure returns (bytes32) {
// Because elapsed can be represented as a 31 bit unsigned integer, and the received values can be represented
// as 22 bit signed integers, we don't need to perform checked arithmetic.
int256 elapsed = int256(currentTimestamp - timestamp(sample));
int256 accLogPairPrice = _accLogPairPrice(sample) + instLogPairPrice * elapsed;
int256 accLogBptPrice = _accLogBptPrice(sample) + instLogBptPrice * elapsed;
int256 accLogInvariant = _accLogInvariant(sample) + instLogInvariant * elapsed;
return
pack(
instLogPairPrice,
accLogPairPrice,
instLogBptPrice,
accLogBptPrice,
instLogInvariant,
accLogInvariant,
currentTimestamp
);
}
/**
* @dev Returns the instant value stored in `sample` for `variable`.
*/
function instant(bytes32 sample, IPriceOracle.Variable variable) internal pure returns (int256) {
if (variable == IPriceOracle.Variable.PAIR_PRICE) {
return _instLogPairPrice(sample);
} else if (variable == IPriceOracle.Variable.BPT_PRICE) {
return _instLogBptPrice(sample);
} else {
// variable == IPriceOracle.Variable.INVARIANT
return _instLogInvariant(sample);
}
}
/**
* @dev Returns the accumulator value stored in `sample` for `variable`.
*/
function accumulator(bytes32 sample, IPriceOracle.Variable variable) internal pure returns (int256) {
if (variable == IPriceOracle.Variable.PAIR_PRICE) {
return _accLogPairPrice(sample);
} else if (variable == IPriceOracle.Variable.BPT_PRICE) {
return _accLogBptPrice(sample);
} else {
// variable == IPriceOracle.Variable.INVARIANT
return _accLogInvariant(sample);
}
}
/**
* @dev Returns `sample`'s timestamp.
*/
function timestamp(bytes32 sample) internal pure returns (uint256) {
return sample.decodeUint31(_TIMESTAMP_OFFSET);
}
/**
* @dev Returns `sample`'s instant value for the logarithm of the pair price.
*/
function _instLogPairPrice(bytes32 sample) private pure returns (int256) {
return sample.decodeInt22(_INST_LOG_PAIR_PRICE_OFFSET);
}
/**
* @dev Returns `sample`'s accumulator of the logarithm of the pair price.
*/
function _accLogPairPrice(bytes32 sample) private pure returns (int256) {
return sample.decodeInt53(_ACC_LOG_PAIR_PRICE_OFFSET);
}
/**
* @dev Returns `sample`'s instant value for the logarithm of the BPT price.
*/
function _instLogBptPrice(bytes32 sample) private pure returns (int256) {
return sample.decodeInt22(_INST_LOG_BPT_PRICE_OFFSET);
}
/**
* @dev Returns `sample`'s accumulator of the logarithm of the BPT price.
*/
function _accLogBptPrice(bytes32 sample) private pure returns (int256) {
return sample.decodeInt53(_ACC_LOG_BPT_PRICE_OFFSET);
}
/**
* @dev Returns `sample`'s instant value for the logarithm of the invariant.
*/
function _instLogInvariant(bytes32 sample) private pure returns (int256) {
return sample.decodeInt22(_INST_LOG_INVARIANT_OFFSET);
}
/**
* @dev Returns `sample`'s accumulator of the logarithm of the invariant.
*/
function _accLogInvariant(bytes32 sample) private pure returns (int256) {
return sample.decodeInt53(_ACC_LOG_INVARIANT_OFFSET);
}
/**
* @dev Returns a sample created by packing together its components.
*/
function pack(
int256 instLogPairPrice,
int256 accLogPairPrice,
int256 instLogBptPrice,
int256 accLogBptPrice,
int256 instLogInvariant,
int256 accLogInvariant,
uint256 _timestamp
) internal pure returns (bytes32) {
return
instLogPairPrice.encodeInt22(_INST_LOG_PAIR_PRICE_OFFSET) |
accLogPairPrice.encodeInt53(_ACC_LOG_PAIR_PRICE_OFFSET) |
instLogBptPrice.encodeInt22(_INST_LOG_BPT_PRICE_OFFSET) |
accLogBptPrice.encodeInt53(_ACC_LOG_BPT_PRICE_OFFSET) |
instLogInvariant.encodeInt22(_INST_LOG_INVARIANT_OFFSET) |
accLogInvariant.encodeInt53(_ACC_LOG_INVARIANT_OFFSET) |
_timestamp.encodeUint31(_TIMESTAMP_OFFSET);
}
/**
* @dev Unpacks a sample into its components.
*/
function unpack(bytes32 sample)
internal
pure
returns (
int256 logPairPrice,
int256 accLogPairPrice,
int256 logBptPrice,
int256 accLogBptPrice,
int256 logInvariant,
int256 accLogInvariant,
uint256 _timestamp
)
{
logPairPrice = _instLogPairPrice(sample);
accLogPairPrice = _accLogPairPrice(sample);
logBptPrice = _instLogBptPrice(sample);
accLogBptPrice = _accLogBptPrice(sample);
logInvariant = _instLogInvariant(sample);
accLogInvariant = _accLogInvariant(sample);
_timestamp = timestamp(sample);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
interface IWeightedPoolPriceOracle {
/**
* @dev Returns the raw data of the sample at `index`.
*/
function getSample(uint256 index)
external
view
returns (
int256 logPairPrice,
int256 accLogPairPrice,
int256 logBptPrice,
int256 accLogBptPrice,
int256 logInvariant,
int256 accLogInvariant,
uint256 timestamp
);
/**
* @dev Returns the total number of samples.
*/
function getTotalSamples() external view returns (uint256);
}
|
Interface for querying historical data from a Pool that can be used as a Price Oracle. This lets third parties retrieve average prices of tokens held by a Pool over a given period of time, as well as the price of the Pool share token (BPT) and invariant. Since the invariant is a sensible measure of Pool liquidity, it can be used to compare two different price sources, and choose the most liquid one. Once the oracle is fully initialized, all queries are guaranteed to succeed as long as they require no data that is not older than the largest safe query window./ The three values that can be queried: - PAIR_PRICE: the price of the tokens in the Pool, expressed as the price of the second token in units of the first token. For example, if token A is worth $2, and token B is worth $4, the pair price will be 2.0. Note that the price is computed including the tokens decimals. This means that the pair price of a Pool with DAI and USDC will be close to 1.0, despite DAI having 18 decimals and USDC 6. - BPT_PRICE: the price of the Pool share token (BPT), in units of the first token. Note that the price is computed including the tokens decimals. This means that the BPT price of a Pool with USDC in which BPT is worth $5 will be 5.0, despite the BPT having 18 decimals and USDC 6. - INVARIANT: the value of the Pool's invariant, which serves as a measure of its liquidity.
|
interface IPriceOracle {
function getTimeWeightedAverage(OracleAverageQuery[] memory queries)
external
view
returns (uint256[] memory results);
function getLatest(Variable variable) external view returns (uint256);
enum Variable { PAIR_PRICE, BPT_PRICE, INVARIANT }
struct OracleAverageQuery {
Variable variable;
uint256 secs;
uint256 ago;
}
function getLargestSafeQueryWindow() external view returns (uint256);
function getPastAccumulators(OracleAccumulatorQuery[] memory queries)
external
view
returns (int256[] memory results);
struct OracleAccumulatorQuery {
Variable variable;
uint256 ago;
}
}
| 67,578 |
./partial_match/56/0x1D0Ea7F96751Ce68d82e9f20764775c9D109846B/sources/MasterChef.sol
|
Deposit LP tokens to MasterChef for KIWI allocation.
|
function deposit(uint256 _pid, uint256 _amount) public {
require (_pid != 0, 'deposit KIWI by staking');
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accKiwiPerBlock).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeKiwiTransfer(msg.sender, pending);
}
}
uint256 buybackFee = _amount.div(10000).mul(pool.depositFee);
uint256 amountWithoutFee = _amount.sub(buybackFee);
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if (buybackFee > 0) {
pool.lpToken.safeTransfer(buyAddr, buybackFee);
}
user.amount = user.amount.add(amountWithoutFee);
cakeDeposit(_pid, amountWithoutFee);
}
user.rewardDebt = user.amount.mul(pool.accKiwiPerBlock).div(1e12);
emit Deposit(msg.sender, _pid, _amount, buybackFee);
}
| 11,319,971 |
pragma solidity ^0.4.24;
// 😀😀😀😀😀😀😀😀😀😀😀😀😀😀
// 😀 😀
// 😀 https://emojisan.github.io 😀
// 😀 😀
// 😀😀😀😀😀😀😀😀😀😀😀😀😀😀
// part of NFT token interface used in this contract
// https://etherscan.io/address/0xE3f2F807ba194ea0221B9109fb14Da600C9e1eb6
interface Emojisan {
function ownerOf(uint tokenId) external view returns (address);
function balanceOf(address owner) external view returns (uint);
function transferFrom(address from, address to, uint tokenId) external;
function mint(uint tokenId) external;
function setMinter(address newMinter) external;
}
contract EmojisanAuctionHouse {
event Bid(uint indexed tokenId);
struct Auction {
address owner;
uint128 currentPrice;
}
struct User {
uint128 balance;
uint32 bidBlock;
}
// NFT token address
// https://etherscan.io/address/0xE3f2F807ba194ea0221B9109fb14Da600C9e1eb6
Emojisan public constant emojisan = Emojisan(0xE3f2F807ba194ea0221B9109fb14Da600C9e1eb6);
uint[] public tokenByIndex;
mapping (uint => Auction) public auction;
mapping (address => User) public user;
uint32 private constant auctionTime = 20000;
address public whaleAddress;
uint32 public whaleStartTime;
uint128 public whaleBalance;
uint32 private constant whaleWithdrawDelay = 80000;
uint128 public ownerBalance;
uint private constant ownerTokenId = 128512;
function tokens() external view returns (uint[]) {
return tokenByIndex;
}
function tokensCount() external view returns (uint) {
return tokenByIndex.length;
}
function wantItForFree(uint tokenId) external {
// user 👤 can bid only on one 1️⃣ token at a time ⏱️
require(block.number >= user[msg.sender].bidBlock + auctionTime);
// check auction has not started 🚫🎬
require(auction[tokenId].owner == address(this));
auction[tokenId].owner = msg.sender;
user[msg.sender].bidBlock = uint32(block.number);
emojisan.mint(tokenId);
emit Bid(tokenId);
}
function wantItMoreThanYou(uint tokenId) external payable {
// user 👤 can bid only on one 1️⃣ token at a time ⏱️
require(block.number >= user[msg.sender].bidBlock + auctionTime);
// check auction has not finished 🚫🏁
address previousOwner = auction[tokenId].owner;
require(block.number < user[previousOwner].bidBlock + auctionTime);
// fancy 🧐 price 💰 calculation 📈
// 0 ➡️ 0.002 ➡️ 0.004 ➡️ 0.008 ➡️ 0.016 ➡️ 0.032 ➡️ 0.064 ➡️ 0.128
// ➡️ 0.256 ➡️ 0.512 ➡️ 1 ➡️ 1.5 ➡️ 2 ➡️ 2.5 ➡️ 3 ➡️ 3.5 ➡️ 4 ➡️ ...
uint128 previousPrice = auction[tokenId].currentPrice;
uint128 price;
if (previousPrice == 0) {
price = 2 finney;
} else if (previousPrice < 500 finney) {
price = 2 * previousPrice;
} else {
price = (previousPrice + 500 finney) / 500 finney * 500 finney;
}
require(msg.value >= price);
uint128 priceDiff = price - previousPrice;
// previous 👤 gets what she 🙆 paid ➕ 2️⃣5️⃣%
user[previousOwner] = User({
balance: previousPrice + priceDiff / 4,
bidBlock: 0
});
// whale 🐋 gets 5️⃣0️⃣%
whaleBalance += priceDiff / 2;
// owner 👩 of token 128512 😀 gets 2️⃣5️⃣%
ownerBalance += priceDiff / 4;
auction[tokenId] = Auction({
owner: msg.sender,
currentPrice: price
});
user[msg.sender].bidBlock = uint32(block.number);
if (msg.value > price) {
// send back eth if someone sent too much 💸💸💸
msg.sender.transfer(msg.value - price);
}
emit Bid(tokenId);
}
function wantMyToken(uint tokenId) external {
Auction memory a = auction[tokenId];
// check auction has finished 🏁
require(block.number >= user[a.owner].bidBlock + auctionTime);
emojisan.transferFrom(this, a.owner, tokenId);
}
function wantMyEther() external {
uint amount = user[msg.sender].balance;
user[msg.sender].balance = 0;
msg.sender.transfer(amount);
}
function wantToBeWhale() external {
// need to have more tokens 💰 than current 🐋
require(emojisan.balanceOf(msg.sender) > emojisan.balanceOf(whaleAddress));
whaleAddress = msg.sender;
// whale 🐳 needs to wait some time ⏱️ before snatching that sweet 🍬 eth 🤑
whaleStartTime = uint32(block.number);
}
function whaleWantMyEther() external {
require(msg.sender == whaleAddress);
// check enough time ⏱️ passed for whale 🐳 to grab 💵💷💶💴
require(block.number >= whaleStartTime + whaleWithdrawDelay);
// whale 🐳 needs to wait some time ⏱️ before snatching that sweet 🍭 eth 🤑 again
whaleStartTime = uint32(block.number);
uint amount = whaleBalance;
whaleBalance = 0;
whaleAddress.transfer(amount);
}
function ownerWantMyEther() external {
uint amount = ownerBalance;
ownerBalance = 0;
emojisan.ownerOf(ownerTokenId).transfer(amount);
}
function wantNewTokens(uint[] tokenIds) external {
// only owner 👩 of token 128512 😀
require(msg.sender == emojisan.ownerOf(ownerTokenId));
for (uint i = 0; i < tokenIds.length; i++) {
auction[tokenIds[i]].owner = this;
tokenByIndex.push(tokenIds[i]);
}
}
function wantNewMinter(address minter) external {
// only owner 👩 of token 128512 😀
require(msg.sender == emojisan.ownerOf(ownerTokenId));
emojisan.setMinter(minter);
}
}
|
only owner 👩 of token 128512 😀
|
function wantNewMinter(address minter) external {
require(msg.sender == emojisan.ownerOf(ownerTokenId));
emojisan.setMinter(minter);
}
| 644,427 |
./full_match/80001/0xAa6801AA07299181ca051fD5428f4f1e3125C5a6/sources/contracts/SubscriptionContract.sol
|
payable(plan.artist).transfer(plan.amount); subscriptions[msg.sender][planId] = Subscription( msg.sender, block.timestamp, block.timestamp + plan.frequency, true );"0+3+Hooray! ", msg.sender, " sent ", token amount, " PUSH to you!" We are passing identity here: https:docs.epns.io/developers/developer-guides/sending-notifications/advanced/notification-payload-types/identity/payload-identity-implementations
|
function subscribe(uint planId) external payable {
Plan storage plan = plans[planId];
require(plan.nftAddress != address(0), "Invalid creator");
require(plan.artist != address(0), "this plan does not exist");
IERC20(tokenAddress).approve(msg.sender, plan.amount);
IERC20(tokenAddress).transfer(plan.artist, plan.amount);
emit PaymentSent(
msg.sender,
plan.artist,
plan.amount,
planId,
block.timestamp
);
PolyverseCreatorNFT nftContract = PolyverseCreatorNFT(plan.nftAddress);
nftContract.mintSubscription(msg.sender);
subscriptions[plan.artist][msg.sender][planId] = Subscription(
msg.sender,
block.timestamp,
block.timestamp + plan.frequency,
true
);
uint256 amount = plan.amount;
IPUSHCommInterface(EPNS_COMM_ADDRESS).sendNotification(
bytes(
string(
abi.encodePacked(
)
)
)
);
emit SubscriptionCreated(msg.sender, planId, block.timestamp, true);
}
| 5,681,875 |
./partial_match/3/0xC91058D7eB0ac094E26fFCb13688a68644CD0256/sources/Pulley.sol
|
require(msg.value == 0.2 ether, "Participate cost 0.2");
|
function reParticipate(address userAddress, address referrerAddress) private {
require(isUserExists(userAddress), "user not exists");
require(isUserExists(referrerAddress), "referrer not exists");
require(lastUserId >=1014, "Less than the minimum amount");
address freeX2Referrer = findFreeX2Referrer(userAddress);
if(users[referrerAddress].activeX2){
users[referrerAddress].partnerActive++;
}
edfToken.gainEdfToken(1000 * 10 ** 6);
users[referrerAddress].partnersCount++;
users[userAddress].pledgeAmount = SafeMath.add(users[userAddress].pledgeAmount, 1000 * 10 ** 6);
users[referrerAddress].wallet = SafeMath.add(users[referrerAddress].wallet, 4 * 10 ** 16);
emit UserEthDetail(referrerAddress, userAddress, users[userAddress].id, 4 * 10 ** 16, now, 4);
users[referrerAddress].releaseRate = SafeMath.add(users[referrerAddress].releaseRate, 1);
starFish(userAddress, users[freeX2Referrer].X2Addr);
playerMap[users[freeX2Referrer].X2Addr].reinvestCount++;
emit ReParticipate(userAddress, referrerAddress, users[userAddress].id, users[referrerAddress].id);
emit UserEthDetail(userAddress, userAddress, users[userAddress].id, 20 * 10 ** 16, now, 2);
}
| 5,223,198 |
./partial_match/42220/0xd44D005d48e2C64Cbc52bdecf03Ec35865609685/sources/contracts/fluentStable.sol
|
Generates a message hash based on the provided parameters.
|
function generateMessageHash(
string memory iNetwork,
string memory iSymbol,
uint256 amount,
address account,
uint256 timestamp
) public pure returns (bytes32) {
return
keccak256(
abi.encodePacked(iNetwork, iSymbol, amount, account, timestamp)
);
}
| 3,495,654 |
pragma solidity ^0.5.0;
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
/**
* @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 SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
/**
* @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]);
}
}
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event 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 TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(address(token) != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer fund with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
}
/**
* @title AllowanceCrowdsale
* @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale.
*/
contract AllowanceCrowdsale is Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address private _tokenWallet;
/**
* @dev Constructor, takes token wallet address.
* @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale
*/
constructor (address tokenWallet) public {
require(tokenWallet != address(0));
_tokenWallet = tokenWallet;
}
/**
* @return the address of the wallet that will hold the tokens.
*/
function tokenWallet() public view returns (address) {
return _tokenWallet;
}
/**
* @dev Checks the amount of tokens left in the allowance.
* @return Amount of tokens left in the allowance
*/
function remainingTokens() public view returns (uint256) {
return Math.min(token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this)));
}
/**
* @dev Overrides parent behavior by transferring tokens from wallet.
* @param beneficiary Token purchaser
* @param tokenAmount Amount of tokens purchased
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount);
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _openingTime;
uint256 private _closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen());
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
*/
constructor (uint256 openingTime, uint256 closingTime) public {
// solhint-disable-next-line not-rely-on-time
require(openingTime >= block.timestamp);
require(closingTime > openingTime);
_openingTime = openingTime;
_closingTime = closingTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view returns (uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view returns (uint256) {
return _closingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp > _closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view {
super._preValidatePurchase(beneficiary, weiAmount);
}
}
/**
* @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 Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () internal {
_addWhitelistAdmin(msg.sender);
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(msg.sender));
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(msg.sender);
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
/**
* @title WhitelistedRole
* @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
* it), and not Whitelisteds themselves.
*/
contract WhitelistedRole is WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted() {
require(isWhitelisted(msg.sender));
_;
}
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
function addWhitelisted(address account) public onlyWhitelistAdmin {
_addWhitelisted(account);
}
function removeWhitelisted(address account) public onlyWhitelistAdmin {
_removeWhitelisted(account);
}
function renounceWhitelisted() public {
_removeWhitelisted(msg.sender);
}
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
}
contract KicksCrowdsale is Crowdsale, TimedCrowdsale, AllowanceCrowdsale, WhitelistedRole {
using SafeMath for uint256;
uint256 private _rate;
uint256 private _kickCap = 33333333333333333333333333; // $50M
uint256 private _kickMinPay = 100 ether;
uint256 private _kickPurchased = 0;
uint256 private _bonus20capBoundary = 800000000000000000000000; // $1.2M
uint256 private _bonus10capBoundary = 1533333333333333333333333; // $2.3M
address private _manualSeller;
address private _rateSetter;
address private _whitelistAdmin;
bool private _KYC = false;
event Bonus(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event ChangeRate(uint256 rate);
constructor(
uint256 rate, // eth to kick rate
ERC20 token, // the kick token address
address payable wallet, // accumulation eth address
address tokenWallet, // kick storage address
address manualSeller, // can sell tokens
address rateSetter, // can change eth rate
uint256 openingTime,
uint256 closingTime
)
Crowdsale(rate, wallet, token)
AllowanceCrowdsale(tokenWallet)
TimedCrowdsale(openingTime, closingTime)
public
{
_rate = rate;
_manualSeller = manualSeller;
_rateSetter = rateSetter;
_whitelistAdmin = msg.sender;
}
/**
* Base crowdsale override
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
if (_KYC) {
require(isWhitelisted(beneficiary), 'Only whitelisted');
}
uint256 kickAmount = weiAmount.mul(_rate);
require(kickAmount >= _kickMinPay, 'Min purchase 100 kick');
require(_kickPurchased.add(kickAmount) <= _kickCap, 'Cap has been reached');
super._preValidatePurchase(beneficiary, weiAmount);
}
function calcBonus(uint256 tokenAmount) internal view returns (uint256) {
uint256 bonus = 0;
if (_kickPurchased.add(tokenAmount) <= _bonus20capBoundary) {
bonus = tokenAmount.mul(20).div(100);
} else if (_kickPurchased.add(tokenAmount) <= _bonus10capBoundary) {
bonus = tokenAmount.mul(10).div(100);
}
return bonus;
}
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
uint256 tokenAmount = weiAmount.mul(_rate);
return tokenAmount.add(calcBonus(tokenAmount));
}
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
uint256 tokenAmount = weiAmount.mul(_rate);
uint256 bonus = calcBonus(tokenAmount);
if (bonus != 0) {
emit Bonus(msg.sender, beneficiary, weiAmount, bonus);
tokenAmount = tokenAmount.add(bonus);
}
_kickPurchased = _kickPurchased.add(tokenAmount);
}
/**
* Manual sell
*/
function manualSell(address beneficiary, uint256 weiAmount) public onlyWhileOpen {
require(msg.sender == _manualSeller);
_preValidatePurchase(beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens);
_updatePurchasingState(beneficiary, weiAmount);
_postValidatePurchase(beneficiary, weiAmount);
}
/**
* Change eth rate
*/
function setRate(uint256 rate) public {
require(msg.sender == _rateSetter);
_rate = rate;
emit ChangeRate(rate);
}
/**
* Change KYC status
*/
function onKYC() public {
require(msg.sender == _whitelistAdmin);
require(!_KYC);
_KYC = true;
}
function offKYC() public {
require(msg.sender == _whitelistAdmin);
require(_KYC);
_KYC = false;
}
/**
* Getters
*/
function rate() public view returns (uint256) {
return _rate;
}
function kickCap() public view returns (uint256) {
return _kickCap;
}
function kickMinPay() public view returns (uint256) {
return _kickMinPay;
}
function kickPurchased() public view returns (uint256) {
return _kickPurchased;
}
function bonus20capBoundary() public view returns (uint256) {
return _bonus20capBoundary;
}
function bonus10capBoundary() public view returns (uint256) {
return _bonus10capBoundary;
}
function KYC() public view returns (bool) {
return _KYC;
}
}
|
Extend parent behavior requiring to be within contributing period beneficiary Token purchaser weiAmount Amount of wei contributed/
|
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view {
super._preValidatePurchase(beneficiary, weiAmount);
}
| 1,012,610 |
//SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.9.0;
contract GlobalVars{
// the current time as a timestamp (seconds from 01 Jan 1970)
uint this_moment = block.timestamp; // `now` is deprecated and is an alias to block.timestamp)
// the current block number
uint block_number = block.number;
// the block difficulty
uint difficulty = block.difficulty;
// the block gas limit
uint gaslimit = block.gaslimit;
address owner;
uint sentValue;
uint gasSpent;
constructor(){
// msg.sender is the address that interacts with the contract (deploys it in this case)
owner = msg.sender;
}
function sendEther() public payable returns(uint _gas){ // must be payable to receive ETH with the transaction
// msg.value is the value of wei sent in this transaction (when calling the function)
_gas = gasleft();
sentValue = msg.value;
gasSpent = _gas - gasleft();
}
// returning the balance of the contract
function getBalance() public returns(uint _balance, uint _gas){
_gas = gasleft();
_balance = address(this).balance;
gasSpent = _gas - gasleft();
}
function myFunction() public payable returns (uint _gas){
_gas = gasleft();
getBalance();
sendEther();
getBalance();
gasSpent = _gas - gasleft();
}
function getGasSpent() public view returns(uint){
return gasSpent;
}
}
|
must be payable to receive ETH with the transaction
|
function sendEther() public payable returns(uint _gas){
| 12,578,076 |
pragma solidity ^0.6;
import "../../../lib/SafeMath.sol";
import {Ownable} from "../ownership/Ownable.sol";
/**
* Stores information for added training data and corresponding meta-data.
*/
interface DataHandler {
function updateClaimableAmount(bytes32 dataKey, uint rewardAmount) external;
}
/**
* Stores information for added training data and corresponding meta-data.
*/
contract DataHandler64 is Ownable, DataHandler {
using SafeMath for uint256;
struct StoredData {
/**
* The data stored.
*/
// Don't store the data because it's not really needed since we emit events when data is added.
// The main reason for storing the data in here is to ensure equality on future interactions like when refunding.
// This extra equality check is only necessary if you're worried about hash collisions.
// int64[] d;
/**
* The classification for the data.
*/
uint64 c;
/**
* The time it was added.
*/
uint t;
/**
* The address that added the data.
*/
address sender;
/**
* The amount that was initially given to deposit this data.
*/
uint initialDeposit;
/**
* The amount of the deposit that can still be claimed.
*/
uint claimableAmount;
/**
* The number of claims that have been made for refunds or reports.
* This should be the size of `claimedBy`.
*/
uint numClaims;
/**
* The set of addresses that claimed a refund or reward on this data.
*/
mapping(address => bool) claimedBy;
}
/**
* Meta-data for data that has been added.
*/
mapping(bytes32 => StoredData) public addedData;
function getClaimableAmount(int64[] memory data, uint64 classification, uint addedTime, address originalAuthor)
public view returns (uint) {
bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor));
StoredData storage existingData = addedData[key];
// Validate found value.
// usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal.");
require(existingData.c == classification, "Classification is not equal.");
require(existingData.t == addedTime, "Added time is not equal.");
require(existingData.sender == originalAuthor, "Data isn't from the right author.");
return existingData.claimableAmount;
}
function getInitialDeposit(int64[] memory data, uint64 classification, uint addedTime, address originalAuthor)
public view returns (uint) {
bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor));
StoredData storage existingData = addedData[key];
// Validate found value.
// usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal.");
require(existingData.c == classification, "Classification is not equal.");
require(existingData.t == addedTime, "Added time is not equal.");
require(existingData.sender == originalAuthor, "Data isn't from the right author.");
return existingData.initialDeposit;
}
function getNumClaims(int64[] memory data, uint64 classification, uint addedTime, address originalAuthor)
public view returns (uint) {
bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor));
StoredData storage existingData = addedData[key];
// Validate found value.
// usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal.");
require(existingData.c == classification, "Classification is not equal.");
require(existingData.t == addedTime, "Added time is not equal.");
require(existingData.sender == originalAuthor, "Data isn't from the right author.");
return existingData.numClaims;
}
/**
* Check if two arrays of training data are equal.
*/
function isDataEqual(int64[] memory d1, int64[] memory d2) public pure returns (bool) {
if (d1.length != d2.length) {
return false;
}
for (uint i = 0; i < d1.length; ++i) {
if (d1[i] != d2[i]) {
return false;
}
}
return true;
}
/**
* Log an attempt to add data.
*
* @param msgSender The address of the one attempting to add data.
* @param cost The cost required to add new data.
* @param data A single sample of training data for the model.
* @param classification The label for `data`.
* @return time The time which the data was added, i.e. the current time in seconds.
*/
function handleAddData(address msgSender, uint cost, int64[] memory data, uint64 classification)
public onlyOwner
returns (uint time) {
time = now; // solium-disable-line security/no-block-members
bytes32 key = keccak256(abi.encodePacked(data, classification, time, msgSender));
StoredData storage existingData = addedData[key];
bool okayToOverwrite = existingData.sender == address(0) || existingData.claimableAmount == 0;
require(okayToOverwrite, "Conflicting data key. The data may have already been added.");
// Maybe we do want to allow duplicate data to be added but just not from the same address.
// Of course that is not sybil-proof.
// Store data.
addedData[key] = StoredData({
// not necessary: d: data,
c: classification,
t: time,
sender: msgSender,
initialDeposit: cost,
claimableAmount: cost,
numClaims: 0
});
}
/**
* Log a refund attempt.
*
* @param submitter The address of the one attempting a refund.
* @param data The data for which to attempt a refund.
* @param classification The label originally submitted for `data`.
* @param addedTime The time in seconds for which the data was added.
* @return claimableAmount The amount that can be claimed for the refund.
* @return claimedBySubmitter `true` if the data has already been claimed by `submitter`, otherwise `false`.
* @return numClaims The number of claims that have been made for the contribution before this request.
*/
function handleRefund(address submitter, int64[] memory data, uint64 classification, uint addedTime)
public onlyOwner
returns (uint claimableAmount, bool claimedBySubmitter, uint numClaims) {
bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, submitter));
StoredData storage existingData = addedData[key];
// Validate found value.
require(existingData.sender != address(0), "Data not found.");
// usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal.");
require(existingData.c == classification, "Classification is not equal.");
require(existingData.t == addedTime, "Added time is not equal.");
require(existingData.sender == submitter, "Data is not from the sender.");
claimableAmount = existingData.claimableAmount;
claimedBySubmitter = existingData.claimedBy[submitter];
numClaims = existingData.numClaims;
// Upon successful completion of the refund the values will be claimed.
existingData.claimableAmount = 0;
existingData.claimedBy[submitter] = true;
existingData.numClaims = numClaims.add(1);
}
/**
* Retrieve information about the data to report.
*
* @param reporter The address of the one reporting the data.
* @param data The data to report.
* @param classification The label submitted for `data`.
* @param addedTime The time in seconds for which the data was added.
* @param originalAuthor The address that originally added the data.
* @return initialDeposit The amount that was initially deposited when the data contribution was submitted.
* @return claimableAmount The amount remainining that can be claimed.
* @return claimedByReporter `true` if the data has already been claimed by `reporter`, otherwise `false`.
* @return numClaims The number of claims that have been made for the contribution before this request.
* @return dataKey The key to the stored data.
*/
function handleReport(
address reporter,
int64[] memory data, uint64 classification, uint addedTime, address originalAuthor)
public onlyOwner
returns (uint initialDeposit, uint claimableAmount, bool claimedByReporter, uint numClaims, bytes32 dataKey) {
dataKey = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor));
StoredData storage existingData = addedData[dataKey];
// Validate found value.
require(existingData.sender != address(0), "Data not found.");
// usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal.");
require(existingData.c == classification, "Classification is not equal.");
require(existingData.t == addedTime, "Added time is not equal.");
require(existingData.sender == originalAuthor, "Sender is not equal.");
initialDeposit = existingData.initialDeposit;
claimableAmount = existingData.claimableAmount;
claimedByReporter = existingData.claimedBy[reporter];
numClaims = existingData.numClaims;
existingData.claimedBy[reporter] = true;
existingData.numClaims = numClaims.add(1);
}
/**
* @return `true` if the contribution has already been claimed by `claimer`, otherwise `false`.
*/
function hasClaimed(
int64[] memory data, uint64 classification,
uint addedTime, address originalAuthor,
address claimer)
public view returns (bool) {
bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor));
StoredData storage existingData = addedData[key];
// Validate found value.
// usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal.");
require(existingData.c == classification, "Classification is not equal.");
require(existingData.t == addedTime, "Added time is not equal.");
require(existingData.sender == originalAuthor, "Data isn't from the right author.");
return existingData.claimedBy[claimer];
}
function updateClaimableAmount(bytes32 dataKey, uint rewardAmount)
public override onlyOwner {
StoredData storage existingData = addedData[dataKey];
// Already validated key lookup.
existingData.claimableAmount = existingData.claimableAmount.sub(rewardAmount);
}
}
|
Validate found value. usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal.");
|
function getClaimableAmount(int64[] memory data, uint64 classification, uint addedTime, address originalAuthor)
public view returns (uint) {
bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor));
StoredData storage existingData = addedData[key];
require(existingData.c == classification, "Classification is not equal.");
require(existingData.t == addedTime, "Added time is not equal.");
require(existingData.sender == originalAuthor, "Data isn't from the right author.");
return existingData.claimableAmount;
}
| 12,872,848 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*
██████╗ █████╗ ███╗ ██╗██╗███████╗██╗
██╔══██╗██╔══██╗████╗ ██║██║██╔════╝██║
██║ ██║███████║██╔██╗ ██║██║█████╗ ██║
██║ ██║██╔══██║██║╚██╗██║██║██╔══╝ ██║
██████╔╝██║ ██║██║ ╚████║██║███████╗███████╗
╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝╚══════╝╚══════╝
█████╗ ██████╗ ███████╗██╗ ██╗ █████╗ ███╗ ███╗
██╔══██╗██╔══██╗██╔════╝██║ ██║██╔══██╗████╗ ████║
███████║██████╔╝███████╗███████║███████║██╔████╔██║
██╔══██║██╔══██╗╚════██║██╔══██║██╔══██║██║╚██╔╝██║
██║ ██║██║ ██║███████║██║ ██║██║ ██║██║ ╚═╝ ██║
╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝
______
/ /\
/ /##\
/ /####\
/ /######\
/ /########\
/ /##########\
/ /#####/\#####\
/ /#####/++\#####\
/ /#####/++++\#####\
/ /#####/\+++++\#####\
/ /#####/ \+++++\#####\
/ /#####/ \+++++\#####\
/ /#####/ \+++++\#####\
/ /#####/ \+++++\#####\
/ /#####/__________\+++++\#####\
/ \+++++\#####\
/__________________________\+++++\####/
\+++++++++++++++++++++++++++++++++\##/
\+++++++++++++++++++++++++++++++++\/
``````````````````````````````````
██████╗██╗ ██╗██╗██████╗
██╔════╝╚██╗██╔╝██║██╔══██╗
██║ ╚███╔╝ ██║██████╔╝
██║ ██╔██╗ ██║██╔═══╝
╚██████╗██╔╝ ██╗██║██║
╚═════╝╚═╝ ╚═╝╚═╝╚═╝
*/
import "./external/OpenSea.sol";
import "./interface/IERC165.sol";
import "./interface/ICxipERC721.sol";
import "./interface/ICxipIdentity.sol";
import "./interface/ICxipProvenance.sol";
import "./interface/ICxipRegistry.sol";
import "./interface/IPA1D.sol";
import "./library/Address.sol";
import "./library/Bytes.sol";
import "./library/Strings.sol";
import "./struct/CollectionData.sol";
import "./struct/TokenData.sol";
import "./struct/Verification.sol";
contract DanielArshamErodingAndReformingCars {
/**
* @dev Stores default collection data: name, symbol, and royalties.
*/
CollectionData private _collectionData;
/**
* @dev Internal last minted token id, to allow for auto-increment.
*/
uint256 private _currentTokenId;
/**
* @dev Array of all token ids in collection.
*/
uint256[] private _allTokens;
/**
* @dev Map of token id to array index of _ownedTokens.
*/
mapping(uint256 => uint256) private _ownedTokensIndex;
/**
* @dev Token id to wallet (owner) address map.
*/
mapping(uint256 => address) private _tokenOwner;
/**
* @dev 1-to-1 map of token id that was assigned an approved operator address.
*/
mapping(uint256 => address) private _tokenApprovals;
/**
* @dev Map of total tokens owner by a specific address.
*/
mapping(address => uint256) private _ownedTokensCount;
/**
* @dev Map of array of token ids owned by a specific address.
*/
mapping(address => uint256[]) private _ownedTokens;
/**
* @notice Map of full operator approval for a particular address.
* @dev Usually utilised for supporting marketplace proxy wallets.
*/
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Token data mapped by token id.
*/
mapping(uint256 => TokenData) private _tokenData;
/**
* @dev Address of admin user. Primarily used as an additional recover address.
*/
address private _admin;
/**
* @dev Address of contract owner. This address can run all onlyOwner functions.
*/
address private _owner;
/**
* @dev Simple tracker of all minted (not-burned) tokens.
*/
uint256 private _totalTokens;
/**
* @dev Mapping from token id to position in the allTokens array.
*/
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @notice Event emitted when an token is minted, transfered, or burned.
* @dev If from is empty, it's a mint. If to is empty, it's a burn. Otherwise, it's a transfer.
* @param from Address from where token is being transfered.
* @param to Address to where token is being transfered.
* @param tokenId Token id that is being minted, Transfered, or burned.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @notice Event emitted when an address delegates power, for a token, to another address.
* @dev Emits event that informs of address approving a third-party operator for a particular token.
* @param wallet Address of the wallet configuring a token operator.
* @param operator Address of the third-party operator approved for interaction.
* @param tokenId A specific token id that is being authorised to operator.
*/
event Approval(address indexed wallet, address indexed operator, uint256 indexed tokenId);
/**
* @notice Event emitted when an address authorises an operator (third-party).
* @dev Emits event that informs of address approving/denying a third-party operator.
* @param wallet Address of the wallet configuring it's operator.
* @param operator Address of the third-party operator that interacts on behalf of the wallet.
* @param approved A boolean indicating whether approval was granted or revoked.
*/
event ApprovalForAll(address indexed wallet, address indexed operator, bool approved);
/**
* @notice Constructor is empty and not utilised.
* @dev To make exact CREATE2 deployment possible, constructor is left empty. We utilize the "init" function instead.
*/
constructor() {}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "CXIP: caller not an owner");
_;
}
/**
* @dev Left empty on purpose to prevent out of gas errors.
*/
receive() external payable {}
/**
* @notice Enables royaltiy functionality at the ERC721 level no other function matches the call.
* @dev See implementation of _royaltiesFallback.
*/
fallback() external {
_royaltiesFallback();
}
function getIntervalConfig() public view returns (uint256[4] memory intervals) {
uint64 unpacked;
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.intervalConfig')) - 1);
assembly {
unpacked := sload(
/* slot */
0xf8883f7674e7099512a3eb674d514a03c06b3984f509bd9a7b34673ea2a79349
)
}
intervals[0] = uint256(uint16(unpacked >> 48));
intervals[1] = uint256(uint16(unpacked >> 32));
intervals[2] = uint256(uint16(unpacked >> 16));
intervals[3] = uint256(uint16(unpacked));
}
function setIntervalConfig(uint256[4] memory intervals) external onlyOwner {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.intervalConfig')) - 1);
uint256 packed = uint256((intervals[0] << 48) | (intervals[1] << 32) | (intervals[2] << 16) | intervals[3]);
assembly {
sstore(
/* slot */
0xf8883f7674e7099512a3eb674d514a03c06b3984f509bd9a7b34673ea2a79349,
packed
)
}
}
function _calculateRotation(uint256 tokenId) internal view returns (uint256 rotationIndex) {
uint256 configIndex = (tokenId / getTokenSeparator());
uint256 interval = getIntervalConfig()[configIndex - 1];
uint256 remainder = ((block.timestamp - getStartTimestamp()) / interval) % 2;
// (remainder == 0 ? "even" : "odd")
rotationIndex = (configIndex * 2) + remainder;
}
/**
* @notice Gets the URI of the NFT on Arweave.
* @dev Concatenates 2 sections of the arweave URI.
* @return string The URI.
*/
function arweaveURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return string(abi.encodePacked("https://arweave.net/", _tokenData[index].arweave, _tokenData[index].arweave2));
}
/**
* @notice Gets the URI of the NFT backup from CXIP.
* @dev Concatenates to https://nft.cxip.io/.
* @return string The URI.
*/
function contractURI() external view returns (string memory) {
return string(abi.encodePacked("https://nft.cxip.io/", Strings.toHexString(address(this)), "/"));
}
/**
* @notice Gets the creator's address.
* @dev If the token Id doesn't exist it will return zero address.
* @return address Creator's address.
*/
function creator(uint256 tokenId) external view returns (address) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return _tokenData[index].creator;
}
/**
* @notice Gets the HTTP URI of the token.
* @dev Concatenates to the baseURI.
* @return string The URI.
*/
function httpURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "CXIP: token does not exist");
return string(abi.encodePacked(baseURI(), "/", Strings.toHexString(tokenId)));
}
/**
* @notice Gets the IPFS URI
* @dev Concatenates to the IPFS domain.
* @return string The URI.
*/
function ipfsURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return string(abi.encodePacked("https://ipfs.io/ipfs/", _tokenData[index].ipfs, _tokenData[index].ipfs2));
}
/**
* @notice Gets the name of the collection.
* @dev Uses two names to extend the max length of the collection name in bytes
* @return string The collection name.
*/
function name() external view returns (string memory) {
return string(abi.encodePacked(Bytes.trim(_collectionData.name), Bytes.trim(_collectionData.name2)));
}
/**
* @notice Gets the hash of the NFT data used to create it.
* @dev Payload is used for verification.
* @param tokenId The Id of the token.
* @return bytes32 The hash.
*/
function payloadHash(uint256 tokenId) external view returns (bytes32) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return _tokenData[index].payloadHash;
}
/**
* @notice Gets the signature of the signed NFT data used to create it.
* @dev Used for signature verification.
* @param tokenId The Id of the token.
* @return Verification a struct containing v, r, s values of the signature.
*/
function payloadSignature(uint256 tokenId) external view returns (Verification memory) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return _tokenData[index].payloadSignature;
}
/**
* @notice Gets the address of the creator.
* @dev The creator signs a payload while creating the NFT.
* @param tokenId The Id of the token.
* @return address The creator.
*/
function payloadSigner(uint256 tokenId) external view returns (address) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return _tokenData[index].creator;
}
/**
* @notice Shows the interfaces the contracts support
* @dev Must add new 4 byte interface Ids here to acknowledge support
* @param interfaceId ERC165 style 4 byte interfaceId.
* @return bool True if supported.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
if (
interfaceId == 0x01ffc9a7 || // ERC165
interfaceId == 0x80ac58cd || // ERC721
interfaceId == 0x780e9d63 || // ERC721Enumerable
interfaceId == 0x5b5e139f || // ERC721Metadata
interfaceId == 0x150b7a02 || // ERC721TokenReceiver
interfaceId == 0xe8a3d485 || // contractURI()
IPA1D(getRegistry().getPA1D()).supportsInterface(interfaceId)
) {
return true;
} else {
return false;
}
}
/**
* @notice Gets the collection's symbol.
* @dev Trims the symbol.
* @return string The symbol.
*/
function symbol() external view returns (string memory) {
return string(Bytes.trim(_collectionData.symbol));
}
/**
* @notice Get's the URI of the token.
* @dev Defaults the the Arweave URI
* @return string The URI.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return string(abi.encodePacked("https://arweave.net/", _tokenData[index].arweave, _tokenData[index].arweave2));
}
/**
* @notice Get list of tokens owned by wallet.
* @param wallet The wallet address to get tokens for.
* @return uint256[] Returns an array of token ids owned by wallet.
*/
function tokensOfOwner(address wallet) external view returns (uint256[] memory) {
return _ownedTokens[wallet];
}
/**
* @notice Adds a new address to the token's approval list.
* @dev Requires the sender to be in the approved addresses.
* @param to The address to approve.
* @param tokenId The affected token.
*/
function approve(address to, uint256 tokenId) public {
address tokenOwner = _tokenOwner[tokenId];
require(to != tokenOwner, "CXIP: can't approve self");
require(_isApproved(msg.sender, tokenId), "CXIP: not approved sender");
_tokenApprovals[tokenId] = to;
emit Approval(tokenOwner, to, tokenId);
}
/**
* @notice Burns the token.
* @dev The sender must be the owner or approved.
* @param tokenId The token to burn.
*/
function burn(uint256 tokenId) public {
require(_isApproved(msg.sender, tokenId), "CXIP: not approved sender");
address wallet = _tokenOwner[tokenId];
_clearApproval(tokenId);
_tokenOwner[tokenId] = address(0);
emit Transfer(wallet, address(0), tokenId);
_removeTokenFromOwnerEnumeration(wallet, tokenId);
}
/**
* @notice Initializes the collection.
* @dev Special function to allow a one time initialisation on deployment. Also configures and deploys royalties.
* @param newOwner The owner of the collection.
* @param collectionData The collection data.
*/
function init(address newOwner, CollectionData calldata collectionData) public {
require(Address.isZero(_admin), "CXIP: already initialized");
_admin = msg.sender;
// temporary set to self, to pass rarible royalties logic trap
_owner = address(this);
_collectionData = collectionData;
IPA1D(address(this)).init(0, payable(collectionData.royalties), collectionData.bps);
// set to actual owner
_owner = newOwner;
}
/**
* @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.
* @param from cannot be the zero address.
* @param to cannot be the zero address.
* @param tokenId token must exist and be owned by `from`.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public payable {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @notice Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings.
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
* @param from cannot be the zero address.
* @param to cannot be the zero address.
* @param tokenId token must exist and be owned by `from`.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public payable {
require(_isApproved(msg.sender, tokenId), "CXIP: not approved sender");
_transferFrom(from, to, tokenId);
if (Address.isContract(to)) {
require(
IERC165(to).supportsInterface(0x01ffc9a7) &&
IERC165(to).supportsInterface(0x150b7a02) &&
ICxipERC721(to).onERC721Received(address(this), from, tokenId, data) == 0x150b7a02,
"CXIP: onERC721Received fail"
);
}
}
/**
* @notice Adds a new approved operator.
* @dev Allows platforms to sell/transfer all your NFTs. Used with proxy contracts like OpenSea/Rarible.
* @param to The address to approve.
* @param approved Turn on or off approval status.
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender, "CXIP: can't approve self");
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @notice Transfers `tokenId` token from `from` to `to`.
* @dev WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* @param from cannot be the zero address.
* @param to cannot be the zero address.
* @param tokenId token must be owned by `from`.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable {
transferFrom(from, to, tokenId, "");
}
/**
* @notice Transfers `tokenId` token from `from` to `to`.
* @dev WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings.
* @param from cannot be the zero address.
* @param to cannot be the zero address.
* @param tokenId token must be owned by `from`.
*/
function transferFrom(
address from,
address to,
uint256 tokenId,
bytes memory /*_data*/
) public payable {
require(_isApproved(msg.sender, tokenId), "CXIP: not approved sender");
_transferFrom(from, to, tokenId);
}
/**
* @notice Mints batches of NFTs.
* @dev Limited to maximum number of NFTs that can be minted for this drop. Needs to be called in tokenId sequence.
* @param creatorWallet The wallet address of the NFT creator.
* @param startId The tokenId from which to start batch mint.
* @param length The total number of NFTs to mint starting from the startId.
* @param recipient Optional parameter, to send the token to a recipient right after minting.
*/
function batchMint(
address creatorWallet,
uint256 startId,
uint256 length,
address recipient
) public onlyOwner {
require(!getMintingClosed(), "CXIP: minting is now closed");
require(_allTokens.length + length <= getTokenLimit(), "CXIP: over token limit");
require(isIdentityWallet(creatorWallet), "CXIP: creator not in identity");
bool hasRecipient = !Address.isZero(recipient);
uint256 tokenId;
for (uint256 i = 0; i < length; i++) {
tokenId = (startId + i);
if (hasRecipient) {
require(!_exists(tokenId), "CXIP: token already exists");
emit Transfer(address(0), creatorWallet, tokenId);
emit Transfer(creatorWallet, recipient, tokenId);
_tokenOwner[tokenId] = recipient;
_addTokenToOwnerEnumeration(recipient, tokenId);
} else {
_mint(creatorWallet, tokenId);
}
}
if (_allTokens.length == getTokenLimit()) {
setMintingClosed();
}
}
function getStartTimestamp() public view returns (uint256 _timestamp) {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.startTimestamp')) - 1);
assembly {
_timestamp := sload(
/* slot */
0xf2aaccfcfa4e77d7601ed4ebe139368f313960f63d25a2f26ec905d019eba48b
)
}
}
/**
* @dev Gets the minting status from storage slot.
* @return mintingClosed Whether minting is open or closed permanently.
*/
function getMintingClosed() public view returns (bool mintingClosed) {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.mintingClosed')) - 1);
uint256 data;
assembly {
data := sload(
/* slot */
0xab90edbe8f424080ec4ee1e9062e8b7540cbbfd5f4287285e52611030e58b8d4
)
}
mintingClosed = (data == 1);
}
/**
* @dev Sets the minting status to closed in storage slot.
*/
function setMintingClosed() public onlyOwner {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.mintingClosed')) - 1);
uint256 data = 1;
assembly {
sstore(
/* slot */
0xab90edbe8f424080ec4ee1e9062e8b7540cbbfd5f4287285e52611030e58b8d4,
data
)
}
}
/**
* @dev Gets the token limit from storage slot.
* @return tokenLimit Maximum number of tokens that can be minted.
*/
function getTokenLimit() public view returns (uint256 tokenLimit) {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.tokenLimit')) - 1);
assembly {
tokenLimit := sload(
/* slot */
0xb63653e470fa8e7fcc528e0068173a1969fdee5ae0ee29dd58e7b6111b829c56
)
}
}
/**
* @dev Sets the token limit to storage slot.
* @param tokenLimit Maximum number of tokens that can be minted.
*/
function setTokenLimit(uint256 tokenLimit) public onlyOwner {
require(getTokenLimit() == 0, "CXIP: token limit already set");
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.tokenLimit')) - 1);
assembly {
sstore(
/* slot */
0xb63653e470fa8e7fcc528e0068173a1969fdee5ae0ee29dd58e7b6111b829c56,
tokenLimit
)
}
}
/**
* @dev Gets the token separator from storage slot.
* @return tokenSeparator The number of tokens before separation.
*/
function getTokenSeparator() public view returns (uint256 tokenSeparator) {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.tokenSeparator')) - 1);
assembly {
tokenSeparator := sload(
/* slot */
0x988145eec05de02f4c5d4ecd419a9617237db574d35b27207657cbd8c5b1f045
)
}
}
/**
* @dev Sets the token separator to storage slot.
* @param tokenSeparator The number of tokens before separation.
*/
function setTokenSeparator(uint256 tokenSeparator) public onlyOwner {
require(getTokenSeparator() == 0, "CXIP: separator already set");
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.tokenSeparator')) - 1);
assembly {
sstore(
/* slot */
0x988145eec05de02f4c5d4ecd419a9617237db574d35b27207657cbd8c5b1f045,
tokenSeparator
)
}
}
/**
* @notice Set an NFT state.
* @dev Time-based states will be retrieved by index.
* @param id The index of time slot to set for.
* @param tokenData The token data for the particular time slot.
*/
function prepareMintData(uint256 id, TokenData calldata tokenData) public onlyOwner {
require(Address.isZero(_tokenData[id].creator), "CXIP: token data already set");
_tokenData[id] = tokenData;
}
function prepareMintDataBatch(uint256[] calldata ids, TokenData[] calldata tokenData) public onlyOwner {
require(ids.length == tokenData.length, "CXIP: array lengths missmatch");
for (uint256 i = 0; i < ids.length; i++) {
require(Address.isZero(_tokenData[ids[i]].creator), "CXIP: token data already set");
_tokenData[ids[i]] = tokenData[i];
}
}
/**
* @notice Sets a name for the collection.
* @dev The name is split in two for gas optimization.
* @param newName First part of name.
* @param newName2 Second part of name.
*/
function setName(bytes32 newName, bytes32 newName2) public onlyOwner {
_collectionData.name = newName;
_collectionData.name2 = newName2;
}
/**
* @notice Sets the start timestamp for token rotations.
* @dev All rotation calculations will use this timestamp as the origin point from which to calculate.
* @param _timestamp UNIX timestamp in seconds.
*/
function setStartTimestamp(uint256 _timestamp) public onlyOwner {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.startTimestamp')) - 1);
assembly {
sstore(
/* slot */
0xf2aaccfcfa4e77d7601ed4ebe139368f313960f63d25a2f26ec905d019eba48b,
_timestamp
)
}
}
/**
* @notice Set a symbol for the collection.
* @dev This is the ticker symbol for smart contract that shows up on EtherScan.
* @param newSymbol The ticker symbol to set for smart contract.
*/
function setSymbol(bytes32 newSymbol) public onlyOwner {
_collectionData.symbol = newSymbol;
}
/**
* @notice Transfers ownership of the collection.
* @dev Can't be the zero address.
* @param newOwner Address of new owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(!Address.isZero(newOwner), "CXIP: zero address");
_owner = newOwner;
}
/**
* @notice Get total number of tokens owned by wallet.
* @dev Used to see total amount of tokens owned by a specific wallet.
* @param wallet Address for which to get token balance.
* @return uint256 Returns an integer, representing total amount of tokens held by address.
*/
function balanceOf(address wallet) public view returns (uint256) {
require(!Address.isZero(wallet), "CXIP: zero address");
return _ownedTokensCount[wallet];
}
/**
* @notice Get a base URI for the token.
* @dev Concatenates with the CXIP domain name.
* @return string the token URI.
*/
function baseURI() public view returns (string memory) {
return string(abi.encodePacked("https://nft.cxip.io/", Strings.toHexString(address(this))));
}
/**
* @notice Gets the approved address for the token.
* @dev Single operator set for a specific token. Usually used for one-time very specific authorisations.
* @param tokenId Token id to get approved operator for.
* @return address Approved address for token.
*/
function getApproved(uint256 tokenId) public view returns (address) {
return _tokenApprovals[tokenId];
}
/**
* @notice Get the associated identity for the collection.
* @dev Goes up the chain to read from the registry.
* @return address Identity contract address.
*/
function getIdentity() public view returns (address) {
return ICxipProvenance(getRegistry().getProvenance()).getWalletIdentity(_owner);
}
/**
* @notice Checks if the address is approved.
* @dev Includes references to OpenSea and Rarible marketplace proxies.
* @param wallet Address of the wallet.
* @param operator Address of the marketplace operator.
* @return bool True if approved.
*/
function isApprovedForAll(address wallet, address operator) public view returns (bool) {
return _operatorApprovals[wallet][operator];
}
/**
* @notice Check if the sender is the owner.
* @dev The owner could also be the admin or identity contract of the owner.
* @return bool True if owner.
*/
function isOwner() public view returns (bool) {
return (msg.sender == _owner || msg.sender == _admin || isIdentityWallet(msg.sender));
}
/**
* @notice Gets the owner's address.
* @dev _owner is first set in init.
* @return address Of ower.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @notice Checks who the owner of a token is.
* @dev The token must exist.
* @param tokenId The token to look up.
* @return address Owner of the token.
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address tokenOwner = _tokenOwner[tokenId];
require(!Address.isZero(tokenOwner), "ERC721: token does not exist");
return tokenOwner;
}
/**
* @notice Get token by index.
* @dev Used in conjunction with totalSupply function to iterate over all tokens in collection.
* @param index Index of token in array.
* @return uint256 Returns the token id of token located at that index.
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "CXIP: index out of bounds");
return _allTokens[index];
}
/**
* @notice Get token from wallet by index instead of token id.
* @dev Helpful for wallet token enumeration where token id info is not yet available. Use in conjunction with balanceOf function.
* @param wallet Specific address for which to get token for.
* @param index Index of token in array.
* @return uint256 Returns the token id of token located at that index in specified wallet.
*/
function tokenOfOwnerByIndex(address wallet, uint256 index) public view returns (uint256) {
require(index < balanceOf(wallet), "CXIP: index out of bounds");
return _ownedTokens[wallet][index];
}
/**
* @notice Total amount of tokens in the collection.
* @dev Ignores burned tokens.
* @return uint256 Returns the total number of active (not burned) tokens.
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @notice Empty function that is triggered by external contract on NFT transfer.
* @dev We have this blank function in place to make sure that external contract sending in NFTs don't error out.
* @dev Since it's not being used, the _operator variable is commented out to avoid compiler warnings.
* @dev Since it's not being used, the _from variable is commented out to avoid compiler warnings.
* @dev Since it's not being used, the _tokenId variable is commented out to avoid compiler warnings.
* @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings.
* @return bytes4 Returns the interfaceId of onERC721Received.
*/
function onERC721Received(
address,
/*_operator*/
address,
/*_from*/
uint256,
/*_tokenId*/
bytes calldata /*_data*/
) public pure returns (bytes4) {
return 0x150b7a02;
}
/**
* @notice Allows retrieval of royalties from the contract.
* @dev This is a default fallback to ensure the royalties are available.
*/
function _royaltiesFallback() internal {
address _target = getRegistry().getPA1D();
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), _target, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @notice Checks if an address is an identity contract.
* @dev It must also be registred.
* @param sender Address to check if registered to identity.
* @return bool True if registred identity.
*/
function isIdentityWallet(address sender) internal view returns (bool) {
address identity = getIdentity();
if (Address.isZero(identity)) {
return false;
}
return ICxipIdentity(identity).isWalletRegistered(sender);
}
/**
* @dev Get the top-level CXIP Registry smart contract. Function must always be internal to prevent miss-use/abuse through bad programming practices.
* @return ICxipRegistry The address of the top-level CXIP Registry smart contract.
*/
function getRegistry() internal pure returns (ICxipRegistry) {
return ICxipRegistry(0xC267d41f81308D7773ecB3BDd863a902ACC01Ade);
}
/**
* @dev Add a newly minted token into managed list of tokens.
* @param to Address of token owner for which to add the token.
* @param tokenId Id of token to add.
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokensCount[to];
_ownedTokensCount[to]++;
_ownedTokens[to].push(tokenId);
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @notice Deletes a token from the approval list.
* @dev Removes from count.
* @param tokenId T.
*/
function _clearApproval(uint256 tokenId) private {
delete _tokenApprovals[tokenId];
}
/**
* @notice Mints an NFT.
* @dev Can to mint the token to the zero address and the token cannot already exist.
* @param to Address to mint to.
* @param tokenId The new token.
*/
function _mint(address to, uint256 tokenId) private {
require(!Address.isZero(to), "CXIP: can't mint a burn");
require(!_exists(tokenId), "CXIP: token already exists");
_tokenOwner[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId;
_allTokensIndex[lastTokenId] = tokenIndex;
delete _allTokensIndex[tokenId];
delete _allTokens[lastTokenIndex];
_allTokens.pop();
}
/**
* @dev Remove a token from managed list of tokens.
* @param from Address of token owner for which to remove the token.
* @param tokenId Id of token to remove.
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
_removeTokenFromAllTokensEnumeration(tokenId);
_ownedTokensCount[from]--;
uint256 lastTokenIndex = _ownedTokensCount[from];
uint256 tokenIndex = _ownedTokensIndex[tokenId];
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId;
_ownedTokensIndex[lastTokenId] = tokenIndex;
}
if (lastTokenIndex == 0) {
delete _ownedTokens[from];
} else {
delete _ownedTokens[from][lastTokenIndex];
_ownedTokens[from].pop();
}
}
/**
* @dev Primary internal function that handles the transfer/mint/burn functionality.
* @param from Address from where token is being transferred. Zero address means it is being minted.
* @param to Address to whom the token is being transferred. Zero address means it is being burned.
* @param tokenId Id of token that is being transferred/minted/burned.
*/
function _transferFrom(
address from,
address to,
uint256 tokenId
) private {
require(_tokenOwner[tokenId] == from, "CXIP: not from's token");
require(!Address.isZero(to), "CXIP: use burn instead");
_clearApproval(tokenId);
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @notice Checks if the token owner exists.
* @dev If the address is the zero address no owner exists.
* @param tokenId The affected token.
* @return bool True if it exists.
*/
function _exists(uint256 tokenId) private view returns (bool) {
address tokenOwner = _tokenOwner[tokenId];
return !Address.isZero(tokenOwner);
}
/**
* @notice Checks if the address is an approved one.
* @dev Uses inlined checks for different usecases of approval.
* @param spender Address of the spender.
* @param tokenId The affected token.
* @return bool True if approved.
*/
function _isApproved(address spender, uint256 tokenId) private view returns (bool) {
require(_exists(tokenId));
address tokenOwner = _tokenOwner[tokenId];
return (spender == tokenOwner || getApproved(tokenId) == spender || isApprovedForAll(tokenOwner, spender));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
contract OpenSeaOwnableDelegateProxy {}
contract OpenSeaProxyRegistry {
mapping(address => OpenSeaOwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
interface IERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
import "../struct/CollectionData.sol";
import "../struct/TokenData.sol";
import "../struct/Verification.sol";
interface ICxipERC721 {
function arweaveURI(uint256 tokenId) external view returns (string memory);
function contractURI() external view returns (string memory);
function creator(uint256 tokenId) external view returns (address);
function httpURI(uint256 tokenId) external view returns (string memory);
function ipfsURI(uint256 tokenId) external view returns (string memory);
function name() external view returns (string memory);
function payloadHash(uint256 tokenId) external view returns (bytes32);
function payloadSignature(uint256 tokenId) external view returns (Verification memory);
function payloadSigner(uint256 tokenId) external view returns (address);
function supportsInterface(bytes4 interfaceId) external view returns (bool);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
function tokensOfOwner(address wallet) external view returns (uint256[] memory);
function verifySHA256(bytes32 hash, bytes calldata payload) external pure returns (bool);
function approve(address to, uint256 tokenId) external;
function burn(uint256 tokenId) external;
function init(address newOwner, CollectionData calldata collectionData) external;
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external payable;
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) external payable;
function setApprovalForAll(address to, bool approved) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external payable;
function transferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) external payable;
function cxipMint(uint256 id, TokenData calldata tokenData) external returns (uint256);
function setApprovalForAll(
address from,
address to,
bool approved
) external;
function setName(bytes32 newName, bytes32 newName2) external;
function setSymbol(bytes32 newSymbol) external;
function transferOwnership(address newOwner) external;
function balanceOf(address wallet) external view returns (uint256);
function baseURI() external view returns (string memory);
function getApproved(uint256 tokenId) external view returns (address);
function getIdentity() external view returns (address);
function isApprovedForAll(address wallet, address operator) external view returns (bool);
function isOwner() external view returns (bool);
function owner() external view returns (address);
function ownerOf(uint256 tokenId) external view returns (address);
function tokenByIndex(uint256 index) external view returns (uint256);
function tokenOfOwnerByIndex(address wallet, uint256 index) external view returns (uint256);
function totalSupply() external view returns (uint256);
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external pure returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
import "../struct/CollectionData.sol";
import "../struct/InterfaceType.sol";
import "../struct/Token.sol";
import "../struct/TokenData.sol";
interface ICxipIdentity {
function addSignedWallet(
address newWallet,
uint8 v,
bytes32 r,
bytes32 s
) external;
function addWallet(address newWallet) external;
function connectWallet() external;
function createERC721Token(
address collection,
uint256 id,
TokenData calldata tokenData,
Verification calldata verification
) external returns (uint256);
function createERC721Collection(
bytes32 saltHash,
address collectionCreator,
Verification calldata verification,
CollectionData calldata collectionData
) external returns (address);
function createCustomERC721Collection(
bytes32 saltHash,
address collectionCreator,
Verification calldata verification,
CollectionData calldata collectionData,
bytes32 slot,
bytes memory bytecode
) external returns (address);
function init(address wallet, address secondaryWallet) external;
function getAuthorizer(address wallet) external view returns (address);
function getCollectionById(uint256 index) external view returns (address);
function getCollectionType(address collection) external view returns (InterfaceType);
function getWallets() external view returns (address[] memory);
function isCollectionCertified(address collection) external view returns (bool);
function isCollectionRegistered(address collection) external view returns (bool);
function isNew() external view returns (bool);
function isOwner() external view returns (bool);
function isTokenCertified(address collection, uint256 tokenId) external view returns (bool);
function isTokenRegistered(address collection, uint256 tokenId) external view returns (bool);
function isWalletRegistered(address wallet) external view returns (bool);
function listCollections(uint256 offset, uint256 length)
external
view
returns (address[] memory);
function nextNonce(address wallet) external view returns (uint256);
function totalCollections() external view returns (uint256);
function isCollectionOpen(address collection) external pure returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
interface ICxipProvenance {
function createIdentity(
bytes32 saltHash,
address wallet,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256, address);
function createIdentityBatch(
bytes32 saltHash,
address[] memory wallets,
uint8[] memory V,
bytes32[] memory RS
) external returns (uint256, address);
function getIdentity() external view returns (address);
function getWalletIdentity(address wallet) external view returns (address);
function informAboutNewWallet(address newWallet) external;
function isIdentityValid(address identity) external view returns (bool);
function nextNonce(address wallet) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
interface ICxipRegistry {
function getAsset() external view returns (address);
function getAssetSigner() external view returns (address);
function getAssetSource() external view returns (address);
function getCopyright() external view returns (address);
function getCopyrightSource() external view returns (address);
function getCustomSource(bytes32 name) external view returns (address);
function getCustomSourceFromString(string memory name) external view returns (address);
function getERC1155CollectionSource() external view returns (address);
function getERC721CollectionSource() external view returns (address);
function getIdentitySource() external view returns (address);
function getPA1D() external view returns (address);
function getPA1DSource() external view returns (address);
function getProvenance() external view returns (address);
function getProvenanceSource() external view returns (address);
function owner() external view returns (address);
function setAsset(address proxy) external;
function setAssetSigner(address source) external;
function setAssetSource(address source) external;
function setCopyright(address proxy) external;
function setCopyrightSource(address source) external;
function setCustomSource(string memory name, address source) external;
function setERC1155CollectionSource(address source) external;
function setERC721CollectionSource(address source) external;
function setIdentitySource(address source) external;
function setPA1D(address proxy) external;
function setPA1DSource(address source) external;
function setProvenance(address proxy) external;
function setProvenanceSource(address source) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
import "../library/Zora.sol";
interface IPA1D {
function init(
uint256 tokenId,
address payable receiver,
uint256 bp
) external;
function configurePayouts(address payable[] memory addresses, uint256[] memory bps) external;
function getPayoutInfo()
external
view
returns (address payable[] memory addresses, uint256[] memory bps);
function getEthPayout() external;
function getTokenPayout(address tokenAddress) external;
function getTokenPayoutByName(string memory tokenName) external;
function getTokensPayout(address[] memory tokenAddresses) external;
function getTokensPayoutByName(string[] memory tokenNames) external;
function supportsInterface(bytes4 interfaceId) external pure returns (bool);
function setRoyalties(
uint256 tokenId,
address payable receiver,
uint256 bp
) external;
function royaltyInfo(uint256 tokenId, uint256 value) external view returns (address, uint256);
function getFeeBps(uint256 tokenId) external view returns (uint256[] memory);
function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory);
function getRoyalties(uint256 tokenId)
external
view
returns (address payable[] memory, uint256[] memory);
function getFees(uint256 tokenId)
external
view
returns (address payable[] memory, uint256[] memory);
function tokenCreator(address contractAddress, uint256 tokenId) external view returns (address);
function calculateRoyaltyFee(
address contractAddress,
uint256 tokenId,
uint256 amount
) external view returns (uint256);
function marketContract() external view returns (address);
function tokenCreators(uint256 tokenId) external view returns (address);
function bidSharesForToken(uint256 tokenId)
external
view
returns (Zora.BidShares memory bidShares);
function getStorageSlot(string calldata slot) external pure returns (bytes32);
function getTokenAddress(string memory tokenName) external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
assembly {
codehash := extcodehash(account)
}
return (codehash != 0x0 &&
codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
function isZero(address account) internal pure returns (bool) {
return (account == address(0));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
library Bytes {
function getBoolean(uint192 _packedBools, uint192 _boolNumber) internal pure returns (bool) {
uint192 flag = (_packedBools >> _boolNumber) & uint192(1);
return (flag == 1 ? true : false);
}
function setBoolean(
uint192 _packedBools,
uint192 _boolNumber,
bool _value
) internal pure returns (uint192) {
if (_value) {
return _packedBools | (uint192(1) << _boolNumber);
} else {
return _packedBools & ~(uint192(1) << _boolNumber);
}
}
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
tempBytes := mload(0x40)
let lengthmod := and(_length, 31)
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
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)
mstore(0x40, and(add(mc, 31), not(31)))
}
default {
tempBytes := mload(0x40)
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function trim(bytes32 source) internal pure returns (bytes memory) {
uint256 temp = uint256(source);
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return slice(abi.encodePacked(source), 32 - length, length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
library Strings {
function toHexString(address account) internal pure returns (string memory) {
return toHexString(uint256(uint160(account)));
}
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);
}
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] = bytes16("0123456789abcdef")[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
import "./UriType.sol";
struct CollectionData {
bytes32 name;
bytes32 name2;
bytes32 symbol;
address royalties;
uint96 bps;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
import "./Verification.sol";
struct TokenData {
bytes32 payloadHash;
Verification payloadSignature;
address creator;
bytes32 arweave;
bytes11 arweave2;
bytes32 ipfs;
bytes14 ipfs2;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
struct Verification {
bytes32 r;
bytes32 s;
uint8 v;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
// This is a 256 value limit (uint8)
enum UriType {
ARWEAVE, // 0
IPFS, // 1
HTTP // 2
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
// This is a 256 value limit (uint8)
enum InterfaceType {
NULL, // 0
ERC20, // 1
ERC721, // 2
ERC1155 // 3
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
import "./InterfaceType.sol";
struct Token {
address collection;
uint256 tokenId;
InterfaceType tokenType;
address creator;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
library Zora {
struct Decimal {
uint256 value;
}
struct BidShares {
// % of sale value that goes to the _previous_ owner of the nft
Decimal prevOwner;
// % of sale value that goes to the original creator of the nft
Decimal creator;
// % of sale value that goes to the seller (current owner) of the nft
Decimal owner;
}
}
|
Gets the token separator from storage slot. return tokenSeparator The number of tokens before separation./ The slot hash has been precomputed for gas optimizaion bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.tokenSeparator')) - 1);
|
function getTokenSeparator() public view returns (uint256 tokenSeparator) {
assembly {
tokenSeparator := sload(
0x988145eec05de02f4c5d4ecd419a9617237db574d35b27207657cbd8c5b1f045
)
}
| 1,359,571 |
/**
*Submitted for verification at Etherscan.io on 2021-10-16
*/
// SPDX-License-Identifier: UNLICENSED
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;
}
}
/**
* @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);
}
}
interface IPUNK {
function punkIndexToAddress(uint256 punkID) external view returns (address);
}
/**
* @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 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);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(
currentAllowance >= amount,
"ERC20: transfer amount exceeds allowance"
);
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender] + addedValue
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(
senderBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
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 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 Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/// @title Papi Token for NNW holders!
/// @author Will Papper <https://twitter.com/WillPapper>
/// @notice This contract mints Papi Token for NNW holders and provides
/// administrative functions to the NNW DAO. It allows:
/// * NNW holders to claim Papi Token
/// * A DAO to set seasons for new opportunities to claim Papi Token
/// * A DAO to mint Papi Token for use within the NNW ecosystem
/// @custom:unaudited This contract has not been audited. Use at your own risk.
contract PapiToken is Context, Ownable, ERC20 {
// NNW contract is available at https://etherscan.io/address/0xEDBaca315748B5a539cf7FB97447A62680b36575
address public NNWContractAddress =
0x602e3a0887cB381366653DF707d38DC3091870Db;
IERC721Enumerable public NNWContract;
address public cdbcontractAddress =
0x42069ABFE407C60cf4ae4112bEDEaD391dBa1cdB;
IERC721Enumerable public cdbcontract;
address public toadzContractAddress =
0x1CB1A5e65610AEFF2551A50f76a87a7d3fB649C6;
IERC721Enumerable public toadContract;
address public punksContractAddress =
0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB;
IPUNK public punksContract;
function daoSetcdbContractAddress(address cdbContractAddress_)
external
onlyOwner
{
cdbcontractAddress = cdbContractAddress_;
cdbcontract = IERC721Enumerable(cdbcontractAddress);
}
function daoSetToadzContractAddress(address toadzContractAddress_)
external
onlyOwner
{
toadzContractAddress = toadzContractAddress_;
toadContract = IERC721Enumerable(toadzContractAddress);
}
function daoSetPunksContractAddress(address punksContractAddress_)
external
onlyOwner
{
punksContractAddress = punksContractAddress_;
punksContract = IPUNK(punksContractAddress);
}
// Give out 10,000 Papi Token for every NNW Bag that a user holds
uint256 public papiTokenPerTokenId = 1000 * (10**decimals());
// tokenIdStart of 1 is based on the following lines in the NNW contract:
/**
function claim(uint256 tokenId) public nonReentrant {
require(tokenId > 0 && tokenId < 7778, "Token ID invalid");
_safeMint(_msgSender(), tokenId);
}
*/
uint256 public cdbtokenIdStart = 160;
uint256 public toadtokenIdStart = 1;
uint256 public NNWtokenIdStart = 1;
uint256 public punkstokenIdStart = 0;
// tokenIdEnd of 8000 is based on the following lines in the NNW contract:
/**
function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner {
require(tokenId > 7777 && tokenId < 8001, "Token ID invalid");
_safeMint(owner(), tokenId);
}
*/
uint256 public cdbtokenIdEnd = 5359;
uint256 public toadtokenIdEnd = 6969;
uint256 public NNWtokenIdEnd = 8000;
uint256 public punkstokenIdEnd = 9999;
// Seasons are used to allow users to claim tokens regularly. Seasons are
// decided by the DAO.
uint256 public season = 0;
// Track claimed tokens within a season
// IMPORTANT: The format of the mapping is:
// claimedForSeason[season][tokenId][claimed]
mapping(uint256 => mapping(uint256 => bool))
public seasonNNWClaimedByTokenId;
mapping(uint256 => mapping(uint256 => bool))
public seasonCdbClaimedByTokenId;
mapping(uint256 => mapping(uint256 => bool))
public seasonToadClaimedByTokenId;
mapping(uint256 => mapping(uint256 => bool))
public seasonOGpunksClaimedByTokenId;
constructor() Ownable() ERC20("Papi Token", "PAPI") {
// Transfer ownership to the NNW DAO
// Ownable by OpenZeppelin automatically sets owner to msg.sender, but
// we're going to be using a separate wallet for deployment
transferOwnership(0xEA2b1D5d02A676f172093D28Cc7A0Cb088E04f75);
NNWContract = IERC721Enumerable(NNWContractAddress);
cdbcontract = IERC721Enumerable(cdbcontractAddress);
toadContract = IERC721Enumerable(toadzContractAddress);
punksContract = IPUNK(punksContractAddress);
}
/// @notice Claim Papi Token for a given NNW ID
/// @param tokenId The tokenId of the NNW NFT
function claimById(uint256 tokenId, uint256 contractID) external {
// Follow the Checks-Effects-Interactions pattern to prevent reentrancy
// attacks
// Checks
// Check that the msgSender owns the token that is being claimed
require(contractID == 1 || contractID == 2 || contractID == 3);
if (contractID == 1) {
require(
_msgSender() == NNWContract.ownerOf(tokenId),
"MUST_OWN_TOKEN_ID"
);
}
if (contractID == 2) {
require(
_msgSender() == cdbcontract.ownerOf(tokenId),
"MUST_OWN_TOKEN_ID"
);
}
if (contractID == 3) {
require(
_msgSender() == toadContract.ownerOf(tokenId),
"MUST_OWN_TOKEN_ID"
);
}
// Further Checks, Effects, and Interactions are contained within the
// _claim() function
_claim(tokenId, _msgSender(), contractID);
}
/// @notice Claim Papi Token for all tokens owned by the sender
/// @notice This function will run out of gas if you have too much NNW! If
/// this is a concern, you should use claimRangeForOwner and claim Papi
/// Token in batches.
function claimAllForOwner(uint256 contractID) external {
require(contractID == 1 || contractID == 2 || contractID == 3);
// Checks
if (contractID == 1) {
uint256 tokenBalanceOwner = NNWContract.balanceOf(_msgSender());
require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED");
for (uint256 i = 0; i < tokenBalanceOwner; i++) {
// Further Checks, Effects, and Interactions are contained within
// the _claim() function
_claim(
NNWContract.tokenOfOwnerByIndex(_msgSender(), i),
_msgSender(),
contractID
);
}
}
if (contractID == 2) {
uint256 tokenBalanceOwner = cdbcontract.balanceOf(_msgSender());
require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED");
for (uint256 i = 0; i < tokenBalanceOwner; i++) {
// Further Checks, Effects, and Interactions are contained within
// the _claim() function
_claim(
cdbcontract.tokenOfOwnerByIndex(_msgSender(), i),
_msgSender(),
contractID
);
}
}
if (contractID == 3) {
uint256 tokenBalanceOwner = toadContract.balanceOf(_msgSender());
require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED");
for (uint256 i = 0; i < tokenBalanceOwner; i++) {
// Further Checks, Effects, and Interactions are contained within
// the _claim() function
_claim(
toadContract.tokenOfOwnerByIndex(_msgSender(), i),
_msgSender(),
contractID
);
}
}
// i < tokenBalanceOwner because tokenBalanceOwner is 1-indexed
}
/// @notice Claim Papi Token for all tokens owned by the sender within a
/// given range
/// @notice This function is useful if you own too much NNW to claim all at
/// once or if you want to leave some NNW unclaimed. If you leave NNW
/// unclaimed, however, you cannot claim it once the next season starts.
function claimRangeForOwner(
uint256 ownerIndexStart,
uint256 ownerIndexEnd,
uint256 contractID
) external {
require(contractID == 1 || contractID == 2 || contractID == 3);
if (contractID == 1) {
uint256 tokenBalanceOwner = NNWContract.balanceOf(_msgSender());
require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED");
require(
ownerIndexStart >= 0 && ownerIndexEnd < tokenBalanceOwner,
"INDEX_OUT_OF_RANGE"
);
for (uint256 i = ownerIndexStart; i <= ownerIndexEnd; i++) {
// Further Checks, Effects, and Interactions are contained within
// the _claim() function
_claim(
NNWContract.tokenOfOwnerByIndex(_msgSender(), i),
_msgSender(),
contractID
);
}
}
if (contractID == 2) {
uint256 tokenBalanceOwner = cdbcontract.balanceOf(_msgSender());
require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED");
require(
ownerIndexStart >= 0 && ownerIndexEnd < tokenBalanceOwner,
"INDEX_OUT_OF_RANGE"
);
for (uint256 i = ownerIndexStart; i <= ownerIndexEnd; i++) {
// Further Checks, Effects, and Interactions are contained within
// the _claim() function
_claim(
cdbcontract.tokenOfOwnerByIndex(_msgSender(), i),
_msgSender(),
contractID
);
}
}
if (contractID == 3) {
uint256 tokenBalanceOwner = toadContract.balanceOf(_msgSender());
require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED");
require(
ownerIndexStart >= 0 && ownerIndexEnd < tokenBalanceOwner,
"INDEX_OUT_OF_RANGE"
);
for (uint256 i = ownerIndexStart; i <= ownerIndexEnd; i++) {
// Further Checks, Effects, and Interactions are contained within
// the _claim() function
_claim(
toadContract.tokenOfOwnerByIndex(_msgSender(), i),
_msgSender(),
contractID
);
}
}
}
// Claim Punks
function claimFromPunkID(uint256 tokenId) external {
require(
_msgSender() == punksContract.punkIndexToAddress(tokenId),
"MUST_OWN_TOKEN_ID"
);
_claim(tokenId, _msgSender(), 4);
}
function claimFromMultiplePunkIDs(uint256[] memory tokenId) external {
for (uint256 i = 0; i < tokenId.length; i++) {
require(
_msgSender() == punksContract.punkIndexToAddress(tokenId[i]),
"MUST_OWN_TOKEN_ID"
);
_claim(tokenId[i], _msgSender(), 4);
}
}
/// @dev Internal function to mint NNW upon claiming
function _claim(
uint256 tokenId,
address tokenOwner,
uint256 contractID
) internal {
// Checks
// Check that the token ID is in range
// We use >= and <= to here because all of the token IDs are 0-indexed
if (contractID == 1) {
require(
tokenId >= NNWtokenIdStart && tokenId <= NNWtokenIdEnd,
"TOKEN_ID_OUT_OF_RANGE"
);
require(
!seasonNNWClaimedByTokenId[season][tokenId],
"GOLD_CLAIMED_FOR_TOKEN_ID"
);
seasonNNWClaimedByTokenId[season][tokenId] = true;
_mint(tokenOwner, papiTokenPerTokenId);
}
if (contractID == 2) {
require(
tokenId >= cdbtokenIdStart && tokenId <= cdbtokenIdEnd,
"TOKEN_ID_OUT_OF_RANGE"
);
require(
!seasonCdbClaimedByTokenId[season][tokenId],
"GOLD_CLAIMED_FOR_TOKEN_ID"
);
seasonCdbClaimedByTokenId[season][tokenId] = true;
_mint(tokenOwner, papiTokenPerTokenId);
}
if (contractID == 3) {
require(
tokenId >= toadtokenIdStart && tokenId <= toadtokenIdEnd,
"TOKEN_ID_OUT_OF_RANGE"
);
require(
!seasonToadClaimedByTokenId[season][tokenId],
"GOLD_CLAIMED_FOR_TOKEN_ID"
);
seasonToadClaimedByTokenId[season][tokenId] = true;
_mint(tokenOwner, papiTokenPerTokenId);
}
if (contractID == 4) {
require(
tokenId >= punkstokenIdStart && tokenId <= punkstokenIdEnd,
"TOKEN_ID_OUT_OF_RANGE"
);
require(
!seasonOGpunksClaimedByTokenId[season][tokenId],
"GOLD_CLAIMED_FOR_TOKEN_ID"
);
seasonOGpunksClaimedByTokenId[season][tokenId] = true;
_mint(tokenOwner, papiTokenPerTokenId);
}
}
/// @notice Allows the DAO to mint new tokens for use within the NNW
/// Ecosystem
/// @param amountDisplayValue The amount of NNW to mint. This should be
/// input as the display value, not in raw decimals. If you want to mint
/// 100 NNW, you should enter "100" rather than the value of 100 * 10^18.
function daoMint(uint256 amountDisplayValue) external onlyOwner {
_mint(owner(), amountDisplayValue * (10**decimals()));
}
/// @notice Allows the DAO to set a new contract address for NNW. This is
/// relevant in the event that NNW migrates to a new contract.
/// @param NNWContractAddress_ The new contract address for NNW
function daoSetNNWContractAddress(address NNWContractAddress_)
external
onlyOwner
{
NNWContractAddress = NNWContractAddress_;
NNWContract = IERC721Enumerable(NNWContractAddress);
}
/// @notice Allows the DAO to set the token IDs that are eligible to claim
/// NNW
/// @param tokenIdStart_ The start of the eligible token range
/// @param tokenIdEnd_ The end of the eligible token range
/// @dev This is relevant in case a future NNW contract has a different
/// total supply of NNW
function daoSetTokenIdRange(
uint256 tokenIdStart_,
uint256 tokenIdEnd_,
uint256 contractID
) external onlyOwner {
require(
contractID == 1 ||
contractID == 2 ||
contractID == 3 ||
contractID == 4
);
if (contractID == 1) {
NNWtokenIdStart = tokenIdStart_;
NNWtokenIdEnd = tokenIdEnd_;
}
if (contractID == 2) {
cdbtokenIdStart = tokenIdStart_;
cdbtokenIdEnd = tokenIdEnd_;
}
if (contractID == 3) {
toadtokenIdStart = tokenIdStart_;
toadtokenIdEnd = tokenIdEnd_;
}
if (contractID == 4) {
punkstokenIdStart = tokenIdStart_;
punkstokenIdEnd = tokenIdEnd_;
}
}
/// @notice Allows the DAO to set a season for new Papi Token claims
/// @param season_ The season to use for claiming NNW
function daoSetSeason(uint256 season_) public onlyOwner {
season = season_;
}
/// @notice Allows the DAO to set the amount of Papi Token that is
/// claimed per token ID
/// @param papiTokenDisplayValue The amount of NNW a user can claim.
/// This should be input as the display value, not in raw decimals. If you
/// want to mint 100 NNW, you should enter "100" rather than the value of
/// 100 * 10^18.
function daoSetpapiTokenPerTokenId(uint256 papiTokenDisplayValue)
public
onlyOwner
{
papiTokenPerTokenId = papiTokenDisplayValue * (10**decimals());
}
/// @notice Allows the DAO to set the season and Papi Token per token ID
/// in one transaction. This ensures that there is not a gap where a user
/// can claim more Papi Token than others
/// @param season_ The season to use for claiming NNW
/// @param papiTokenDisplayValue The amount of NNW a user can claim.
/// This should be input as the display value, not in raw decimals. If you
/// want to mint 100 NNW, you should enter "100" rather than the value of
/// 100 * 10^18.
/// @dev We would save a tiny amount of gas by modifying the season and
/// papiToken variables directly. It is better practice for security,
/// however, to avoid repeating code. This function is so rarely used that
/// it's not worth moving these values into their own internal function to
/// skip the gas used on the modifier check.
function daoSetSeasonAndpapiTokenPerTokenID(
uint256 season_,
uint256 papiTokenDisplayValue
) external onlyOwner {
daoSetSeason(season_);
daoSetpapiTokenPerTokenId(papiTokenDisplayValue);
}
}
|
Allows the DAO to set the season and Papi Token per token ID in one transaction. This ensures that there is not a gap where a user can claim more Papi Token than others season_ The season to use for claiming NNW papiTokenDisplayValue The amount of NNW a user can claim. This should be input as the display value, not in raw decimals. If you want to mint 100 NNW, you should enter "100" rather than the value of 100 10^18. We would save a tiny amount of gas by modifying the season and papiToken variables directly. It is better practice for security, however, to avoid repeating code. This function is so rarely used that it's not worth moving these values into their own internal function to skip the gas used on the modifier check.
|
function daoSetSeasonAndpapiTokenPerTokenID(
uint256 season_,
uint256 papiTokenDisplayValue
) external onlyOwner {
daoSetSeason(season_);
daoSetpapiTokenPerTokenId(papiTokenDisplayValue);
}
| 1,137,224 |
./partial_match/1/0x646Eb9B8E6bED62c0e46b67f3EfdEF926Fb9D621/sources/Whoopsies.sol
|
Utils Toggle v2 NFTs claim eligibility state
|
function toggleV2ClaimActive() public onlyOwner {
v2ClaimActive = !v2ClaimActive;
}
| 9,235,050 |
// SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./ERC721A.sol";
pragma solidity ^0.8.0;
/**
* @title Shark Society contract
* @dev Extends ERC721A Non-Fungible Token Standard basic implementation
*/
contract SharkSociety is ERC721A {
using SafeMath for uint256;
using Strings for uint256;
string public PROVENANCE;
uint256 public constant MAX_TOKENS = 5000;
uint256 public constant MAX_TOKENS_PLUS_ONE = 5001;
uint256 public sharkPrice = 0.04 ether;
uint256 public presaleSharkPrice = 0.03 ether;
uint public constant maxSharksPlusOne = 6;
uint public constant maxOwnedPlusOne = 9;
uint public constant maxForPresalePlusOne = 3;
bool public saleIsActive = false;
// Metadata base URI
string public baseURI;
// Whitelist and Presale
mapping(address => bool) Whitelist;
bool public presaleIsActive = false;
uint256 _maxBatchSize = 5;
uint256 _maxTotalSupply = 5000;
/**
@param name - Name of ERC721 as used in openzeppelin
@param symbol - Symbol of ERC721 as used in openzeppelin
@param provenance - The sha256 string of concatenated sha256 of all images in their natural order - AKA Provenance.
@param baseUri - Base URI for token metadata
*/
constructor(string memory name,
string memory symbol,
string memory provenance,
string memory baseUri)
ERC721A(name, symbol, _maxBatchSize, _maxTotalSupply){
PROVENANCE = provenance;
baseURI = baseUri;
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(0x0Cf7d58A50d5b3683Fd38c9f3934723DeC75A3c0).transfer(balance.mul(200).div(1000));
payable(0x8A7fA1106068DD75427525631b086208884111a5).transfer(balance.mul(200).div(1000));
payable(0xfc9DA6Edc4ABB3f3E4Ec2AD5B606514Ce1DE0dA4).transfer(balance.mul(240).div(1000));
payable(0xF5278A7BCc1546F22f7CD6b2B23286293139aF9B).transfer(balance.mul(100).div(1000));
payable(0x946f817599B788a58f4e85689F8D4a508dc3C801).transfer(balance.mul(150).div(1000));
payable(0xC68b81FBDff9587c3a024e7179a29329Ee9c1C8e).transfer(balance.mul(100).div(1000));
payable(0x38dE2236b854A8E06293237AeFaE4FDa94b2a2c3).transfer(balance.mul(10).div(1000));
}
/**
* @dev Sets the Base URI for computing {tokenURI}.
*/
function setBaseURI(string calldata _tokenBaseURI) external onlyOwner {
baseURI = _tokenBaseURI;
}
/**
* @dev Returns the base URI. Overrides empty string returned by base class.
* Unused because we override {tokenURI}.
* Included for completeness-sake.
*/
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
/**
* @dev Adds addresses to the whitelist
*/
function addToWhitelist(address[] calldata addrs) external onlyOwner {
for (uint i = 0; i < addrs.length; i++) {
Whitelist[addrs[i]] = true;
}
}
/**
* @dev Removes addresses from the whitelist
*/
function removeFromWhitelist(address[] calldata addrs) external onlyOwner {
for (uint i = 0; i < addrs.length; i++) {
Whitelist[addrs[i]] = false;
}
}
/**
* @dev Checks if an address is in the whitelist
*/
function isAddressInWhitelist(address addr) public view returns (bool) {
return Whitelist[addr];
}
/**
* @dev Checks if the sender's address is in the whitelist
*/
function isSenderInWhitelist() public view returns (bool) {
return Whitelist[msg.sender];
}
/**
* @dev Pause sale if active, activate if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Pause presale if active, activate if paused
*/
function flipPresaleState() public onlyOwner {
presaleIsActive = !presaleIsActive;
}
/*
* Set provenance hash - just in case there is an error
* Provenance hash is set in the contract construction time,
* ideally there is no reason to ever call it.
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
PROVENANCE = provenanceHash;
}
/**
* @dev Sets the mint price
*/
function setPrice(uint256 price) external onlyOwner {
require(price > 0, "Invalid price.");
sharkPrice = price;
}
/**
* @dev Sets the mint price
*/
function setPresalePrice(uint256 price) external onlyOwner {
require(price > 0, "Invalid price.");
presaleSharkPrice = price;
}
function registerForPresale() external {
require(!presaleIsActive, "The presale has already begun!");
Whitelist[msg.sender] = true;
}
/**
* @dev Mints Sharks
* Ether value sent must exactly match.
*/
function mintSharks(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Sharks.");
require(numberOfTokens < maxSharksPlusOne, "Can only mint 5 Sharks at a time.");
require(balanceOf(msg.sender).add(numberOfTokens) < maxOwnedPlusOne, "Purchase would exceed presale limit of 8 Sharks per address.");
require(totalSupply().add(numberOfTokens) < MAX_TOKENS_PLUS_ONE, "Purchase would exceed max supply of Sharks.");
require(sharkPrice.mul(numberOfTokens) == msg.value, "Ether value sent is not correct.");
_safeMint(msg.sender, numberOfTokens);
}
/**
* @dev Mints Sharks during the presale.
* Ether value sent must exactly match -
* and only addresses in {Whitelist} are allowed to participate in the presale.
*/
function presaleMintSharks(uint numberOfTokens) public payable {
require(presaleIsActive && !saleIsActive, "Presale is not active.");
require(isSenderInWhitelist(), "Your address is not in the whitelist.");
require(balanceOf(msg.sender).add(numberOfTokens) < maxForPresalePlusOne, "Purchase would exceed presale limit of 2 Sharks per address.");
require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Sharks.");
require(presaleSharkPrice.mul(numberOfTokens) == msg.value, "Ether value sent is not correct.");
_safeMint(msg.sender, numberOfTokens);
}
/**
* Reserve Sharks for future marketing and the team
*/
function reserveSharks(uint256 amount, address to) public onlyOwner {
uint supply = totalSupply();
require(supply.add(amount) < MAX_TOKENS_PLUS_ONE, "Reserving would exceed supply.");
_safeMint(to, amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.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";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
Ownable,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 public collectionSize;
uint256 internal immutable maxBatchSize;
// 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) private _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;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
* `collectionSize_` refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721B: collection must have a nonzero supply"
);
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
collectionSize = collectionSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @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 ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(
owner != address(0),
"ERC721A: balance query for the zero address"
);
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @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)
{
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 override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
require(
_exists(tokenId),
"ERC721A: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
override
{
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @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 = ERC721A.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @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 override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: 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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return (tokenId < currentIndex);
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - there must be `quantity` tokens remaining unminted in the total collection.
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721A.ownerOf(tokenId);
AddressData memory addressData = _addressData[owner];
_addressData[owner] = AddressData(
addressData.balance - 1,
addressData.numberMinted - 1
);
_ownerships[tokenId] = TokenOwnership(
address(0),
uint64(block.timestamp)
);
}
/**
* @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);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, 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;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > collectionSize - 1) {
endIndex = collectionSize - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721A: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* 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`.
*/
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.
*
* 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` 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 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Reserve Sharks for future marketing and the team/
|
function reserveSharks(uint256 amount, address to) public onlyOwner {
uint supply = totalSupply();
require(supply.add(amount) < MAX_TOKENS_PLUS_ONE, "Reserving would exceed supply.");
_safeMint(to, amount);
}
| 370,550 |
// File: canonical-weth/contracts/WETH9.sol
// Copyright (C) 2015, 2016, 2017 Dapphub
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.4.22 <0.6;
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
function() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return address(this).balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/protocol/lib/Require.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;
/**
* @title Require
* @author dYdX
*
* Stringifies parameters to pretty-print revert messages. Costs more gas than regular require()
*/
library Require {
// ============ Constants ============
uint256 constant ASCII_ZERO = 48; // '0'
uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10
uint256 constant ASCII_LOWER_EX = 120; // 'x'
bytes2 constant COLON = 0x3a20; // ': '
bytes2 constant COMMA = 0x2c20; // ', '
bytes2 constant LPAREN = 0x203c; // ' <'
byte constant RPAREN = 0x3e; // '>'
uint256 constant FOUR_BIT_MASK = 0xf;
// ============ Library Functions ============
function that(
bool must,
bytes32 file,
bytes32 reason
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason)
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
// ============ Private Functions ============
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
// put the input bytes into the result
bytes memory result = abi.encodePacked(input);
// determine the length of the input by finding the location of the last non-zero byte
for (uint256 i = 32; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// find the last non-zero byte in order to determine the length
if (result[i] != 0) {
uint256 length = i + 1;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
mstore(result, length) // r.length = length;
}
return result;
}
}
// all bytes are zero
return new bytes(0);
}
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
// get the final string length
uint256 j = input;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
// allocate the string
bytes memory bstr = new bytes(length);
// populate the string starting with the least-significant character
j = input;
for (uint256 i = length; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// take last decimal digit
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
// remove the last decimal digit
j /= 10;
}
return bstr;
}
function stringify(
address input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// addresses are "0x" followed by 20 bytes of data which take up 2 characters each
bytes memory result = new bytes(42);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 20; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[41 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[40 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function stringify(
bytes32 input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each
bytes memory result = new bytes(66);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 32; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[65 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[64 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function char(
uint256 input
)
private
pure
returns (byte)
{
// return ASCII digit (0-9)
if (input < 10) {
return byte(uint8(input + ASCII_ZERO));
}
// return ASCII letter (a-f)
return byte(uint8(input + ASCII_RELATIVE_ZERO));
}
}
// File: contracts/protocol/lib/Math.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title Math
* @author dYdX
*
* Library for non-standard Math functions
*/
library Math {
using SafeMath for uint256;
// ============ Constants ============
bytes32 constant FILE = "Math";
// ============ Library Functions ============
/*
* Return target * (numerator / denominator).
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
/*
* Return target * (numerator / denominator), but rounded up.
*/
function getPartialRoundUp(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (target == 0 || numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return target.mul(numerator).sub(1).div(denominator).add(1);
}
function getPartialRoundHalfUp(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (target == 0 || numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
uint result = target.mul(numerator);
// round the denominator comparator up to ensure a fair comparison is done on the `result`'s modulo.
// For example, 51 / 103 == 0; 51 % 103 == 51; ((103 - 1) / 2) + 1 == 52; 51 < 52, therefore no round up
return result.div(denominator).add(result.mod(denominator) >= denominator.sub(1).div(2).add(1) ? 1 : 0);
}
function to128(
uint256 number
)
internal
pure
returns (uint128)
{
uint128 result = uint128(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint128",
number
);
return result;
}
function to96(
uint256 number
)
internal
pure
returns (uint96)
{
uint96 result = uint96(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint96",
number
);
return result;
}
function to32(
uint256 number
)
internal
pure
returns (uint32)
{
uint32 result = uint32(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint32",
number
);
return result;
}
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
// File: contracts/protocol/lib/Types.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title Types
* @author dYdX
*
* Library for interacting with the basic structs used in DolomiteMargin
*/
library Types {
using Math for uint256;
// ============ Permission ============
struct OperatorArg {
address operator;
bool trusted;
}
// ============ AssetAmount ============
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
// ============ Par (Principal Amount) ============
// Total borrow and supply values for a market
struct TotalPar {
uint128 borrow;
uint128 supply;
}
// Individual principal amount for an account
struct Par {
bool sign; // true if positive
uint128 value;
}
function zeroPar()
internal
pure
returns (Par memory)
{
return Par({
sign: false,
value: 0
});
}
function sub(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
return add(a, negative(b));
}
function add(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
Par memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value).to128();
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value).to128();
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value).to128();
}
}
return result;
}
function equals(
Par memory a,
Par memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Par memory a
)
internal
pure
returns (Par memory)
{
return Par({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Par memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Par memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Par memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
function isLessThanZero(
Par memory a
)
internal
pure
returns (bool)
{
return a.value > 0 && !a.sign;
}
function isGreaterThanOrEqualToZero(
Par memory a
)
internal
pure
returns (bool)
{
return isZero(a) || a.sign;
}
// ============ Wei (Token Amount) ============
// Individual token amount for an account
struct Wei {
bool sign; // true if positive
uint256 value;
}
function zeroWei()
internal
pure
returns (Wei memory)
{
return Wei({
sign: false,
value: 0
});
}
function sub(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
return add(a, negative(b));
}
function add(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
Wei memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value);
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value);
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value);
}
}
return result;
}
function equals(
Wei memory a,
Wei memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Wei memory a
)
internal
pure
returns (Wei memory)
{
return Wei({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Wei memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Wei memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Wei memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
}
// File: contracts/protocol/lib/EnumerableSet.sol
/*
Copyright 2021 Dolomite.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
library EnumerableSet {
struct Set {
// Storage of set values
uint256[] _values;
// Value to the index in `_values` array, plus 1 because index 0 means a value is not in the set.
mapping(uint256 => uint256) _valueToIndexMap;
}
/**
* @dev Add a value to a set. O(1).
*
* @return true if the value was added to the set, that is if it was not already present.
*/
function add(Set storage set, uint256 value) internal returns (bool) {
if (!contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._valueToIndexMap[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* @return true if the value was removed from the set, that is if it was present.
*/
function remove(Set storage set, uint256 value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._valueToIndexMap[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) {
uint256 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._valueToIndexMap[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored, which is the last index
set._values.pop();
// Delete the index for the deleted slot
delete set._valueToIndexMap[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Set storage set, uint256 value) internal view returns (bool) {
return set._valueToIndexMap[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Set storage set) internal view returns (uint256) {
return set._values.length;
}
/**
* @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) internal view returns (uint256[] memory) {
return set._values;
}
}
// File: contracts/protocol/lib/Account.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title Account
* @author dYdX
*
* Library of structs and functions that represent an account
*/
library Account {
// ============ Enums ============
/*
* Most-recently-cached account status.
*
* Normal: Can only be liquidated if the account values are violating the global margin-ratio.
* Liquid: Can be liquidated no matter the account values.
* Can be vaporized if there are no more positive account values.
* Vapor: Has only negative (or zeroed) account values. Can be vaporized.
*
*/
enum Status {
Normal,
Liquid,
Vapor
}
// ============ Structs ============
// Represents the unique key that specifies an account
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
// The complete storage for any account
struct Storage {
Status status;
uint32 numberOfMarketsWithBorrow;
EnumerableSet.Set marketsWithNonZeroBalanceSet;
mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal
}
// ============ Library Functions ============
function equals(
Info memory a,
Info memory b
)
internal
pure
returns (bool)
{
return a.owner == b.owner && a.number == b.number;
}
}
// File: contracts/protocol/lib/Actions.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title Actions
* @author dYdX
*
* Library that defines and parses valid Actions
*/
library Actions {
// ============ Constants ============
bytes32 constant FILE = "Actions";
// ============ Enums ============
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {
OnePrimary,
TwoPrimary,
PrimaryAndSecondary
}
enum MarketLayout {
ZeroMarkets,
OneMarket,
TwoMarkets
}
// ============ Structs ============
/*
* Arguments that are passed to DolomiteMargin in an ordered list as part of a single operation.
* Each ActionArgs has an actionType which specifies which action struct that this data will be
* parsed into before being processed.
*/
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
// ============ Action Types ============
/*
* Moves tokens from an address to DolomiteMargin. Can either repay a borrow or provide additional supply.
*/
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
/*
* Moves tokens from DolomiteMargin to another address. Can either borrow tokens or reduce the amount
* previously supplied.
*/
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
/*
* Transfers balance between two accounts. The msg.sender must be an operator for both accounts.
* The amount field applies to accountOne.
* This action does not require any token movement since the trade is done internally to DolomiteMargin.
*/
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
/*
* Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field
* applies to the makerMarket.
*/
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies
* to the takerMarket.
*/
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Trades balances between two accounts using any external contract that implements the
* AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for
* which it is trading on-behalf-of). The amount field applies to the makerAccount and the
* inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will
* quote a change for the makerAccount in the outputMarket (or will disallow the trade).
* This action does not require any token movement since the trade is done internally to DolomiteMargin.
*/
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
/*
* Each account must maintain a certain margin-ratio (specified globally). If the account falls
* below this margin-ratio, it can be liquidated by any other account. This allows anyone else
* (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in
* exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined
* by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an
* account also sets a flag on the account that the account is being liquidated. This allows
* anyone to continue liquidating the account until there are no more borrows being taken by the
* liquidating account. Liquidators do not have to liquidate the entire account all at once but
* can liquidate as much as they choose. The liquidating flag allows liquidators to continue
* liquidating the account even if it becomes collateralized through partial liquidation or
* price movement.
*/
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Similar to liquidate, but vaporAccounts are accounts that have only negative balances remaining. The arbitrageur
* pays back the negative asset (owedMarket) of the vaporAccount in exchange for a collateral asset (heldMarket) at
* a favorable spread. However, since the liquidAccount has no collateral assets, the collateral must come from
* DolomiteMargin's excess tokens.
*/
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Passes arbitrary bytes of data to an external contract that implements the Callee interface.
* Does not change any asset amounts. This function may be useful for setting certain variables
* on layer-two contracts for certain accounts without having to make a separate Ethereum
* transaction for doing so. Also, the second-layer contracts can ensure that the call is coming
* from an operator of the particular account.
*/
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
// ============ Helper Functions ============
function getMarketLayout(
ActionType actionType
)
internal
pure
returns (MarketLayout)
{
if (
actionType == Actions.ActionType.Deposit
|| actionType == Actions.ActionType.Withdraw
|| actionType == Actions.ActionType.Transfer
) {
return MarketLayout.OneMarket;
}
else if (actionType == Actions.ActionType.Call) {
return MarketLayout.ZeroMarkets;
}
return MarketLayout.TwoMarkets;
}
function getAccountLayout(
ActionType actionType
)
internal
pure
returns (AccountLayout)
{
if (
actionType == Actions.ActionType.Transfer
|| actionType == Actions.ActionType.Trade
) {
return AccountLayout.TwoPrimary;
} else if (
actionType == Actions.ActionType.Liquidate
|| actionType == Actions.ActionType.Vaporize
) {
return AccountLayout.PrimaryAndSecondary;
}
return AccountLayout.OnePrimary;
}
// ============ Parsing Functions ============
function parseDepositArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (DepositArgs memory)
{
return DepositArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
from: args.otherAddress
});
}
function parseWithdrawArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (WithdrawArgs memory)
{
return WithdrawArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
to: args.otherAddress
});
}
function parseTransferArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TransferArgs memory)
{
return TransferArgs({
amount: args.amount,
accountOne: accounts[args.accountId],
accountTwo: accounts[args.otherAccountId],
market: args.primaryMarketId
});
}
function parseBuyArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (BuyArgs memory)
{
return BuyArgs({
amount: args.amount,
account: accounts[args.accountId],
makerMarket: args.primaryMarketId,
takerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseSellArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (SellArgs memory)
{
return SellArgs({
amount: args.amount,
account: accounts[args.accountId],
takerMarket: args.primaryMarketId,
makerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseTradeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TradeArgs memory)
{
return TradeArgs({
amount: args.amount,
takerAccount: accounts[args.accountId],
makerAccount: accounts[args.otherAccountId],
inputMarket: args.primaryMarketId,
outputMarket: args.secondaryMarketId,
autoTrader: args.otherAddress,
tradeData: args.data
});
}
function parseLiquidateArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (LiquidateArgs memory)
{
return LiquidateArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
liquidAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseVaporizeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (VaporizeArgs memory)
{
return VaporizeArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
vaporAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseCallArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (CallArgs memory)
{
return CallArgs({
account: accounts[args.accountId],
callee: args.otherAddress,
data: args.data
});
}
}
// File: contracts/protocol/lib/Decimal.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Functions ============
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function onePlus(
D256 memory d
)
internal
pure
returns (D256 memory)
{
return D256({ value: d.value.add(BASE) });
}
function mul(
uint256 target,
D256 memory d
)
internal
pure
returns (uint256)
{
return Math.getPartial(target, d.value, BASE);
}
function div(
uint256 target,
D256 memory d
)
internal
pure
returns (uint256)
{
return Math.getPartial(target, BASE, d.value);
}
}
// File: contracts/protocol/lib/Time.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title Time
* @author dYdX
*
* Library for dealing with time, assuming timestamps fit within 32 bits (valid until year 2106)
*/
library Time {
// ============ Library Functions ============
function currentTime()
internal
view
returns (uint32)
{
return Math.to32(block.timestamp);
}
}
// File: contracts/protocol/lib/Interest.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title Interest
* @author dYdX
*
* Library for managing the interest rate and interest indexes of DolomiteMargin
*/
library Interest {
using Math for uint256;
using SafeMath for uint256;
// ============ Constants ============
bytes32 constant FILE = "Interest";
uint64 constant BASE = 10**18;
// ============ Structs ============
struct Rate {
uint256 value;
}
struct Index {
uint96 borrow;
uint96 supply;
uint32 lastUpdate;
}
// ============ Library Functions ============
/**
* Get a new market Index based on the old index and market interest rate.
* Calculate interest for borrowers by using the formula rate * time. Approximates
* continuously-compounded interest when called frequently, but is much more
* gas-efficient to calculate. For suppliers, the interest rate is adjusted by the earningsRate,
* then prorated across all suppliers.
*
* @param index The old index for a market
* @param rate The current interest rate of the market
* @param totalPar The total supply and borrow par values of the market
* @param earningsRate The portion of the interest that is forwarded to the suppliers
* @return The updated index for a market
*/
function calculateNewIndex(
Index memory index,
Rate memory rate,
Types.TotalPar memory totalPar,
Decimal.D256 memory earningsRate
)
internal
view
returns (Index memory)
{
(
Types.Wei memory supplyWei,
Types.Wei memory borrowWei
) = totalParToWei(totalPar, index);
// get interest increase for borrowers
uint32 currentTime = Time.currentTime();
uint256 borrowInterest = rate.value.mul(uint256(currentTime).sub(index.lastUpdate));
// get interest increase for suppliers
uint256 supplyInterest;
if (Types.isZero(supplyWei)) {
supplyInterest = 0;
} else {
supplyInterest = Decimal.mul(borrowInterest, earningsRate);
if (borrowWei.value < supplyWei.value) {
supplyInterest = Math.getPartial(supplyInterest, borrowWei.value, supplyWei.value);
}
}
assert(supplyInterest <= borrowInterest);
return Index({
borrow: Math.getPartial(index.borrow, borrowInterest, BASE).add(index.borrow).to96(),
supply: Math.getPartial(index.supply, supplyInterest, BASE).add(index.supply).to96(),
lastUpdate: currentTime
});
}
function newIndex()
internal
view
returns (Index memory)
{
return Index({
borrow: BASE,
supply: BASE,
lastUpdate: Time.currentTime()
});
}
/*
* Convert a principal amount to a token amount given an index.
*/
function parToWei(
Types.Par memory input,
Index memory index
)
internal
pure
returns (Types.Wei memory)
{
uint256 inputValue = uint256(input.value);
if (input.sign) {
return Types.Wei({
sign: true,
value: inputValue.getPartialRoundHalfUp(index.supply, BASE)
});
} else {
return Types.Wei({
sign: false,
value: inputValue.getPartialRoundUp(index.borrow, BASE)
});
}
}
/*
* Convert a token amount to a principal amount given an index.
*/
function weiToPar(
Types.Wei memory input,
Index memory index
)
internal
pure
returns (Types.Par memory)
{
if (input.sign) {
return Types.Par({
sign: true,
value: input.value.getPartialRoundHalfUp(BASE, index.supply).to128()
});
} else {
return Types.Par({
sign: false,
value: input.value.getPartialRoundUp(BASE, index.borrow).to128()
});
}
}
/*
* Convert the total supply and borrow principal amounts of a market to total supply and borrow
* token amounts.
*/
function totalParToWei(
Types.TotalPar memory totalPar,
Index memory index
)
internal
pure
returns (Types.Wei memory, Types.Wei memory)
{
Types.Par memory supplyPar = Types.Par({
sign: true,
value: totalPar.supply
});
Types.Par memory borrowPar = Types.Par({
sign: false,
value: totalPar.borrow
});
Types.Wei memory supplyWei = parToWei(supplyPar, index);
Types.Wei memory borrowWei = parToWei(borrowPar, index);
return (supplyWei, borrowWei);
}
}
// File: contracts/protocol/interfaces/IInterestSetter.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title IInterestSetter
* @author dYdX
*
* Interface that Interest Setters for DolomiteMargin must implement in order to report interest rates.
*/
interface IInterestSetter {
// ============ Public Functions ============
/**
* Get the interest rate of a token given some borrowed and supplied amounts
*
* @param token The address of the ERC20 token for the market
* @param borrowWei The total borrowed token amount for the market
* @param supplyWei The total supplied token amount for the market
* @return The interest rate per second
*/
function getInterestRate(
address token,
uint256 borrowWei,
uint256 supplyWei
)
external
view
returns (Interest.Rate memory);
}
// File: contracts/protocol/lib/Monetary.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title Monetary
* @author dYdX
*
* Library for types involving money
*/
library Monetary {
/*
* The price of a base-unit of an asset. Has `36 - token.decimals` decimals
*/
struct Price {
uint256 value;
}
/*
* Total value of an some amount of an asset. Equal to (price * amount). Has 36 decimals.
*/
struct Value {
uint256 value;
}
}
// File: contracts/protocol/interfaces/IPriceOracle.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title IPriceOracle
* @author dYdX
*
* Interface that Price Oracles for DolomiteMargin must implement in order to report prices.
*/
contract IPriceOracle {
// ============ Constants ============
uint256 public constant ONE_DOLLAR = 10 ** 36;
// ============ Public Functions ============
/**
* Get the price of a token
*
* @param token The ERC20 token address of the market
* @return The USD price of a base unit of the token, then multiplied by 10^36.
* So a USD-stable coin with 18 decimal places would return 10^18.
* This is the price of the base unit rather than the price of a "human-readable"
* token amount. Every ERC20 may have a different number of decimals.
*/
function getPrice(
address token
)
public
view
returns (Monetary.Price memory);
}
// File: contracts/protocol/lib/Cache.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title Cache
* @author dYdX
*
* Library for caching information about markets
*/
library Cache {
// ============ Constants ============
bytes32 internal constant FILE = "Cache";
uint internal constant ONE = 1;
uint256 internal constant MAX_UINT_BITS = 256;
// ============ Structs ============
struct MarketInfo {
uint marketId;
address token;
bool isClosing;
uint128 borrowPar;
Monetary.Price price;
}
struct MarketCache {
MarketInfo[] markets;
uint256[] marketBitmaps;
uint256 marketsLength;
}
// ============ Setter Functions ============
/**
* Initialize an empty cache for some given number of total markets.
*/
function create(
uint256 numMarkets
)
internal
pure
returns (MarketCache memory)
{
return MarketCache({
markets: new MarketInfo[](0),
marketBitmaps: new uint[]((numMarkets / MAX_UINT_BITS) + ONE),
marketsLength: 0
});
}
// ============ Getter Functions ============
function getNumMarkets(
MarketCache memory cache
)
internal
pure
returns (uint256)
{
return cache.markets.length;
}
function hasMarket(
MarketCache memory cache,
uint256 marketId
)
internal
pure
returns (bool)
{
uint bucketIndex = marketId / MAX_UINT_BITS;
uint indexFromRight = marketId % MAX_UINT_BITS;
uint bit = cache.marketBitmaps[bucketIndex] & (ONE << indexFromRight);
return bit > 0;
}
function get(
MarketCache memory cache,
uint256 marketId
)
internal
pure
returns (MarketInfo memory)
{
Require.that(
cache.markets.length > 0,
FILE,
"not initialized"
);
return _getInternal(
cache.markets,
0,
cache.marketsLength,
marketId
);
}
function set(
MarketCache memory cache,
uint256 marketId
)
internal
pure
{
// Devs should not be able to call this function once the `markets` array has been initialized (non-zero length)
Require.that(
cache.markets.length == 0,
FILE,
"already initialized"
);
uint bucketIndex = marketId / MAX_UINT_BITS;
uint indexFromRight = marketId % MAX_UINT_BITS;
cache.marketBitmaps[bucketIndex] |= (ONE << indexFromRight);
cache.marketsLength += 1;
}
function getAtIndex(
MarketCache memory cache,
uint256 index
)
internal
pure
returns (MarketInfo memory)
{
Require.that(
index < cache.markets.length,
FILE,
"invalid index",
index,
cache.markets.length
);
return cache.markets[index];
}
// solium-disable security/no-assign-params
function getLeastSignificantBit(uint256 x) internal pure returns (uint) {
// gas usage peaks at 350 per call
uint lsb = 255;
if (x & uint128(-1) > 0) {
lsb -= 128;
} else {
x >>= 128;
}
if (x & uint64(-1) > 0) {
lsb -= 64;
} else {
x >>= 64;
}
if (x & uint32(-1) > 0) {
lsb -= 32;
} else {
x >>= 32;
}
if (x & uint16(-1) > 0) {
lsb -= 16;
} else {
x >>= 16;
}
if (x & uint8(-1) > 0) {
lsb -= 8;
} else {
x >>= 8;
}
if (x & 0xf > 0) {
lsb -= 4;
} else {
x >>= 4;
}
if (x & 0x3 > 0) {
lsb -= 2;
} else {
x >>= 2;
}
if (x & 0x1 > 0) {
lsb -= 1;
}
// solium-enable security/no-assign-params
return lsb;
}
// ============ Private Functions ============
function _getInternal(
MarketInfo[] memory data,
uint beginInclusive,
uint endExclusive,
uint marketId
) private pure returns (MarketInfo memory) {
uint len = endExclusive - beginInclusive;
if (len == 0 || (len == ONE && data[beginInclusive].marketId != marketId)) {
revert("Cache: item not found");
}
uint mid = beginInclusive + len / 2;
uint midMarketId = data[mid].marketId;
if (marketId < midMarketId) {
return _getInternal(
data,
beginInclusive,
mid,
marketId
);
} else if (marketId > midMarketId) {
return _getInternal(
data,
mid + 1,
endExclusive,
marketId
);
} else {
return data[mid];
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/protocol/interfaces/IERC20Detailed.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title IERC20
* @author dYdX
*
* Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so
* that we don't automatically revert when calling non-compliant tokens that have no return value for
* transfer(), transferFrom(), or approve().
*/
contract IERC20Detailed is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/protocol/lib/Token.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title Token
* @author dYdX
*
* This library contains basic functions for interacting with ERC20 tokens. Modified to work with
* tokens that don't adhere strictly to the ERC20 standard (for example tokens that don't return a
* boolean value on success).
*/
library Token {
// ============ Library Functions ============
function transfer(
address token,
address to,
uint256 amount
)
internal
{
if (amount == 0 || to == address(this)) {
return;
}
_callOptionalReturn(
token,
abi.encodeWithSelector(IERC20Detailed(token).transfer.selector, to, amount),
"Token: transfer failed"
);
}
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
internal
{
if (amount == 0 || to == from) {
return;
}
// solium-disable arg-overflow
_callOptionalReturn(
token,
abi.encodeWithSelector(IERC20Detailed(token).transferFrom.selector, from, to, amount),
"Token: transferFrom failed"
);
// solium-enable arg-overflow
}
// ============ Private Functions ============
function _callOptionalReturn(address token, bytes memory data, string memory error) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to contain contract code. Not needed since tokens are manually added
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solium-disable-next-line security/no-low-level-calls
(bool success, bytes memory returnData) = token.call(data);
require(success, error);
if (returnData.length > 0) {
// Return data is optional
require(abi.decode(returnData, (bool)), error);
}
}
}
// File: contracts/protocol/lib/Storage.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title Storage
* @author dYdX
*
* Functions for reading, writing, and verifying state in DolomiteMargin
*/
library Storage {
using Cache for Cache.MarketCache;
using Storage for Storage.State;
using Math for uint256;
using Types for Types.Par;
using Types for Types.Wei;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.Set;
// ============ Constants ============
bytes32 internal constant FILE = "Storage";
uint256 internal constant ONE = 1;
uint256 internal constant MAX_UINT_BITS = 256;
// ============ Structs ============
// All information necessary for tracking a market
struct Market {
// Contract address of the associated ERC20 token
address token;
// Whether additional borrows are allowed for this market
bool isClosing;
// Whether this market can be removed and its ID can be recycled and reused
bool isRecyclable;
// Total aggregated supply and borrow amount of the entire market
Types.TotalPar totalPar;
// Interest index of the market
Interest.Index index;
// Contract address of the price oracle for this market
IPriceOracle priceOracle;
// Contract address of the interest setter for this market
IInterestSetter interestSetter;
// Multiplier on the marginRatio for this market, IE 5% (0.05 * 1e18). This number increases the market's
// required collateralization by: reducing the user's supplied value (in terms of dollars) for this market and
// increasing its borrowed value. This is done through the following operation:
// `suppliedWei = suppliedWei + (assetValueForThisMarket / (1 + marginPremium))`
// This number increases the user's borrowed wei by multiplying it by:
// `borrowedWei = borrowedWei + (assetValueForThisMarket * (1 + marginPremium))`
Decimal.D256 marginPremium;
// Multiplier on the liquidationSpread for this market, IE 20% (0.2 * 1e18). This number increases the
// `liquidationSpread` using the following formula:
// `liquidationSpread = liquidationSpread * (1 + spreadPremium)`
// NOTE: This formula is applied up to two times - one for each market whose spreadPremium is greater than 0
// (when performing a liquidation between two markets)
Decimal.D256 spreadPremium;
}
// The global risk parameters that govern the health and security of the system
struct RiskParams {
// Required ratio of over-collateralization
Decimal.D256 marginRatio;
// Percentage penalty incurred by liquidated accounts
Decimal.D256 liquidationSpread;
// Percentage of the borrower's interest fee that gets passed to the suppliers
Decimal.D256 earningsRate;
// The minimum absolute borrow value of an account
// There must be sufficient incentivize to liquidate undercollateralized accounts
Monetary.Value minBorrowedValue;
}
// The maximum RiskParam values that can be set
struct RiskLimits {
// The highest that the ratio can be for liquidating under-water accounts
uint64 marginRatioMax;
// The highest that the liquidation rewards can be when a liquidator liquidates an account
uint64 liquidationSpreadMax;
// The highest that the supply APR can be for a market, as a proportion of the borrow rate. Meaning, a rate of
// 100% (1e18) would give suppliers all of the interest that borrowers are paying. A rate of 90% would give
// suppliers 90% of the interest that borrowers pay.
uint64 earningsRateMax;
uint64 marginPremiumMax;
uint64 spreadPremiumMax;
uint128 minBorrowedValueMax;
}
// The entire storage state of DolomiteMargin
struct State {
// number of markets
uint256 numMarkets;
// marketId => Market
mapping (uint256 => Market) markets;
mapping (address => uint256) tokenToMarketId;
mapping(uint256 => uint256) recycledMarketIds;
// owner => account number => Account
mapping (address => mapping (uint256 => Account.Storage)) accounts;
// Addresses that can control other users accounts
mapping (address => mapping (address => bool)) operators;
// Addresses that can control all users accounts
mapping (address => bool) globalOperators;
// mutable risk parameters of the system
RiskParams riskParams;
// immutable risk limits of the system
RiskLimits riskLimits;
}
// ============ Functions ============
function getToken(
Storage.State storage state,
uint256 marketId
)
internal
view
returns (address)
{
return state.markets[marketId].token;
}
function getTotalPar(
Storage.State storage state,
uint256 marketId
)
internal
view
returns (Types.TotalPar memory)
{
return state.markets[marketId].totalPar;
}
function getIndex(
Storage.State storage state,
uint256 marketId
)
internal
view
returns (Interest.Index memory)
{
return state.markets[marketId].index;
}
function getNumExcessTokens(
Storage.State storage state,
uint256 marketId
)
internal
view
returns (Types.Wei memory)
{
Interest.Index memory index = state.getIndex(marketId);
Types.TotalPar memory totalPar = state.getTotalPar(marketId);
address token = state.getToken(marketId);
Types.Wei memory balanceWei = Types.Wei({
sign: true,
value: IERC20Detailed(token).balanceOf(address(this))
});
(
Types.Wei memory supplyWei,
Types.Wei memory borrowWei
) = Interest.totalParToWei(totalPar, index);
// borrowWei is negative, so subtracting it makes the value more positive
return balanceWei.sub(borrowWei).sub(supplyWei);
}
function getStatus(
Storage.State storage state,
Account.Info memory account
)
internal
view
returns (Account.Status)
{
return state.accounts[account.owner][account.number].status;
}
function getPar(
Storage.State storage state,
Account.Info memory account,
uint256 marketId
)
internal
view
returns (Types.Par memory)
{
return state.accounts[account.owner][account.number].balances[marketId];
}
function getWei(
Storage.State storage state,
Account.Info memory account,
uint256 marketId
)
internal
view
returns (Types.Wei memory)
{
Types.Par memory par = state.getPar(account, marketId);
if (par.isZero()) {
return Types.zeroWei();
}
Interest.Index memory index = state.getIndex(marketId);
return Interest.parToWei(par, index);
}
function getMarketsWithBalancesSet(
Storage.State storage state,
Account.Info memory account
)
internal
view
returns (EnumerableSet.Set storage)
{
return state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet;
}
function getMarketsWithBalances(
Storage.State storage state,
Account.Info memory account
)
internal
view
returns (uint256[] memory)
{
return state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.values();
}
function getNumberOfMarketsWithBorrow(
Storage.State storage state,
Account.Info memory account
)
internal
view
returns (uint256)
{
return state.accounts[account.owner][account.number].numberOfMarketsWithBorrow;
}
function getLiquidationSpreadForPair(
Storage.State storage state,
uint256 heldMarketId,
uint256 owedMarketId
)
internal
view
returns (Decimal.D256 memory)
{
uint256 result = state.riskParams.liquidationSpread.value;
result = Decimal.mul(result, Decimal.onePlus(state.markets[heldMarketId].spreadPremium));
result = Decimal.mul(result, Decimal.onePlus(state.markets[owedMarketId].spreadPremium));
return Decimal.D256({
value: result
});
}
function fetchNewIndex(
Storage.State storage state,
uint256 marketId,
Interest.Index memory index
)
internal
view
returns (Interest.Index memory)
{
Interest.Rate memory rate = state.fetchInterestRate(marketId, index);
return Interest.calculateNewIndex(
index,
rate,
state.getTotalPar(marketId),
state.riskParams.earningsRate
);
}
function fetchInterestRate(
Storage.State storage state,
uint256 marketId,
Interest.Index memory index
)
internal
view
returns (Interest.Rate memory)
{
Types.TotalPar memory totalPar = state.getTotalPar(marketId);
(
Types.Wei memory supplyWei,
Types.Wei memory borrowWei
) = Interest.totalParToWei(totalPar, index);
Interest.Rate memory rate = state.markets[marketId].interestSetter.getInterestRate(
state.getToken(marketId),
borrowWei.value,
supplyWei.value
);
return rate;
}
function fetchPrice(
Storage.State storage state,
uint256 marketId,
address token
)
internal
view
returns (Monetary.Price memory)
{
IPriceOracle oracle = IPriceOracle(state.markets[marketId].priceOracle);
Monetary.Price memory price = oracle.getPrice(token);
Require.that(
price.value != 0,
FILE,
"Price cannot be zero",
marketId
);
return price;
}
function getAccountValues(
Storage.State storage state,
Account.Info memory account,
Cache.MarketCache memory cache,
bool adjustForLiquidity
)
internal
view
returns (Monetary.Value memory, Monetary.Value memory)
{
Monetary.Value memory supplyValue;
Monetary.Value memory borrowValue;
uint256 numMarkets = cache.getNumMarkets();
for (uint256 i = 0; i < numMarkets; i++) {
Types.Wei memory userWei = state.getWei(account, cache.getAtIndex(i).marketId);
if (userWei.isZero()) {
continue;
}
uint256 assetValue = userWei.value.mul(cache.getAtIndex(i).price.value);
Decimal.D256 memory adjust = Decimal.one();
if (adjustForLiquidity) {
adjust = Decimal.onePlus(state.markets[cache.getAtIndex(i).marketId].marginPremium);
}
if (userWei.sign) {
supplyValue.value = supplyValue.value.add(Decimal.div(assetValue, adjust));
} else {
borrowValue.value = borrowValue.value.add(Decimal.mul(assetValue, adjust));
}
}
return (supplyValue, borrowValue);
}
function isCollateralized(
Storage.State storage state,
Account.Info memory account,
Cache.MarketCache memory cache,
bool requireMinBorrow
)
internal
view
returns (bool)
{
if (state.getNumberOfMarketsWithBorrow(account) == 0) {
// The user does not have a balance with a borrow amount, so they must be collateralized
return true;
}
// get account values (adjusted for liquidity)
(
Monetary.Value memory supplyValue,
Monetary.Value memory borrowValue
) = state.getAccountValues(account, cache, /* adjustForLiquidity = */ true);
if (borrowValue.value == 0) {
return true;
}
if (requireMinBorrow) {
Require.that(
borrowValue.value >= state.riskParams.minBorrowedValue.value,
FILE,
"Borrow value too low",
account.owner,
account.number
);
}
uint256 requiredMargin = Decimal.mul(borrowValue.value, state.riskParams.marginRatio);
return supplyValue.value >= borrowValue.value.add(requiredMargin);
}
function isGlobalOperator(
Storage.State storage state,
address operator
)
internal
view
returns (bool)
{
return state.globalOperators[operator];
}
function isLocalOperator(
Storage.State storage state,
address owner,
address operator
)
internal
view
returns (bool)
{
return state.operators[owner][operator];
}
function requireIsGlobalOperator(
Storage.State storage state,
address operator
)
internal
view
{
bool isValidOperator = state.isGlobalOperator(operator);
Require.that(
isValidOperator,
FILE,
"Unpermissioned global operator",
operator
);
}
function requireIsOperator(
Storage.State storage state,
Account.Info memory account,
address operator
)
internal
view
{
bool isValidOperator =
operator == account.owner
|| state.isGlobalOperator(operator)
|| state.isLocalOperator(account.owner, operator);
Require.that(
isValidOperator,
FILE,
"Unpermissioned operator",
operator
);
}
/**
* Determine and set an account's balance based on the intended balance change. Return the
* equivalent amount in wei
*/
function getNewParAndDeltaWei(
Storage.State storage state,
Account.Info memory account,
uint256 marketId,
Types.AssetAmount memory amount
)
internal
view
returns (Types.Par memory, Types.Wei memory)
{
Types.Par memory oldPar = state.getPar(account, marketId);
if (amount.value == 0 && amount.ref == Types.AssetReference.Delta) {
return (oldPar, Types.zeroWei());
}
Interest.Index memory index = state.getIndex(marketId);
Types.Wei memory oldWei = Interest.parToWei(oldPar, index);
Types.Par memory newPar;
Types.Wei memory deltaWei;
if (amount.denomination == Types.AssetDenomination.Wei) {
deltaWei = Types.Wei({
sign: amount.sign,
value: amount.value
});
if (amount.ref == Types.AssetReference.Target) {
deltaWei = deltaWei.sub(oldWei);
}
newPar = Interest.weiToPar(oldWei.add(deltaWei), index);
} else { // AssetDenomination.Par
newPar = Types.Par({
sign: amount.sign,
value: amount.value.to128()
});
if (amount.ref == Types.AssetReference.Delta) {
newPar = oldPar.add(newPar);
}
deltaWei = Interest.parToWei(newPar, index).sub(oldWei);
}
return (newPar, deltaWei);
}
function getNewParAndDeltaWeiForLiquidation(
Storage.State storage state,
Account.Info memory account,
uint256 marketId,
Types.AssetAmount memory amount
)
internal
view
returns (Types.Par memory, Types.Wei memory)
{
Types.Par memory oldPar = state.getPar(account, marketId);
Require.that(
!oldPar.isPositive(),
FILE,
"Owed balance cannot be positive",
account.owner,
account.number
);
(
Types.Par memory newPar,
Types.Wei memory deltaWei
) = state.getNewParAndDeltaWei(
account,
marketId,
amount
);
// if attempting to over-repay the owed asset, bound it by the maximum
if (newPar.isPositive()) {
newPar = Types.zeroPar();
deltaWei = state.getWei(account, marketId).negative();
}
Require.that(
!deltaWei.isNegative() && oldPar.value >= newPar.value,
FILE,
"Owed balance cannot increase",
account.owner,
account.number
);
// if not paying back enough wei to repay any par, then bound wei to zero
if (oldPar.equals(newPar)) {
deltaWei = Types.zeroWei();
}
return (newPar, deltaWei);
}
function isVaporizable(
Storage.State storage state,
Account.Info memory account,
Cache.MarketCache memory cache
)
internal
view
returns (bool)
{
bool hasNegative = false;
uint256 numMarkets = cache.getNumMarkets();
for (uint256 i = 0; i < numMarkets; i++) {
Types.Par memory par = state.getPar(account, cache.getAtIndex(i).marketId);
if (par.isZero()) {
continue;
} else if (par.sign) {
return false;
} else {
hasNegative = true;
}
}
return hasNegative;
}
// =============== Setter Functions ===============
function updateIndex(
Storage.State storage state,
uint256 marketId
)
internal
returns (Interest.Index memory)
{
Interest.Index memory index = state.getIndex(marketId);
if (index.lastUpdate == Time.currentTime()) {
return index;
}
return state.markets[marketId].index = state.fetchNewIndex(marketId, index);
}
function setStatus(
Storage.State storage state,
Account.Info memory account,
Account.Status status
)
internal
{
state.accounts[account.owner][account.number].status = status;
}
function setPar(
Storage.State storage state,
Account.Info memory account,
uint256 marketId,
Types.Par memory newPar
)
internal
{
Types.Par memory oldPar = state.getPar(account, marketId);
if (Types.equals(oldPar, newPar)) {
// GUARD statement
return;
}
// updateTotalPar
Types.TotalPar memory totalPar = state.getTotalPar(marketId);
// roll-back oldPar
if (oldPar.sign) {
totalPar.supply = uint256(totalPar.supply).sub(oldPar.value).to128();
} else {
totalPar.borrow = uint256(totalPar.borrow).sub(oldPar.value).to128();
}
// roll-forward newPar
if (newPar.sign) {
totalPar.supply = uint256(totalPar.supply).add(newPar.value).to128();
} else {
totalPar.borrow = uint256(totalPar.borrow).add(newPar.value).to128();
}
if (oldPar.isLessThanZero() && newPar.isGreaterThanOrEqualToZero()) {
// user went from borrowing to repaying or positive
state.accounts[account.owner][account.number].numberOfMarketsWithBorrow -= 1;
} else if (oldPar.isGreaterThanOrEqualToZero() && newPar.isLessThanZero()) {
// user went from zero or positive to borrowing
state.accounts[account.owner][account.number].numberOfMarketsWithBorrow += 1;
}
if (newPar.isZero() && (!oldPar.isZero())) {
// User went from a non-zero balance to zero. Remove the market from the set.
state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.remove(marketId);
} else if ((!newPar.isZero()) && oldPar.isZero()) {
// User went from zero to non-zero. Add the market to the set.
state.accounts[account.owner][account.number].marketsWithNonZeroBalanceSet.add(marketId);
}
state.markets[marketId].totalPar = totalPar;
state.accounts[account.owner][account.number].balances[marketId] = newPar;
}
/**
* Determine and set an account's balance based on a change in wei
*/
function setParFromDeltaWei(
Storage.State storage state,
Account.Info memory account,
uint256 marketId,
Types.Wei memory deltaWei
)
internal
{
if (deltaWei.isZero()) {
return;
}
Interest.Index memory index = state.getIndex(marketId);
Types.Wei memory oldWei = state.getWei(account, marketId);
Types.Wei memory newWei = oldWei.add(deltaWei);
Types.Par memory newPar = Interest.weiToPar(newWei, index);
state.setPar(
account,
marketId,
newPar
);
}
function initializeCache(
Storage.State storage state,
Cache.MarketCache memory cache
) internal view {
cache.markets = new Cache.MarketInfo[](cache.marketsLength);
uint counter = 0;
// Really neat byproduct of iterating through a bitmap using the least significant bit, where each set flag
// represents the marketId, --> the initialized `cache.markets` array is sorted in O(n)!!!!!!
// Meaning, this function call is O(n) where `n` is the number of markets in the cache
for (uint i = 0; i < cache.marketBitmaps.length; i++) {
uint bitmap = cache.marketBitmaps[i];
while (bitmap != 0) {
uint nextSetBit = Cache.getLeastSignificantBit(bitmap);
uint marketId = (MAX_UINT_BITS * i) + nextSetBit;
address token = state.getToken(marketId);
if (state.markets[marketId].isClosing) {
cache.markets[counter++] = Cache.MarketInfo({
marketId: marketId,
token: token,
isClosing: true,
borrowPar: state.getTotalPar(marketId).borrow,
price: state.fetchPrice(marketId, token)
});
} else {
// don't need the borrowPar if the market is not closing
cache.markets[counter++] = Cache.MarketInfo({
marketId: marketId,
token: token,
isClosing: false,
borrowPar: 0,
price: state.fetchPrice(marketId, token)
});
}
// unset the set bit
bitmap = bitmap - (ONE << nextSetBit);
}
if (counter == cache.marketsLength) {
break;
}
}
Require.that(
cache.marketsLength == counter,
FILE,
"cache initialized improperly",
cache.marketsLength,
cache.markets.length
);
}
}
// File: contracts/protocol/interfaces/IDolomiteMargin.sol
/*
Copyright 2021 Dolomite.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity >=0.5.0;
interface IDolomiteMargin {
// ============ Getters for Markets ============
/**
* Get the ERC20 token address for a market.
*
* @param token The token to query
* @return The token's marketId if the token is valid
*/
function getMarketIdByTokenAddress(
address token
) external view returns (uint256);
/**
* Get the ERC20 token address for a market.
*
* @param marketId The market to query
* @return The token address
*/
function getMarketTokenAddress(
uint256 marketId
) external view returns (address);
/**
* Return true if a particular market is in closing mode. Additional borrows cannot be taken
* from a market that is closing.
*
* @param marketId The market to query
* @return True if the market is closing
*/
function getMarketIsClosing(
uint256 marketId
)
external
view
returns (bool);
/**
* Get the price of the token for a market.
*
* @param marketId The market to query
* @return The price of each atomic unit of the token
*/
function getMarketPrice(
uint256 marketId
) external view returns (Monetary.Price memory);
/**
* Get the total number of markets.
*
* @return The number of markets
*/
function getNumMarkets() external view returns (uint256);
/**
* Get the total principal amounts (borrowed and supplied) for a market.
*
* @param marketId The market to query
* @return The total principal amounts
*/
function getMarketTotalPar(
uint256 marketId
) external view returns (Types.TotalPar memory);
/**
* Get the most recently cached interest index for a market.
*
* @param marketId The market to query
* @return The most recent index
*/
function getMarketCachedIndex(
uint256 marketId
) external view returns (Interest.Index memory);
/**
* Get the interest index for a market if it were to be updated right now.
*
* @param marketId The market to query
* @return The estimated current index
*/
function getMarketCurrentIndex(
uint256 marketId
) external view returns (Interest.Index memory);
/**
* Get the price oracle address for a market.
*
* @param marketId The market to query
* @return The price oracle address
*/
function getMarketPriceOracle(
uint256 marketId
) external view returns (IPriceOracle);
/**
* Get the interest-setter address for a market.
*
* @param marketId The market to query
* @return The interest-setter address
*/
function getMarketInterestSetter(
uint256 marketId
) external view returns (IInterestSetter);
/**
* Get the margin premium for a market. A margin premium makes it so that any positions that
* include the market require a higher collateralization to avoid being liquidated.
*
* @param marketId The market to query
* @return The market's margin premium
*/
function getMarketMarginPremium(
uint256 marketId
) external view returns (Decimal.D256 memory);
/**
* Get the spread premium for a market. A spread premium makes it so that any liquidations
* that include the market have a higher spread than the global default.
*
* @param marketId The market to query
* @return The market's spread premium
*/
function getMarketSpreadPremium(
uint256 marketId
) external view returns (Decimal.D256 memory);
/**
* Return true if this market can be removed and its ID can be recycled and reused
*
* @param marketId The market to query
* @return True if the market is recyclable
*/
function getMarketIsRecyclable(
uint256 marketId
) external view returns (bool);
/**
* Gets the recyclable markets, up to `n` length. If `n` is greater than the length of the list, 0's are returned
* for the empty slots.
*
* @param n The number of markets to get, bounded by the linked list being smaller than `n`
* @return The list of recyclable markets, in the same order held by the linked list
*/
function getRecyclableMarkets(
uint256 n
) external view returns (uint[] memory);
/**
* Get the current borrower interest rate for a market.
*
* @param marketId The market to query
* @return The current interest rate
*/
function getMarketInterestRate(
uint256 marketId
) external view returns (Interest.Rate memory);
/**
* Get basic information about a particular market.
*
* @param marketId The market to query
* @return A Storage.Market struct with the current state of the market
*/
function getMarket(
uint256 marketId
) external view returns (Storage.Market memory);
/**
* Get comprehensive information about a particular market.
*
* @param marketId The market to query
* @return A tuple containing the values:
* - A Storage.Market struct with the current state of the market
* - The current estimated interest index
* - The current token price
* - The current market interest rate
*/
function getMarketWithInfo(
uint256 marketId
)
external
view
returns (
Storage.Market memory,
Interest.Index memory,
Monetary.Price memory,
Interest.Rate memory
);
/**
* Get the number of excess tokens for a market. The number of excess tokens is calculated by taking the current
* number of tokens held in DolomiteMargin, adding the number of tokens owed to DolomiteMargin by borrowers, and
* subtracting the number of tokens owed to suppliers by DolomiteMargin.
*
* @param marketId The market to query
* @return The number of excess tokens
*/
function getNumExcessTokens(
uint256 marketId
) external view returns (Types.Wei memory);
// ============ Getters for Accounts ============
/**
* Get the principal value for a particular account and market.
*
* @param account The account to query
* @param marketId The market to query
* @return The principal value
*/
function getAccountPar(
Account.Info calldata account,
uint256 marketId
) external view returns (Types.Par memory);
/**
* Get the principal value for a particular account and market, with no check the market is valid. Meaning, markets
* that don't exist return 0.
*
* @param account The account to query
* @param marketId The market to query
* @return The principal value
*/
function getAccountParNoMarketCheck(
Account.Info calldata account,
uint256 marketId
) external view returns (Types.Par memory);
/**
* Get the token balance for a particular account and market.
*
* @param account The account to query
* @param marketId The market to query
* @return The token amount
*/
function getAccountWei(
Account.Info calldata account,
uint256 marketId
) external view returns (Types.Wei memory);
/**
* Get the status of an account (Normal, Liquidating, or Vaporizing).
*
* @param account The account to query
* @return The account's status
*/
function getAccountStatus(
Account.Info calldata account
) external view returns (Account.Status);
/**
* Get a list of markets that have a non-zero balance for an account
*
* @param account The account to query
* @return The non-sorted marketIds with non-zero balance for the account.
*/
function getAccountMarketsWithNonZeroBalances(
Account.Info calldata account
) external view returns (uint256[] memory);
/**
* Get the number of markets with which an account has a negative balance.
*
* @param account The account to query
* @return The non-sorted marketIds with non-zero balance for the account.
*/
function getNumberOfMarketsWithBorrow(
Account.Info calldata account
) external view returns (uint256);
/**
* Get the total supplied and total borrowed value of an account.
*
* @param account The account to query
* @return The following values:
* - The supplied value of the account
* - The borrowed value of the account
*/
function getAccountValues(
Account.Info calldata account
) external view returns (Monetary.Value memory, Monetary.Value memory);
/**
* Get the total supplied and total borrowed values of an account adjusted by the marginPremium
* of each market. Supplied values are divided by (1 + marginPremium) for each market and
* borrowed values are multiplied by (1 + marginPremium) for each market. Comparing these
* adjusted values gives the margin-ratio of the account which will be compared to the global
* margin-ratio when determining if the account can be liquidated.
*
* @param account The account to query
* @return The following values:
* - The supplied value of the account (adjusted for marginPremium)
* - The borrowed value of the account (adjusted for marginPremium)
*/
function getAdjustedAccountValues(
Account.Info calldata account
) external view returns (Monetary.Value memory, Monetary.Value memory);
/**
* Get an account's summary for each market.
*
* @param account The account to query
* @return The following values:
* - The market IDs for each market
* - The ERC20 token address for each market
* - The account's principal value for each market
* - The account's (supplied or borrowed) number of tokens for each market
*/
function getAccountBalances(
Account.Info calldata account
) external view returns (uint[] memory, address[] memory, Types.Par[] memory, Types.Wei[] memory);
// ============ Getters for Account Permissions ============
/**
* Return true if a particular address is approved as an operator for an owner's accounts.
* Approved operators can act on the accounts of the owner as if it were the operator's own.
*
* @param owner The owner of the accounts
* @param operator The possible operator
* @return True if operator is approved for owner's accounts
*/
function getIsLocalOperator(
address owner,
address operator
) external view returns (bool);
/**
* Return true if a particular address is approved as a global operator. Such an address can
* act on any account as if it were the operator's own.
*
* @param operator The address to query
* @return True if operator is a global operator
*/
function getIsGlobalOperator(
address operator
) external view returns (bool);
// ============ Getters for Risk Params ============
/**
* Get the global minimum margin-ratio that every position must maintain to prevent being
* liquidated.
*
* @return The global margin-ratio
*/
function getMarginRatio() external view returns (Decimal.D256 memory);
/**
* Get the global liquidation spread. This is the spread between oracle prices that incentivizes
* the liquidation of risky positions.
*
* @return The global liquidation spread
*/
function getLiquidationSpread() external view returns (Decimal.D256 memory);
/**
* Get the adjusted liquidation spread for some market pair. This is equal to the global
* liquidation spread multiplied by (1 + spreadPremium) for each of the two markets.
*
* @param heldMarketId The market for which the account has collateral
* @param owedMarketId The market for which the account has borrowed tokens
* @return The adjusted liquidation spread
*/
function getLiquidationSpreadForPair(
uint256 heldMarketId,
uint256 owedMarketId
) external view returns (Decimal.D256 memory);
/**
* Get the global earnings-rate variable that determines what percentage of the interest paid
* by borrowers gets passed-on to suppliers.
*
* @return The global earnings rate
*/
function getEarningsRate() external view returns (Decimal.D256 memory);
/**
* Get the global minimum-borrow value which is the minimum value of any new borrow on DolomiteMargin.
*
* @return The global minimum borrow value
*/
function getMinBorrowedValue() external view returns (Monetary.Value memory);
/**
* Get all risk parameters in a single struct.
*
* @return All global risk parameters
*/
function getRiskParams() external view returns (Storage.RiskParams memory);
/**
* Get all risk parameter limits in a single struct. These are the maximum limits at which the
* risk parameters can be set by the admin of DolomiteMargin.
*
* @return All global risk parameter limits
*/
function getRiskLimits() external view returns (Storage.RiskLimits memory);
// ============ Write Functions ============
/**
* The main entry-point to DolomiteMargin that allows users and contracts to manage accounts.
* Take one or more actions on one or more accounts. The msg.sender must be the owner or
* operator of all accounts except for those being liquidated, vaporized, or traded with.
* One call to operate() is considered a singular "operation". Account collateralization is
* ensured only after the completion of the entire operation.
*
* @param accounts A list of all accounts that will be used in this operation. Cannot contain
* duplicates. In each action, the relevant account will be referred-to by its
* index in the list.
* @param actions An ordered list of all actions that will be taken in this operation. The
* actions will be processed in order.
*/
function operate(
Account.Info[] calldata accounts,
Actions.ActionArgs[] calldata actions
) external;
/**
* Approves/disapproves any number of operators. An operator is an external address that has the
* same permissions to manipulate an account as the owner of the account. Operators are simply
* addresses and therefore may either be externally-owned Ethereum accounts OR smart contracts.
*
* Operators are also able to act as AutoTrader contracts on behalf of the account owner if the
* operator is a smart contract and implements the IAutoTrader interface.
*
* @param args A list of OperatorArgs which have an address and a boolean. The boolean value
* denotes whether to approve (true) or revoke approval (false) for that address.
*/
function setOperators(
Types.OperatorArg[] calldata args
) external;
}
// File: contracts/external/helpers/OnlyDolomiteMargin.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title onlyDolomiteMargin
* @author dYdX
*
* Inheritable contract that restricts the calling of certain functions to DolomiteMargin only
*/
contract OnlyDolomiteMargin {
// ============ Constants ============
bytes32 constant FILE = "OnlyDolomiteMargin";
// ============ Storage ============
IDolomiteMargin public DOLOMITE_MARGIN;
// ============ Constructor ============
constructor (
address dolomiteMargin
)
public
{
DOLOMITE_MARGIN = IDolomiteMargin(dolomiteMargin);
}
// ============ Modifiers ============
modifier onlyDolomiteMargin(address from) {
Require.that(
from == address(DOLOMITE_MARGIN),
FILE,
"Only Dolomite can call function",
from
);
_;
}
}
// File: contracts/external/proxies/PayableProxy.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.7;
/**
* @title PayableProxy
* @author dYdX
*
* Contract for wrapping/unwrapping ETH before/after interacting with DolomiteMargin
*/
contract PayableProxy is OnlyDolomiteMargin, ReentrancyGuard {
// ============ Constants ============
bytes32 constant FILE = "PayableProxy";
// ============ Storage ============
WETH9 public WETH;
// ============ Constructor ============
constructor (
address dolomiteMargin,
address payable weth
)
public
OnlyDolomiteMargin(dolomiteMargin)
{
WETH = WETH9(weth);
WETH.approve(dolomiteMargin, uint256(-1));
}
// ============ Public Functions ============
/**
* Fallback function. Disallows ether to be sent to this contract without data except when
* unwrapping WETH.
*/
function ()
external
payable
{
require( // coverage-disable-line
msg.sender == address(WETH),
"Cannot receive ETH"
);
}
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions,
address payable sendEthTo
)
public
payable
nonReentrant
{
WETH9 weth = WETH;
// create WETH from ETH
if (msg.value != 0) {
weth.deposit.value(msg.value)();
}
// validate the input
for (uint256 i = 0; i < actions.length; i++) {
Actions.ActionArgs memory action = actions[i];
// Can only operate on accounts owned by msg.sender
address owner1 = accounts[action.accountId].owner;
Require.that(
owner1 == msg.sender,
FILE,
"Sender must be primary account",
owner1
);
// For a transfer both accounts must be owned by msg.sender
if (action.actionType == Actions.ActionType.Transfer) {
address owner2 = accounts[action.otherAccountId].owner;
Require.that(
owner2 == msg.sender,
FILE,
"Sender must be secondary account",
owner2
);
}
}
DOLOMITE_MARGIN.operate(accounts, actions);
// return all remaining WETH to the sendEthTo as ETH
uint256 remainingWeth = weth.balanceOf(address(this));
if (remainingWeth != 0) {
Require.that(
sendEthTo != address(0),
FILE,
"Must set sendEthTo"
);
weth.withdraw(remainingWeth);
sendEthTo.transfer(remainingWeth);
}
}
}
|
Convert a token amount to a principal amount given an index./
|
function weiToPar(
Types.Wei memory input,
Index memory index
)
internal
pure
returns (Types.Par memory)
{
if (input.sign) {
return Types.Par({
sign: true,
value: input.value.getPartialRoundHalfUp(BASE, index.supply).to128()
});
return Types.Par({
sign: false,
value: input.value.getPartialRoundUp(BASE, index.borrow).to128()
});
}
}
| 6,397,716 |
./full_match/1/0xB80ccEb6Fa958b52203604D7624F4Abdb4F373F4/sources/src/common/PremiumPriceOracle.sol
|
Sets rent prices for the specified node (can only be called by the node owner) _rentPrices The price array. Each element corresponds to a specific name length; names longer than the length of the array default to the price of the last element. Values are in base price units, equal to one attodollar (1e-18 dollar) each./
|
function setPrices(bytes32 node, uint256[] memory _rentPrices) public nodeOperator(node) {
require(block.timestamp - rentPricesUpdated[node] > 5 minutes);
rentPrices[node] = _rentPrices;
rentPricesUpdated[node] = block.timestamp;
emit RentPriceChanged(node, _rentPrices);
}
| 8,459,714 |
./full_match/137/0x11d455366ba5D590e7838c4CEcE9aCC95C567e46/sources/contracts/trove-factory.sol
|
check if the Trove guessed ICR matches and commits partial redemptios/
|
function commitPartRedeem(
RedemptionInfo memory _redInfo,
uint256 _maxRate,
uint256 _lastTroveCurrentICR,
address _lastTroveNewPositionHint
) internal returns (RedemptionInfo memory) {
ITrove currentRedemptionTrove = ITrove(_redInfo.currentTroveAddress);
uint256 currentFeeRatio = getRedemptionFeeRatio(_redInfo.currentTroveAddress) + feeRecipient.baseRate();
if (currentRedemptionTrove.collateralization() == _lastTroveCurrentICR && currentFeeRatio < _maxRate) {
uint256 maxLastRedeem = BONQMath.min(
getRedemptionAmount(currentFeeRatio, _redInfo.stableCoinLeft),
currentRedemptionTrove.netDebt()
);
(uint256 stblRed, uint256 colRed) = _redeemPartTrove(
msg.sender,
_redInfo.currentTroveAddress,
maxLastRedeem,
_lastTroveNewPositionHint
);
_redInfo.stableCoinRedeemed += stblRed;
uint256 newFee = getRedemptionFee(currentFeeRatio, stblRed);
_redInfo.feeAmount += newFee;
_redInfo.stableCoinLeft -= stblRed + newFee;
_redInfo.collateralRedeemed += colRed;
_redInfo.lastTroveRedeemed = _redInfo.currentTroveAddress;
}
return _redInfo;
}
| 4,722,886 |
/**
*Submitted for verification at Etherscan.io on 2022-02-04
*/
// Sources flattened with hardhat v2.6.1 https://hardhat.org
// File contracts/oz/0.8.0/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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File contracts/oz/0.8.0/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
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;
}
}
// File contracts/oz/0.8.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 `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/oz/0.8.0/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// 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);
}
}
}
}
// File contracts/oz/0.8.0/token/ERC20/utils/SafeERC20.sol
pragma solidity ^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 Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(
oldAllowance >= value,
"SafeERC20: decreased allowance below zero"
);
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata =
address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// File contracts/Curve/Curve_Registry_V3.sol
// ΓûêΓûêΓûêΓûêΓûêΓûêΓûêΓòùΓûæΓûêΓûêΓûêΓûêΓûêΓòùΓûæΓûêΓûêΓûêΓûêΓûêΓûêΓòùΓûæΓûêΓûêΓûêΓûêΓûêΓûêΓòùΓûæΓûêΓûêΓûêΓûêΓûêΓûêΓûêΓòùΓûêΓûêΓûêΓûêΓûêΓûêΓòùΓûæΓûæΓûæΓûæΓûêΓûêΓûêΓûêΓûêΓûêΓûêΓòùΓûêΓûêΓòù
// ΓòÜΓòÉΓòÉΓòÉΓòÉΓûêΓûêΓòæΓûêΓûêΓòöΓòÉΓòÉΓûêΓûêΓòùΓûêΓûêΓòöΓòÉΓòÉΓûêΓûêΓòùΓûêΓûêΓòöΓòÉΓòÉΓûêΓûêΓòùΓûêΓûêΓòöΓòÉΓòÉΓòÉΓòÉΓò¥ΓûêΓûêΓòöΓòÉΓòÉΓûêΓûêΓòùΓûæΓûæΓûæΓûêΓûêΓòöΓòÉΓòÉΓòÉΓòÉΓò¥ΓûêΓûêΓòæ
// ΓûæΓûæΓûêΓûêΓûêΓòöΓòÉΓò¥ΓûêΓûêΓûêΓûêΓûêΓûêΓûêΓòæΓûêΓûêΓûêΓûêΓûêΓûêΓòöΓò¥ΓûêΓûêΓûêΓûêΓûêΓûêΓòöΓò¥ΓûêΓûêΓûêΓûêΓûêΓòùΓûæΓûæΓûêΓûêΓûêΓûêΓûêΓûêΓòöΓò¥ΓûæΓûæΓûæΓûêΓûêΓûêΓûêΓûêΓòùΓûæΓûæΓûêΓûêΓòæ
// ΓûêΓûêΓòöΓòÉΓòÉΓò¥ΓûæΓûæΓûêΓûêΓòöΓòÉΓòÉΓûêΓûêΓòæΓûêΓûêΓòöΓòÉΓòÉΓòÉΓò¥ΓûæΓûêΓûêΓòöΓòÉΓòÉΓòÉΓò¥ΓûæΓûêΓûêΓòöΓòÉΓòÉΓò¥ΓûæΓûæΓûêΓûêΓòöΓòÉΓòÉΓûêΓûêΓòùΓûæΓûæΓûæΓûêΓûêΓòöΓòÉΓòÉΓò¥ΓûæΓûæΓûêΓûêΓòæ
// ΓûêΓûêΓûêΓûêΓûêΓûêΓûêΓòùΓûêΓûêΓòæΓûæΓûæΓûêΓûêΓòæΓûêΓûêΓòæΓûæΓûæΓûæΓûæΓûæΓûêΓûêΓòæΓûæΓûæΓûæΓûæΓûæΓûêΓûêΓûêΓûêΓûêΓûêΓûêΓòùΓûêΓûêΓòæΓûæΓûæΓûêΓûêΓòæΓûêΓûêΓòùΓûêΓûêΓòæΓûæΓûæΓûæΓûæΓûæΓûêΓûêΓòæ
// ΓòÜΓòÉΓòÉΓòÉΓòÉΓòÉΓòÉΓò¥ΓòÜΓòÉΓò¥ΓûæΓûæΓòÜΓòÉΓò¥ΓòÜΓòÉΓò¥ΓûæΓûæΓûæΓûæΓûæΓòÜΓòÉΓò¥ΓûæΓûæΓûæΓûæΓûæΓòÜΓòÉΓòÉΓòÉΓòÉΓòÉΓòÉΓò¥ΓòÜΓòÉΓò¥ΓûæΓûæΓòÜΓòÉΓò¥ΓòÜΓòÉΓò¥ΓòÜΓòÉΓò¥ΓûæΓûæΓûæΓûæΓûæΓòÜΓòÉΓò¥
// Copyright (C) 2022 zapper
// This program 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 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice Registry for Curve Pools with Utility functions.
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.0;
interface ICurveAddressProvider {
function get_registry() external view returns (address);
function get_address(uint256 _id) external view returns (address);
}
interface ICurveRegistry {
function get_pool_from_lp_token(address lpToken)
external
view
returns (address);
function get_lp_token(address swapAddress) external view returns (address);
function get_n_coins(address _pool)
external
view
returns (uint256[2] memory);
function get_coins(address _pool) external view returns (address[8] memory);
function get_underlying_coins(address _pool)
external
view
returns (address[8] memory);
}
interface ICurveCryptoRegistry {
function get_pool_from_lp_token(address lpToken)
external
view
returns (address);
function get_lp_token(address swapAddress) external view returns (address);
function get_n_coins(address _pool) external view returns (uint256);
function get_coins(address _pool) external view returns (address[8] memory);
}
interface ICurveFactoryRegistry {
function get_n_coins(address _pool) external view returns (uint256);
function get_coins(address _pool) external view returns (address[2] memory);
function get_underlying_coins(address _pool)
external
view
returns (address[8] memory);
}
interface ICurveV2Pool {
function price_oracle(uint256 k) external view returns (uint256);
}
contract Curve_Registry_V3 is Ownable {
using SafeERC20 for IERC20;
ICurveAddressProvider internal constant CurveAddressProvider =
ICurveAddressProvider(0x0000000022D53366457F9d5E68Ec105046FC4383);
ICurveRegistry public CurveRegistry;
ICurveFactoryRegistry public FactoryRegistry;
ICurveCryptoRegistry public CurveCryptoRegistry;
address internal constant wbtcToken =
0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
address internal constant sbtcCrvToken =
0x075b1bb99792c9E1041bA13afEf80C91a1e70fB3;
address internal constant ETHAddress =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
mapping(address => bool) public shouldAddUnderlying;
mapping(address => address) private depositAddresses;
constructor() {
CurveRegistry = ICurveRegistry(CurveAddressProvider.get_registry());
FactoryRegistry = ICurveFactoryRegistry(
CurveAddressProvider.get_address(3)
);
CurveCryptoRegistry = ICurveCryptoRegistry(
CurveAddressProvider.get_address(5)
);
// set mappings
depositAddresses[
0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51
] = 0xbBC81d23Ea2c3ec7e56D39296F0cbB648873a5d3;
depositAddresses[
0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56
] = 0xeB21209ae4C2c9FF2a86ACA31E123764A3B6Bc06;
depositAddresses[
0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C
] = 0xac795D2c97e60DF6a99ff1c814727302fD747a80;
depositAddresses[
0x06364f10B501e868329afBc005b3492902d6C763
] = 0xA50cCc70b6a011CffDdf45057E39679379187287;
depositAddresses[
0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27
] = 0xb6c057591E073249F2D9D88Ba59a46CFC9B59EdB;
depositAddresses[
0xA5407eAE9Ba41422680e2e00537571bcC53efBfD
] = 0xFCBa3E75865d2d561BE8D220616520c171F12851;
shouldAddUnderlying[0xDeBF20617708857ebe4F679508E7b7863a8A8EeE] = true;
shouldAddUnderlying[0xEB16Ae0052ed37f479f7fe63849198Df1765a733] = true;
shouldAddUnderlying[0x2dded6Da1BF5DBdF597C45fcFaa3194e53EcfeAF] = true;
}
/**
@notice Checks if the pool is an original (non-factory) pool
@param swapAddress Curve swap address for the pool
@return true if pool is a non-factory pool, false otherwise
*/
function isCurvePool(address swapAddress) public view returns (bool) {
if (CurveRegistry.get_lp_token(swapAddress) != address(0)) {
return true;
}
return false;
}
/**
@notice Checks if the pool is a factory pool
@param swapAddress Curve swap address for the pool
@return true if pool is a factory pool, false otherwise
*/
function isFactoryPool(address swapAddress) public view returns (bool) {
if (FactoryRegistry.get_coins(swapAddress)[0] != address(0)) {
return true;
}
return false;
}
/**
@notice Checks if the pool is a Crypto pool
@param swapAddress Curve swap address for the pool
@return true if pool is a crypto pool, false otherwise
*/
function isCryptoPool(address swapAddress) public view returns (bool) {
if (CurveCryptoRegistry.get_lp_token(swapAddress) != address(0)) {
return true;
}
return false;
}
/**
@notice Checks if the Pool is a metapool
@notice All factory pools are metapools but not all metapools
* are factory pools! (e.g. dusd)
@param swapAddress Curve swap address for the pool
@return true if the pool is a metapool, false otherwise
*/
function isMetaPool(address swapAddress) public view returns (bool) {
if (isCurvePool(swapAddress)) {
uint256[2] memory poolTokenCounts =
CurveRegistry.get_n_coins(swapAddress);
if (poolTokenCounts[0] == poolTokenCounts[1]) return false;
else return true;
}
if (isCryptoPool(swapAddress)) {
uint256 poolTokensCount =
CurveCryptoRegistry.get_n_coins(swapAddress);
address[8] memory poolTokens =
CurveCryptoRegistry.get_coins(swapAddress);
for (uint256 i = 0; i < poolTokensCount; i++) {
if (isCurvePool(poolTokens[i])) return true;
}
}
if (isFactoryPool(swapAddress)) return true;
return false;
}
/**
@notice Checks if the Pool is metapool of the Curve or Factory pool type
@notice All factory pools are metapools but not all metapools
* are factory pools! (e.g. dusd)
@param swapAddress Curve swap address for the pool
@return 1 if Meta Curve Pool
2 if Meta Factory Pool
0 otherwise
*/
function _isCurveFactoryMetaPool(address swapAddress)
internal
view
returns (uint256)
{
if (isCurvePool(swapAddress)) {
uint256[2] memory poolTokenCounts =
CurveRegistry.get_n_coins(swapAddress);
if (poolTokenCounts[0] == poolTokenCounts[1]) return 0;
else return 1;
}
if (isFactoryPool(swapAddress)) return 2;
return 0;
}
/**
@notice Checks if the pool is a Curve V2 pool
@param swapAddress Curve swap address for the pool
@return true if pool is a V2 pool, false otherwise
*/
function isV2Pool(address swapAddress) public view returns (bool) {
try ICurveV2Pool(swapAddress).price_oracle(0) {
return true;
} catch {
return false;
}
}
/**
@notice Gets the Curve pool deposit address
@notice The deposit address is used for pools with wrapped (c, y) tokens
@param swapAddress Curve swap address for the pool
@return depositAddress Curve pool deposit address or the swap address if not mapped
*/
function getDepositAddress(address swapAddress)
external
view
returns (address depositAddress)
{
depositAddress = depositAddresses[swapAddress];
if (depositAddress == address(0)) return swapAddress;
}
/**
@notice Gets the Curve pool swap address
@notice The token and swap address is the same for metapool/factory pools
@param tokenAddress Curve swap address for the pool
@return swapAddress Curve pool swap address or address(0) if pool doesnt exist
*/
function getSwapAddress(address tokenAddress)
external
view
returns (address swapAddress)
{
swapAddress = CurveRegistry.get_pool_from_lp_token(tokenAddress);
if (swapAddress != address(0)) {
return swapAddress;
}
swapAddress = CurveCryptoRegistry.get_pool_from_lp_token(tokenAddress);
if (swapAddress != address(0)) {
return swapAddress;
}
if (isFactoryPool(tokenAddress)) {
return tokenAddress;
}
return address(0);
}
/**
@notice Gets the Curve pool token address
@notice The token and swap address is the same for metapool/factory pools
@param swapAddress Curve swap address for the pool
@return tokenAddress Curve pool token address or address(0) if pool doesnt exist
*/
function getTokenAddress(address swapAddress)
external
view
returns (address tokenAddress)
{
tokenAddress = CurveRegistry.get_lp_token(swapAddress);
if (tokenAddress != address(0)) {
return tokenAddress;
}
tokenAddress = CurveCryptoRegistry.get_lp_token(swapAddress);
if (tokenAddress != address(0)) {
return tokenAddress;
}
if (isFactoryPool(swapAddress)) {
return swapAddress;
}
return address(0);
}
/**
@notice Gets the number of non-underlying tokens in a pool
@param swapAddress Curve swap address for the pool
@return number of underlying tokens in the pool
*/
function getNumTokens(address swapAddress) public view returns (uint256) {
if (isCurvePool(swapAddress)) {
return CurveRegistry.get_n_coins(swapAddress)[0];
} else if (isCryptoPool(swapAddress)) {
return CurveCryptoRegistry.get_n_coins(swapAddress);
} else {
return FactoryRegistry.get_n_coins(swapAddress);
}
}
/**
@notice Gets an array of underlying pool token addresses
@param swapAddress Curve swap address for the pool
@return poolTokens returns 4 element array containing the
* addresses of the pool tokens (0 address if pool contains < 4 tokens)
*/
function getPoolTokens(address swapAddress)
public
view
returns (address[4] memory poolTokens)
{
uint256 isCurveFactoryMetaPool = _isCurveFactoryMetaPool(swapAddress);
if (isCurveFactoryMetaPool == 1) {
address[8] memory poolUnderlyingCoins =
CurveRegistry.get_coins(swapAddress);
for (uint256 i = 0; i < 2; i++) {
poolTokens[i] = poolUnderlyingCoins[i];
}
} else if (isCurveFactoryMetaPool == 2) {
address[2] memory poolUnderlyingCoins =
FactoryRegistry.get_coins(swapAddress);
for (uint256 i = 0; i < 2; i++) {
poolTokens[i] = poolUnderlyingCoins[i];
}
} else if (isCryptoPool(swapAddress)) {
address[8] memory poolUnderlyingCoins =
CurveCryptoRegistry.get_coins(swapAddress);
for (uint256 i = 0; i < 4; i++) {
poolTokens[i] = poolUnderlyingCoins[i];
}
} else {
address[8] memory poolUnderlyingCoins;
if (isBtcPool(swapAddress)) {
poolUnderlyingCoins = CurveRegistry.get_coins(swapAddress);
} else {
poolUnderlyingCoins = CurveRegistry.get_underlying_coins(
swapAddress
);
}
for (uint256 i = 0; i < 4; i++) {
poolTokens[i] = poolUnderlyingCoins[i];
}
}
}
/**
@notice Checks if the Curve pool contains WBTC
@param swapAddress Curve swap address for the pool
@return true if the pool contains WBTC, false otherwise
*/
function isBtcPool(address swapAddress) public view returns (bool) {
address[8] memory poolTokens = CurveRegistry.get_coins(swapAddress);
for (uint256 i = 0; i < 4; i++) {
if (poolTokens[i] == wbtcToken || poolTokens[i] == sbtcCrvToken)
return true;
}
return false;
}
/**
@notice Checks if the Curve pool contains ETH
@param swapAddress Curve swap address for the pool
@return true if the pool contains ETH, false otherwise
*/
function isEthPool(address swapAddress) external view returns (bool) {
address[8] memory poolTokens = CurveRegistry.get_coins(swapAddress);
for (uint256 i = 0; i < 4; i++) {
if (poolTokens[i] == ETHAddress) {
return true;
}
}
return false;
}
/**
@notice Check if the pool contains the toToken
@param swapAddress Curve swap address for the pool
@param toToken contract address of the token
@return true if the pool contains the token, false otherwise
@return index of the token in the pool, 0 if pool does not contain the token
*/
function isUnderlyingToken(address swapAddress, address toToken)
external
view
returns (bool, uint256)
{
address[4] memory poolTokens = getPoolTokens(swapAddress);
for (uint256 i = 0; i < 4; i++) {
if (poolTokens[i] == address(0)) return (false, 0);
if (poolTokens[i] == toToken) return (true, i);
}
return (false, 0);
}
/**
@notice Updates to the latest Curve registry from the address provider
*/
function update_curve_registry() external onlyOwner {
address new_address = CurveAddressProvider.get_registry();
require(address(CurveRegistry) != new_address, "Already updated");
CurveRegistry = ICurveRegistry(new_address);
}
/**
@notice Updates to the latest Curve factory registry from the address provider
*/
function update_factory_registry() external onlyOwner {
address new_address = CurveAddressProvider.get_address(3);
require(address(FactoryRegistry) != new_address, "Already updated");
FactoryRegistry = ICurveFactoryRegistry(new_address);
}
/**
@notice Updates to the latest Curve crypto registry from the address provider
*/
function update_crypto_registry() external onlyOwner {
address new_address = CurveAddressProvider.get_address(5);
require(address(CurveCryptoRegistry) != new_address, "Already updated");
CurveCryptoRegistry = ICurveCryptoRegistry(new_address);
}
/**
@notice Add new pools which use the _use_underlying bool
@param swapAddresses Curve swap addresses for the pool
@param addUnderlying True if underlying tokens are always added
*/
function updateShouldAddUnderlying(
address[] calldata swapAddresses,
bool[] calldata addUnderlying
) external onlyOwner {
require(
swapAddresses.length == addUnderlying.length,
"Mismatched arrays"
);
for (uint256 i = 0; i < swapAddresses.length; i++) {
shouldAddUnderlying[swapAddresses[i]] = addUnderlying[i];
}
}
/**
@notice Add new pools which use uamounts for add_liquidity
@param swapAddresses Curve swap addresses to map from
@param _depositAddresses Curve deposit addresses to map to
*/
function updateDepositAddresses(
address[] calldata swapAddresses,
address[] calldata _depositAddresses
) external onlyOwner {
require(
swapAddresses.length == _depositAddresses.length,
"Mismatched arrays"
);
for (uint256 i = 0; i < swapAddresses.length; i++) {
depositAddresses[swapAddresses[i]] = _depositAddresses[i];
}
}
/**
//@notice Withdraw stuck tokens
*/
function withdrawTokens(address[] calldata tokens) external onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
uint256 qty;
if (tokens[i] == ETHAddress) {
qty = address(this).balance;
Address.sendValue(payable(owner()), qty);
} else {
qty = IERC20(tokens[i]).balanceOf(address(this));
IERC20(tokens[i]).safeTransfer(owner(), qty);
}
}
}
}
|
Withdraw stuck tokens/
|
function withdrawTokens(address[] calldata tokens) external onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
uint256 qty;
if (tokens[i] == ETHAddress) {
qty = address(this).balance;
Address.sendValue(payable(owner()), qty);
qty = IERC20(tokens[i]).balanceOf(address(this));
IERC20(tokens[i]).safeTransfer(owner(), qty);
}
}
}
| 7,840,694 |
./full_match/5/0xEad4BEBAB5E42Bd6019a39e66B374583bF1a9D3d/sources/project_/contracts/PinkWojak.sol
|
_mult = 10 means x1, 20 means x2
|
function setGameWinSellPenaltyMultiplier(uint256 _mult) external onlyOwner {
require(
(_totalTax * _mult) / 10 <= (PERCENT_DENOMENATOR * 49) / 100,
'total cannot be more than 49%'
);
gameWinSellPenaltyMultiplier = _mult;
}
| 1,915,017 |
pragma solidity ^0.5.12;
library SafeMath {
function MUL98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0)
return 0;
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV107(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0);
uint256 c = a / b;
return c;
}
function SUB705(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD235(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD157(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
contract ERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowed;
event TRANSFER731(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL787(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
uint256 internal _totalSupply;
function TOTALSUPPLY882() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF767(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE10(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER204(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER522(msg.sender, to, value);
return true;
}
function APPROVE277(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_allowed[msg.sender][spender] = value;
emit APPROVAL787(msg.sender, spender, value);
return true;
}
function TRANSFERFROM832(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER522(from, to, value);
_allowed[msg.sender][to] = _allowed[msg.sender][to].SUB705(value);
return true;
}
function _TRANSFER522(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB705(value);
_balances[to] = _balances[to].ADD235(value);
emit TRANSFER731(from, to, value);
}
}
contract ERC20Mintable is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function _MINT321(address to, uint256 amount) internal { //inject NONSTANDARD NAMING
_balances[to] = _balances[to].ADD235(amount);
_totalSupply = _totalSupply.ADD235(amount);
emit TRANSFER731(address(0), to, amount);
}
function _BURN441(address from, uint256 amount) internal { //inject NONSTANDARD NAMING
_balances[from] = _balances[from].SUB705(amount);
_totalSupply = _totalSupply.SUB705(amount);
emit TRANSFER731(from, address(0), amount);
}
}
// ----------- Aave ----------------
contract ILendingPoolAddressesProvider {
function GETLENDINGPOOL38() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLIMPL881(address _pool) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLCORE21() public view returns (address payable); //inject NONSTANDARD NAMING
function SETLENDINGPOOLCOREIMPL156(address _lendingPoolCore) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLCONFIGURATOR254() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLCONFIGURATORIMPL555(address _configurator) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLDATAPROVIDER61() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLDATAPROVIDERIMPL193(address _provider) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLPARAMETERSPROVIDER362() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLPARAMETERSPROVIDERIMPL978(address _parametersProvider) public; //inject NONSTANDARD NAMING
function GETTOKENDISTRIBUTOR827() public view returns (address); //inject NONSTANDARD NAMING
function SETTOKENDISTRIBUTOR348(address _tokenDistributor) public; //inject NONSTANDARD NAMING
function GETFEEPROVIDER168() public view returns (address); //inject NONSTANDARD NAMING
function SETFEEPROVIDERIMPL718(address _feeProvider) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLLIQUIDATIONMANAGER82() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLLIQUIDATIONMANAGER708(address _manager) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLMANAGER762() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLMANAGER882(address _lendingPoolManager) public; //inject NONSTANDARD NAMING
function GETPRICEORACLE485() public view returns (address); //inject NONSTANDARD NAMING
function SETPRICEORACLE428(address _priceOracle) public; //inject NONSTANDARD NAMING
function GETLENDINGRATEORACLE592() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGRATEORACLE655(address _lendingRateOracle) public; //inject NONSTANDARD NAMING
}
interface ILendingPool {
function ADDRESSESPROVIDER344() external view returns(address); //inject NONSTANDARD NAMING
function DEPOSIT818(address _reserve, uint256 _amount, uint16 _referralCode) external payable; //inject NONSTANDARD NAMING
function REDEEMUNDERLYING805(address _reserve, address _user, uint256 _amount) external; //inject NONSTANDARD NAMING
function BORROW264(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external; //inject NONSTANDARD NAMING
function REPAY662(address _reserve, uint256 _amount, address _onBehalfOf) external payable; //inject NONSTANDARD NAMING
function SWAPBORROWRATEMODE766(address _reserve) external; //inject NONSTANDARD NAMING
function REBALANCEFIXEDBORROWRATE627(address _reserve, address _user) external; //inject NONSTANDARD NAMING
function SETUSERUSERESERVEASCOLLATERAL986(address _reserve, bool _useAsCollateral) external; //inject NONSTANDARD NAMING
function LIQUIDATIONCALL807(address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken) external payable; //inject NONSTANDARD NAMING
function FLASHLOAN206(address _receiver, address _reserve, uint256 _amount, bytes calldata _params) external; //inject NONSTANDARD NAMING
function GETRESERVECONFIGURATIONDATA59(address _reserve) external view returns(uint256 ltv, uint256 liquidationThreshold, uint256 liquidationDiscount, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool fixedBorrowRateEnabled, bool isActive); //inject NONSTANDARD NAMING
function GETRESERVEDATA692(address _reserve) external view returns(uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsFixed, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 fixedBorrowRate, uint256 averageFixedBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp); //inject NONSTANDARD NAMING
function GETUSERACCOUNTDATA811(address _user) external view returns(uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor); //inject NONSTANDARD NAMING
function GETUSERRESERVEDATA732(address _reserve, address _user) external view returns(uint256 currentATokenBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled); //inject NONSTANDARD NAMING
function GETRESERVES689() external view; //inject NONSTANDARD NAMING
}
interface ILendingPoolCore {
function GETRESERVEATOKENADDRESS314(address _reserve) external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVECURRENTVARIABLEBORROWRATE762(address _token) external view returns (uint256); //inject NONSTANDARD NAMING
function GETRESERVECURRENTLIQUIDITYRATE636(address _token) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface IAavePriceOracleGetter {
function GETASSETPRICE734(address _asset) external view returns (uint256); //inject NONSTANDARD NAMING
function GETASSETSPRICES996(address[] calldata _assets) external view returns(uint256[] memory); //inject NONSTANDARD NAMING
function GETSOURCEOFASSET324(address _asset) external view returns(address); //inject NONSTANDARD NAMING
function GETFALLBACKORACLE535() external view returns(address); //inject NONSTANDARD NAMING
}
interface IAToken {
function REDIRECTINTERESTSTREAM242(address _to) external; //inject NONSTANDARD NAMING
function REDIRECTINTERESTSTREAMOF292(address _from, address _to) external; //inject NONSTANDARD NAMING
function ALLOWINTERESTREDIRECTIONTO292(address _to) external; //inject NONSTANDARD NAMING
function REDEEM632(uint256 _amount) external; //inject NONSTANDARD NAMING
function PRINCIPALBALANCEOF100(address _user) external view returns(uint256); //inject NONSTANDARD NAMING
function ISTRANSFERALLOWED396(address _user, uint256 _amount) external view returns (bool); //inject NONSTANDARD NAMING
function GETUSERINDEX768(address _user) external view returns(uint256); //inject NONSTANDARD NAMING
function GETINTERESTREDIRECTIONADDRESS228(address _user) external view returns(address); //inject NONSTANDARD NAMING
function GETREDIRECTEDBALANCE288(address _user) external view returns(uint256); //inject NONSTANDARD NAMING
function TOTALSUPPLY882() external view returns (uint256 supply); //inject NONSTANDARD NAMING
function BALANCEOF767(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING
function TRANSFER204(address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function TRANSFERFROM832(address _from, address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function APPROVE277(address _spender, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function ALLOWANCE10(address _owner, address _spender) external view returns (uint256 remaining); //inject NONSTANDARD NAMING
function NAME858() external view returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL894() external view returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS454() external view returns (uint8); //inject NONSTANDARD NAMING
}
interface PriceOracle {
function GETUNDERLYINGPRICE929(address) external view returns (uint256); //inject NONSTANDARD NAMING
}
// ---------- Compound ----------
interface CErc20 {
function BORROW264(uint256) external returns (uint256); //inject NONSTANDARD NAMING
function BORROWRATEPERBLOCK388() external view returns (uint256); //inject NONSTANDARD NAMING
function BORROWBALANCECURRENT444(address) external returns (uint256); //inject NONSTANDARD NAMING
function REPAYBORROW515(uint256) external returns (uint256); //inject NONSTANDARD NAMING
}
interface CEth {
function MINT397() external payable; //inject NONSTANDARD NAMING
function REDEEMUNDERLYING805(uint redeemAmount) external returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFUNDERLYING788(address owner) external returns (uint256); //inject NONSTANDARD NAMING
function SUPPLYRATEPERBLOCK15() external view returns (uint256); //inject NONSTANDARD NAMING
}
interface Comptroller {
function MARKETS249(address) external returns (bool, uint256); //inject NONSTANDARD NAMING
function ENTERMARKETS82(address[] calldata) //inject NONSTANDARD NAMING
external
returns (uint256[] memory);
function GETACCOUNTLIQUIDITY384(address) //inject NONSTANDARD NAMING
external
view
returns (uint256, uint256, uint256);
function ORACLE168() external view returns(address); //inject NONSTANDARD NAMING
}
// ---------- kyber ----------
interface Exchange {
function TRADE301( //inject NONSTANDARD NAMING
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId )external payable returns(uint);
}
// -----tCDP-----
contract tCDPConstants {
uint256 constant dust264 = 1e6; // minimum mint amount //inject NONSTANDARD NAMING
ERC20 constant dai445 = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI(debt) token address //inject NONSTANDARD NAMING
//Compound
Comptroller constant comptroller75 = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); //inject NONSTANDARD NAMING
CEth constant ceth501 = CEth(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); //inject NONSTANDARD NAMING
CErc20 constant cdai61 = CErc20(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); //inject NONSTANDARD NAMING
//AAVE
ILendingPoolAddressesProvider constant addressesprovider654 = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); //inject NONSTANDARD NAMING
uint16 constant referral215 = 47; // TODO: apply new referral code //inject NONSTANDARD NAMING
//Kyber
Exchange constant kybernetwork927 = Exchange(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); //inject NONSTANDARD NAMING
address constant etheraddr36 = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //inject NONSTANDARD NAMING
address constant ref472 = 0xD0533664013a82c31584B7FFDB215139f38Ad77A; //inject NONSTANDARD NAMING
//rebalance target/boundary/size
uint256 constant targetratio559 = 0.4e18; //40% //inject NONSTANDARD NAMING
uint256 constant upperbound23 = 444444444444444444; // 1/225% //inject NONSTANDARD NAMING
uint256 constant lowerbound414 = 363636363636363636; // 1/275% //inject NONSTANDARD NAMING
uint256 constant bite558 = 0.025 * 1e18; //2.5% //inject NONSTANDARD NAMING
}
contract tCDP is ERC20Mintable, tCDPConstants{
using SafeMath for *;
bool public isCompound;
event MIGRATION431(uint8); // 0x01 = to Compound, 0x02 = to Aave //inject NONSTANDARD NAMING
constructor() public {
symbol = "tETH-DAI";
name = "tokenized CDP ETH-DAI v1";
decimals = 18;
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
dai445.APPROVE277(lendingPoolCoreAddress, uint256(-1));
dai445.APPROVE277(address(cdai61), uint256(-1));
address[] memory cTokens = new address[](1);
cTokens[0] = address(ceth501);
uint256[] memory errors = comptroller75.ENTERMARKETS82(cTokens);
require(errors[0] == 0, "Comptroller.enterMarkets failed.");
dai445.APPROVE277(address(kybernetwork927), uint256(-1));
isCompound = FINDBESTRATE616();
}
function INITIATE270(uint256 amount) external payable { //inject NONSTANDARD NAMING
require(_totalSupply < dust264, "initiated");
require(msg.value > dust264, "value too small");
if(isCompound) {
ceth501.MINT397.value(msg.value)();
_MINT321(msg.sender, msg.value);
require(cdai61.BORROW264(amount) == 0, "borrow failed");
dai445.TRANSFER204(msg.sender, amount);
}
else {
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.DEPOSIT818.value(msg.value)(etheraddr36, msg.value, referral215);
_MINT321(msg.sender, msg.value);
lendingPool.BORROW264(address(dai445), amount, 2, referral215);
dai445.TRANSFER204(msg.sender, amount);
}
}
function COLLATERAL797() public returns(uint256) { //inject NONSTANDARD NAMING
if(isCompound) {
return ceth501.BALANCEOFUNDERLYING788(address(this));
}
else {
address lendingPoolCore = addressesprovider654.GETLENDINGPOOLCORE21();
address aETH = ILendingPoolCore(lendingPoolCore).GETRESERVEATOKENADDRESS314(etheraddr36);
return IAToken(aETH).BALANCEOF767(address(this));
}
}
function DEBT567() public returns(uint256) { //inject NONSTANDARD NAMING
if(isCompound) {
return cdai61.BORROWBALANCECURRENT444(address(this));
}
else {
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
(, uint256 borrowBalance,,,,,,,,) = lendingPool.GETUSERRESERVEDATA732(address(dai445), address(this));
return borrowBalance;
}
}
function MINT397() external payable returns(uint256) { //inject NONSTANDARD NAMING
require(_totalSupply >= dust264, "not initiated");
uint256 amount = msg.value;
uint256 tokenToMint = _totalSupply.MUL98(amount).DIV107(COLLATERAL797());
uint256 tokenToBorrow = DEBT567().MUL98(amount).DIV107(COLLATERAL797());
_MINT321(msg.sender, tokenToMint);
if(isCompound) {
ceth501.MINT397.value(amount)();
require(cdai61.BORROW264(tokenToBorrow) == 0, "borrow failed");
dai445.TRANSFER204(msg.sender, tokenToBorrow);
}
else{
// deposit
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.DEPOSIT818.value(amount)(etheraddr36, amount, referral215);
// borrow
lendingPool.BORROW264(address(dai445), tokenToBorrow, 2, referral215);
// transfer
dai445.TRANSFER204(msg.sender, tokenToBorrow);
}
return tokenToMint;
}
function BURN250(uint256 amount) external { //inject NONSTANDARD NAMING
uint256 tokenToRepay = amount.MUL98(DEBT567()).DIV107(_totalSupply);
uint256 tokenToDraw = amount.MUL98(COLLATERAL797()).DIV107(_totalSupply);
_BURN441(msg.sender, amount);
dai445.TRANSFERFROM832(msg.sender, address(this), tokenToRepay);
if(isCompound) {
require(cdai61.REPAYBORROW515(tokenToRepay) == 0, "repay failed");
require(ceth501.REDEEMUNDERLYING805(tokenToDraw) == 0, "redeem failed");
}
else {
// repay
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
// Dai.approve(lendingPoolCoreAddress, tokenToRepay);
lendingPool.REPAY662(address(dai445), tokenToRepay, address(this));
// redeem
IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36));
aETH.REDEEM632(tokenToDraw);
}
(bool success, ) = msg.sender.call.value(tokenToDraw)("");
require(success, "Failed to transfer ether to msg.sender");
}
function() external payable{}
//true if (cEth APR - cDai APR) >= (aEth APR - aDai APR), otherwise, false
function FINDBESTRATE616() public view returns (bool) { //inject NONSTANDARD NAMING
return AAVEDAIAPR797().MUL98(targetratio559).DIV107(1e18).ADD235(COMPOUNDETHAPR912()) > COMPOUNDDAIAPR961().MUL98(targetratio559).DIV107(1e18).ADD235(AAVEETHAPR160());
}
function COMPOUNDDAIAPR961() public view returns (uint256) { //inject NONSTANDARD NAMING
return cdai61.BORROWRATEPERBLOCK388().MUL98(2102400);
}
function COMPOUNDETHAPR912() public view returns (uint256) { //inject NONSTANDARD NAMING
return ceth501.SUPPLYRATEPERBLOCK15().MUL98(2102400);
}
function AAVEDAIAPR797() public view returns (uint256) { //inject NONSTANDARD NAMING
ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21());
return core.GETRESERVECURRENTVARIABLEBORROWRATE762(address(dai445)).DIV107(1e9);
}
function AAVEETHAPR160() public view returns (uint256) { //inject NONSTANDARD NAMING
ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21());
return core.GETRESERVECURRENTLIQUIDITYRATE636(etheraddr36).DIV107(1e9);
}
function GETUNDERLYINGPRICE929() public view returns(uint256) { //inject NONSTANDARD NAMING
uint256 price;
if(isCompound) {
address oracle = comptroller75.ORACLE168();
PriceOracle priceOracle = PriceOracle(oracle);
price = priceOracle.GETUNDERLYINGPRICE929(address(cdai61));
}
else {
address oracleAddress = addressesprovider654.GETPRICEORACLE485();
IAavePriceOracleGetter priceOracle = IAavePriceOracleGetter(oracleAddress);
price = priceOracle.GETASSETPRICE734(address(dai445));
}
return price;
}
function DEBTRATIO670() public returns (uint256) { //inject NONSTANDARD NAMING
uint256 price = GETUNDERLYINGPRICE929();
uint256 ratio = DEBT567().MUL98(price).DIV107(COLLATERAL797());
return ratio;
}
function DELEVERAGE904() external { //inject NONSTANDARD NAMING
require(_totalSupply >= dust264, "not initiated");
require(DEBTRATIO670() > upperbound23, "debt ratio is good");
uint256 amount = COLLATERAL797().MUL98(bite558).DIV107(1e18);
if(isCompound) {
require(ceth501.REDEEMUNDERLYING805(amount) == 0, "redeem failed");
uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472);
require(cdai61.REPAYBORROW515(income) == 0, "repay failed");
}
else {
// redeem
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36));
aETH.REDEEM632(amount);
uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472);
// repay
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
// Dai.approve(lendingPoolCoreAddress, income);
lendingPool.REPAY662(address(dai445), income, address(this));
}
}
function LEVERAGE920() external { //inject NONSTANDARD NAMING
require(_totalSupply >= dust264, "not initiated");
require(DEBTRATIO670() < lowerbound414, "debt ratio is good");
uint256 amount = DEBT567().MUL98(bite558).DIV107(1e18);
if(isCompound) {
require(cdai61.BORROW264(amount) == 0, "borrow failed");
uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472);
ceth501.MINT397.value(income)();
}
else {
// borrow
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.BORROW264(address(dai445), amount, 2, referral215);
uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472);
// deposit
lendingPool.DEPOSIT818.value(income)(etheraddr36, income, referral215);
}
}
function MIGRATE814() external { //inject NONSTANDARD NAMING
if(FINDBESTRATE616() != isCompound) {
uint256 _debt = DEBT567();
uint256 _collateral = COLLATERAL797();
dai445.TRANSFERFROM832(msg.sender, address(this), _debt);
uint256 newBorrow = _debt.ADD235(2);
if(isCompound) {
require(cdai61.REPAYBORROW515(_debt) == 0, "borrow failed");
require(ceth501.REDEEMUNDERLYING805(_collateral) == 0, "redeem failed");
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.DEPOSIT818.value(_collateral)(etheraddr36, _collateral, referral215);
lendingPool.BORROW264(address(dai445), newBorrow, 2, referral215);
isCompound = false;
emit MIGRATION431(0x02);
}
else {
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
lendingPool.REPAY662(address(dai445), _debt, address(this));
IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36));
aETH.REDEEM632(_collateral);
ceth501.MINT397.value(_collateral)();
require(cdai61.BORROW264(newBorrow) == 0, "borrow failed");
isCompound = true;
emit MIGRATION431(0x01);
}
dai445.TRANSFER204(msg.sender, newBorrow);
}
}
}
|
inject NONSTANDARD NAMING
|
function GETLENDINGPOOL38() public view returns (address);
| 5,544,548 |
./full_match/4/0xF385BE5f6AE64f3C6e967C1CD7Ac359039BcE62c/sources/contracts/NaffleNew.sol
|
creatorToCampaign[_creator][_campaignIndex].nftItem.transferFrom(_creator, _winner, _nftTokenId); creatorToCampaign[_creator][_campaignIndex].nftItem.transfer(_winner, _nftTokenId); address _winner = creatorToCampaign[_creator].winner; creatorToCampaign[_creator].nftItem.transferFrom(_creator, _winner, _nftTokenId); return (_winner, sent);
|
function chooseWinnerAndSell (address _creator, uint256 _campaignIndex) internal returns(address, bool){
require(creatorToCampaign[_creator][_campaignIndex].endTime < block.timestamp, "It's not time to draw yet.");
uint256 _successedTicket = randomTicketId(_creator, _campaignIndex);
address _winner = creatorToCampaign[_creator][_campaignIndex].ticketIdToBuyer[_successedTicket];
uint256 _nftTokenId = creatorToCampaign[_creator][_campaignIndex].nftTokenId;
uint256 _currentTickets = creatorToCampaign[_creator][_campaignIndex].tickets.length;
uint256 _ticketPrice = creatorToCampaign[_creator][_campaignIndex].ticketPrice;
uint256 _totalPrice = _ticketPrice * _currentTickets;
uint256 _platformFee = calculatePercentage(_totalPrice, platformFee);
uint256 _totalIncome = _totalPrice - _platformFee;
address _nftAddress = creatorToCampaign[_creator][_campaignIndex].nftAddress;
creatorToCampaign[_creator][_campaignIndex].winner = _winner;
creatorToCampaign[_creator][_campaignIndex].nftItem.transferFrom(_nftAddress, _winner, _nftTokenId);
closeCampaign(_creator, _campaignIndex);
emit Selled(_creator,_campaignIndex);
return (_winner, sent);
(bool sent,) = _creator.call{value: _totalIncome}("");
}
| 12,288,304 |
pragma solidity ^0.4.18;
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
pragma solidity ^0.4.0;
contract OraclizeI {
address public cbAddress;
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable public returns (bytes32 _id);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) public;
function setCustomGasPrice(uint _gasPrice) public;
}
contract OraclizeAddrResolverI {
function getAddress() view public returns (address _addr);
}
contract usingOraclize {
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if ((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetworkAuto();
if (address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetworkAuto() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit, uint priceLimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > priceLimit + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title 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;
}
}
library Helpers {
using SafeMath for uint256;
function parseIntRound(string _a, uint256 _b) internal pure returns (uint256) {
bytes memory bresult = bytes(_a);
uint256 mint = 0;
_b++;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((bresult[i] >= 48) && (bresult[i] <= 57)) {
if (decimals) {
if (_b == 0) {
break;
}
else
_b--;
}
if (_b == 0) {
if (uint(bresult[i]) - 48 >= 5)
mint += 1;
} else {
mint *= 10;
mint += uint(bresult[i]) - 48;
}
} else if (bresult[i] == 46)
decimals = true;
}
if (_b > 0)
mint *= 10**(_b - 1);
return mint;
}
}
contract OracleI {
bytes32 public oracleName;
bytes16 public oracleType;
uint256 public rate;
bool public waitQuery;
uint256 public updateTime;
uint256 public callbackTime;
function getPrice() view public returns (uint);
function setBank(address _bankAddress) public;
function setGasPrice(uint256 _price) public;
function setGasLimit(uint256 _limit) public;
function updateRate() external returns (bool);
}
/**
* @title Base contract for Oraclize oracles.
*
* @dev Base contract for oracles. Not abstract.
*/
contract OracleBase is Ownable, usingOraclize, OracleI {
event NewOraclizeQuery();
event OraclizeError(string desciption);
event PriceTicker(string price, bytes32 queryId, bytes proof);
event BankSet(address bankAddress);
struct OracleConfig {
string datasource;
string arguments;
}
bytes32 public oracleName = "Base Oracle";
bytes16 public oracleType = "Undefined";
uint256 public updateTime;
uint256 public callbackTime;
uint256 public priceLimit = 1 ether;
mapping(bytes32=>bool) validIds; // ensure that each query response is processed only once
address public bankAddress;
uint256 public rate;
bool public waitQuery = false;
OracleConfig public oracleConfig;
uint256 public gasPrice = 20 * 10**9;
uint256 public gasLimit = 100000;
uint256 constant MIN_GAS_PRICE = 1 * 10**9; // Min gas price limit
uint256 constant MAX_GAS_PRICE = 100 * 10**9; // Max gas limit pric
uint256 constant MIN_GAS_LIMIT = 95000;
uint256 constant MAX_GAS_LIMIT = 1000000;
uint256 constant MIN_REQUEST_PRICE = 0.001118 ether;
modifier onlyBank() {
require(msg.sender == bankAddress);
_;
}
/**
* @dev Constructor.
*/
function OracleBase() public {
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
}
/**
* @dev Sets gas price.
* @param priceInWei New gas price.
*/
function setGasPrice(uint256 priceInWei) public onlyOwner {
require((priceInWei >= MIN_GAS_PRICE) && (priceInWei <= MAX_GAS_PRICE));
gasPrice = priceInWei;
oraclize_setCustomGasPrice(gasPrice);
}
/**
* @dev Sets gas limit.
* @param _gasLimit New gas limit.
*/
function setGasLimit(uint256 _gasLimit) public onlyOwner {
require((_gasLimit >= MIN_GAS_LIMIT) && (_gasLimit <= MAX_GAS_LIMIT));
gasLimit = _gasLimit;
}
/**
* @dev Sets bank address.
* @param bank Address of the bank contract.
*/
function setBank(address bank) public onlyOwner {
bankAddress = bank;
BankSet(bankAddress);
}
/**
* @dev oraclize getPrice.
*/
function getPrice() public view returns (uint) {
return oraclize_getPrice(oracleConfig.datasource, gasLimit);
}
/**
* @dev Requests updating rate from oraclize.
*/
function updateRate() external onlyBank returns (bool) {
if (getPrice() > this.balance) {
OraclizeError("Not enough ether");
return false;
}
bytes32 queryId = oraclize_query(oracleConfig.datasource, oracleConfig.arguments, gasLimit, priceLimit);
if (queryId == bytes32(0)) {
OraclizeError("Unexpectedly high query price");
return false;
}
NewOraclizeQuery();
validIds[queryId] = true;
waitQuery = true;
updateTime = now;
return true;
}
/**
* @dev Oraclize default callback with the proof set.
* @param myid The callback ID.
* @param result The callback data.
* @param proof The oraclize proof bytes.
*/
function __callback(bytes32 myid, string result, bytes proof) public {
require(validIds[myid] && msg.sender == oraclize_cbAddress());
rate = Helpers.parseIntRound(result, 3); // save it in storage as 1/1000 of $
delete validIds[myid];
callbackTime = now;
waitQuery = false;
PriceTicker(result, myid, proof);
}
/**
* @dev Oraclize default callback without the proof set.
* @param myid The callback ID.
* @param result The callback data.
*/
function __callback(bytes32 myid, string result) public {
bytes memory proof = new bytes(1);
__callback(myid, result, proof);
}
/**
* @dev Method used for oracle funding
*/
function () public payable {}
}
/**
* @title Bitfinex oracle.
*
* @dev URL: https://www.bitfinex.com
* @dev API Docs: https://bitfinex.readme.io/v1/reference#rest-public-ticker
*/
contract OracleBitfinex is OracleBase {
bytes32 constant ORACLE_NAME = "Bitfinex Oraclize Async";
bytes16 constant ORACLE_TYPE = "ETHUSD";
string constant ORACLE_DATASOURCE = "URL";
string constant ORACLE_ARGUMENTS = "json(https://api.bitfinex.com/v1/pubticker/ethusd).last_price";
/**
* @dev Constructor.
*/
function OracleBitfinex() public {
oracleName = ORACLE_NAME;
oracleType = ORACLE_TYPE;
oracleConfig = OracleConfig({datasource: ORACLE_DATASOURCE, arguments: ORACLE_ARGUMENTS});
}
}
|
Sets bank address. bank Address of the bank contract./
|
function setBank(address bank) public onlyOwner {
bankAddress = bank;
BankSet(bankAddress);
}
| 2,474,407 |
./full_match/56/0x2B26d2ebA918870657eBA9AA7623Cfa98Cc17187/sources/Address.sol
|
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 or custom error, it is bubbled up by this function (like regular Solidity function calls). However, if the call reverted with no returned reason, this function reverts with a {FailedInnerCall} error. Returns the raw returned data. To convert to the expected return value, Requirements: - `target` must be a contract. - calling `target` with `data` must not revert./
|
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
| 3,228,970 |
./full_match/1/0x0f3191844f9Ef71EBe63e1Eb25ED25c19dd07352/sources/src/Libraries/LibAsset.sol
|
Gives MAX approval for another address to spend tokens assetId Token address to transfer spender Address to give spend approval to amount Amount to approve for spending/
|
function maxApproveERC20(
IERC20 assetId,
address spender,
uint256 amount
) internal {
if (address(assetId) == NATIVE_ASSETID) return;
if (spender == NULL_ADDRESS) revert NullAddrIsNotAValidSpender();
uint256 allowance = assetId.allowance(address(this), spender);
if (allowance < amount) {
if (allowance != 0) SafeERC20.safeApprove(IERC20(assetId), spender, 0);
SafeERC20.safeIncreaseAllowance(IERC20(assetId), spender, MAX_INT);
}
}
| 9,746,484 |
./full_match/4/0xE849C5A1eaA1604e80841B9140B9f34Fb7017120/sources/contracts/potenza/Potenza.sol
|
Calculate the total available number of mints return total mint available/
|
function totalMintsAvailable() public view override returns (uint256) {
return derivativeParams.maxTotalSupply - currentSupply;
}
| 794,063 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title: MinteVipTicket
/// @authors: manifold.xyz & Collector
import "./ERC721Creator.sol";
contract MVIP is ERC721Creator {
uint256 public price = 40000000000000000; //0.04 ETH
bool public saleIsActive = true;
uint private rand;
constructor(string memory tokenName, string memory symbol) ERC721Creator(tokenName, symbol) {}
/* claim multiple tokens */
function claimBatch(address to, uint256 _qty) public nonReentrant payable {
require(_qty > 0, "Quantity must be more than 0");
require(saleIsActive, "Sale must be active to mint");
require(msg.value >= price*_qty, "Price is not correct.");
string memory uri;
for (uint i = 0; i < _qty; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
rand = (pseudo_rand()%100)+1;
uri = getVIPUri(rand);
_mintBase(to, uri);
}
}
function getVIPUri(uint r) private pure returns (string memory) {
string memory uri;
if (r < 41 ){
uri = "ipfs://QmTfFj2d8oXRRhmFG9h82zkSdTjzEiqk3ZCiotFp2XLtfg"; //DYNASTY
} else if (r >= 41 && r < 69){
uri = "ipfs://QmYXwKTQRutEgMyjP35kcSqvZ6mZnB92Q4Hgu7LnVvLD4j"; //RELICS
} else if (r >= 69 && r < 86){
uri = "ipfs://QmW7us4Zmk9ZcZQVgR17QijKCXFMFCXvtLxwSL9gFFFL6y"; //ROYALS
} else if (r >= 86 && r < 96){
uri = "ipfs://QmR2LJjd7hCm95FFtVvgxz8f98LKLTQeXgHdWqHiwnToQR"; //LEGENDS
} else if (r >= 96 && r < 100){
uri = "ipfs://QmYtD7m8mUb3JHwQCEaskjW9KPwrr2XgQNnFEwjLnnEzkC"; //COSMOS
} else {
uri = "ipfs://QmQDAGCT5ux1Fc6zTKjbVNF18KofYpLDTK7AiRN3P5dP4C"; //GENESIS
}
return uri;
}
function pseudo_rand() private view returns (uint) {
return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, _tokenCount)));
}
function withdraw() public payable adminRequired {
require(payable(_msgSender()).send(address(this).balance));
}
function changeSaleState() public adminRequired {
saleIsActive = !saleIsActive;
}
function changePrice(uint256 newPrice) public adminRequired {
price = newPrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "./access/AdminControl.sol";
import "./core/ERC721CreatorCore.sol";
/**
* @dev ERC721Creator implementation
*/
contract ERC721Creator is AdminControl, ERC721, ERC721CreatorCore {
constructor (string memory _name, string memory _symbol) ERC721(_name, _symbol) {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721CreatorCore, AdminControl) returns (bool) {
return ERC721CreatorCore.supportsInterface(interfaceId) || ERC721.supportsInterface(interfaceId) || AdminControl.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
_approveTransfer(from, to, tokenId);
}
/**
* @dev See {ICreatorCore-registerExtension}.
*/
function registerExtension(address extension, string calldata baseURI) external override adminRequired nonBlacklistRequired(extension) {
_registerExtension(extension, baseURI, false);
}
/**
* @dev See {ICreatorCore-registerExtension}.
*/
function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external override adminRequired nonBlacklistRequired(extension) {
_registerExtension(extension, baseURI, baseURIIdentical);
}
/**
* @dev See {ICreatorCore-unregisterExtension}.
*/
function unregisterExtension(address extension) external override adminRequired {
_unregisterExtension(extension);
}
/**
* @dev See {ICreatorCore-blacklistExtension}.
*/
function blacklistExtension(address extension) external override adminRequired {
_blacklistExtension(extension);
}
/**
* @dev See {ICreatorCore-setBaseTokenURIExtension}.
*/
function setBaseTokenURIExtension(string calldata uri) external override extensionRequired {
_setBaseTokenURIExtension(uri, false);
}
/**
* @dev See {ICreatorCore-setBaseTokenURIExtension}.
*/
function setBaseTokenURIExtension(string calldata uri, bool identical) external override extensionRequired {
_setBaseTokenURIExtension(uri, identical);
}
/**
* @dev See {ICreatorCore-setTokenURIPrefixExtension}.
*/
function setTokenURIPrefixExtension(string calldata prefix) external override extensionRequired {
_setTokenURIPrefixExtension(prefix);
}
/**
* @dev See {ICreatorCore-setTokenURIExtension}.
*/
function setTokenURIExtension(uint256 tokenId, string calldata uri) external override extensionRequired {
_setTokenURIExtension(tokenId, uri);
}
/**
* @dev See {ICreatorCore-setTokenURIExtension}.
*/
function setTokenURIExtension(uint256[] memory tokenIds, string[] calldata uris) external override extensionRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint i = 0; i < tokenIds.length; i++) {
_setTokenURIExtension(tokenIds[i], uris[i]);
}
}
/**
* @dev See {ICreatorCore-setBaseTokenURI}.
*/
function setBaseTokenURI(string calldata uri) external override adminRequired {
_setBaseTokenURI(uri);
}
/**
* @dev See {ICreatorCore-setTokenURIPrefix}.
*/
function setTokenURIPrefix(string calldata prefix) external override adminRequired {
_setTokenURIPrefix(prefix);
}
/**
* @dev See {ICreatorCore-setTokenURI}.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external override adminRequired {
_setTokenURI(tokenId, uri);
}
/**
* @dev See {ICreatorCore-setTokenURI}.
*/
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external override adminRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint i = 0; i < tokenIds.length; i++) {
_setTokenURI(tokenIds[i], uris[i]);
}
}
/**
* @dev See {ICreatorCore-setMintPermissions}.
*/
function setMintPermissions(address extension, address permissions) external override adminRequired {
_setMintPermissions(extension, permissions);
}
/**
* @dev See {IERC721CreatorCore-mintBase}.
*/
function mintBase(address to) public virtual override nonReentrant adminRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintBase(to, "");
}
/**
* @dev See {IERC721CreatorCore-mintBase}.
*/
function mintBase(address to, string calldata uri) public virtual override nonReentrant adminRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintBase(to, uri);
}
/**
* @dev See {IERC721CreatorCore-mintBaseBatch}.
*/
function mintBaseBatch(address to, uint16 count) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintBase(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721CreatorCore-mintBaseBatch}.
*/
function mintBaseBatch(address to, string[] calldata uris) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](uris.length);
for (uint i = 0; i < uris.length; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintBase(to, uris[i]);
}
return tokenIds;
}
/**
* @dev Mint token with no extension
*/
function _mintBase(address to, string memory uri) internal virtual returns(uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
// Track the extension that minted the token
_tokensExtension[tokenId] = address(this);
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintBase(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721CreatorCore-mintExtension}.
*/
function mintExtension(address to) public virtual override nonReentrant extensionRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintExtension(to, "");
}
/**
* @dev See {IERC721CreatorCore-mintExtension}.
*/
function mintExtension(address to, string calldata uri) public virtual override nonReentrant extensionRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintExtension(to, uri);
}
/**
* @dev See {IERC721CreatorCore-mintExtensionBatch}.
*/
function mintExtensionBatch(address to, uint16 count) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintExtension(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721CreatorCore-mintExtensionBatch}.
*/
function mintExtensionBatch(address to, string[] calldata uris) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](uris.length);
for (uint i = 0; i < uris.length; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintExtension(to, uris[i]);
}
}
/**
* @dev Mint token via extension
*/
function _mintExtension(address to, string memory uri) internal virtual returns(uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
_checkMintPermissions(to, tokenId);
// Track the extension that minted the token
_tokensExtension[tokenId] = msg.sender;
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintExtension(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721CreatorCore-tokenExtension}.
*/
function tokenExtension(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "Nonexistent token");
return _tokenExtension(tokenId);
}
/**
* @dev See {IERC721CreatorCore-burn}.
*/
function burn(uint256 tokenId) public virtual override nonReentrant {
require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved");
address owner = ownerOf(tokenId);
_burn(tokenId);
_postBurn(owner, tokenId);
}
/**
* @dev See {ICreatorCore-setRoyalties}.
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired {
_setRoyaltiesExtension(address(this), receivers, basisPoints);
}
/**
* @dev See {ICreatorCore-setRoyalties}.
*/
function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired {
require(_exists(tokenId), "Nonexistent token");
_setRoyalties(tokenId, receivers, basisPoints);
}
/**
* @dev See {ICreatorCore-setRoyaltiesExtension}.
*/
function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired {
_setRoyaltiesExtension(extension, receivers, basisPoints);
}
/**
* @dev {See ICreatorCore-getRoyalties}.
*/
function getRoyalties(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See ICreatorCore-getFees}.
*/
function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See ICreatorCore-getFeeRecipients}.
*/
function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyReceivers(tokenId);
}
/**
* @dev {See ICreatorCore-getFeeBps}.
*/
function getFeeBps(uint256 tokenId) external view virtual override returns (uint[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyBPS(tokenId);
}
/**
* @dev {See ICreatorCore-royaltyInfo}.
*/
function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata) external view virtual override returns (address, uint256, bytes memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyInfo(tokenId, value);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "Nonexistent token");
return _tokenURI(tokenId);
}
}
// 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}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./IAdminControl.sol";
abstract contract AdminControl is Ownable, IAdminControl, ERC165 {
using EnumerableSet for EnumerableSet.AddressSet;
// Track registered admins
EnumerableSet.AddressSet private _admins;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IAdminControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Only allows approved admins to call the specified function
*/
modifier adminRequired() {
require(owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin");
_;
}
/**
* @dev See {IAdminControl-getAdmins}.
*/
function getAdmins() external view override returns (address[] memory admins) {
admins = new address[](_admins.length());
for (uint i = 0; i < _admins.length(); i++) {
admins[i] = _admins.at(i);
}
return admins;
}
/**
* @dev See {IAdminControl-approveAdmin}.
*/
function approveAdmin(address admin) external override onlyOwner {
if (!_admins.contains(admin)) {
emit AdminApproved(admin, msg.sender);
_admins.add(admin);
}
}
/**
* @dev See {IAdminControl-revokeAdmin}.
*/
function revokeAdmin(address admin) external override onlyOwner {
if (_admins.contains(admin)) {
emit AdminRevoked(admin, msg.sender);
_admins.remove(admin);
}
}
/**
* @dev See {IAdminControl-isAdmin}.
*/
function isAdmin(address admin) public override view returns (bool) {
return (owner() == admin || _admins.contains(admin));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "../extensions/ERC721/IERC721CreatorExtensionApproveTransfer.sol";
import "../extensions/ERC721/IERC721CreatorExtensionBurnable.sol";
import "../permissions/ERC721/IERC721CreatorMintPermissions.sol";
import "./IERC721CreatorCore.sol";
import "./CreatorCore.sol";
/**
* @dev Core ERC721 creator implementation
*/
abstract contract ERC721CreatorCore is CreatorCore, IERC721CreatorCore {
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorCore, IERC165) returns (bool) {
return interfaceId == type(IERC721CreatorCore).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {ICreatorCore-setApproveTransferExtension}.
*/
function setApproveTransferExtension(bool enabled) external override extensionRequired {
require(!enabled || ERC165Checker.supportsInterface(msg.sender, type(IERC721CreatorExtensionApproveTransfer).interfaceId), "Extension must implement IERC721CreatorExtensionApproveTransfer");
if (_extensionApproveTransfers[msg.sender] != enabled) {
_extensionApproveTransfers[msg.sender] = enabled;
emit ExtensionApproveTransferUpdated(msg.sender, enabled);
}
}
/**
* @dev Set mint permissions for an extension
*/
function _setMintPermissions(address extension, address permissions) internal {
require(_extensions.contains(extension), "CreatorCore: Invalid extension");
require(permissions == address(0x0) || ERC165Checker.supportsInterface(permissions, type(IERC721CreatorMintPermissions).interfaceId), "Invalid address");
if (_extensionPermissions[extension] != permissions) {
_extensionPermissions[extension] = permissions;
emit MintPermissionsUpdated(extension, permissions, msg.sender);
}
}
/**
* Check if an extension can mint
*/
function _checkMintPermissions(address to, uint256 tokenId) internal {
if (_extensionPermissions[msg.sender] != address(0x0)) {
IERC721CreatorMintPermissions(_extensionPermissions[msg.sender]).approveMint(msg.sender, to, tokenId);
}
}
/**
* Override for post mint actions
*/
function _postMintBase(address, uint256) internal virtual {}
/**
* Override for post mint actions
*/
function _postMintExtension(address, uint256) internal virtual {}
/**
* Post-burning callback and metadata cleanup
*/
function _postBurn(address owner, uint256 tokenId) internal virtual {
// Callback to originating extension if needed
if (_tokensExtension[tokenId] != address(this)) {
if (ERC165Checker.supportsInterface(_tokensExtension[tokenId], type(IERC721CreatorExtensionBurnable).interfaceId)) {
IERC721CreatorExtensionBurnable(_tokensExtension[tokenId]).onBurn(owner, tokenId);
}
}
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
// Delete token origin extension tracking
delete _tokensExtension[tokenId];
}
/**
* Approve a transfer
*/
function _approveTransfer(address from, address to, uint256 tokenId) internal {
if (_extensionApproveTransfers[_tokensExtension[tokenId]]) {
require(IERC721CreatorExtensionApproveTransfer(_tokensExtension[tokenId]).approveTransfer(from, to, tokenId), "ERC721Creator: Extension approval failure");
}
}
}
// 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;
/**
* @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;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "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] = alphabet[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;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Interface for admin control
*/
interface IAdminControl is IERC165 {
event AdminApproved(address indexed account, address indexed sender);
event AdminRevoked(address indexed account, address indexed sender);
/**
* @dev gets address of all admins
*/
function getAdmins() external view returns (address[] memory);
/**
* @dev add an admin. Can only be called by contract owner.
*/
function approveAdmin(address admin) external;
/**
* @dev remove an admin. Can only be called by contract owner.
*/
function revokeAdmin(address admin) external;
/**
* @dev checks whether or not given address is an admin
* Returns True if they are
*/
function isAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* Implement this if you want your extension to approve a transfer
*/
interface IERC721CreatorExtensionApproveTransfer is IERC165 {
/**
* @dev Set whether or not the creator will check the extension for approval of token transfer
*/
function setApproveTransfer(address creator, bool enabled) external;
/**
* @dev Called by creator contract to approve a transfer
*/
function approveTransfer(address from, address to, uint256 tokenId) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Your extension is required to implement this interface if it wishes
* to receive the onBurn callback whenever a token the extension created is
* burned
*/
interface IERC721CreatorExtensionBurnable is IERC165 {
/**
* @dev callback handler for burn events
*/
function onBurn(address owner, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721Creator compliant extension contracts.
*/
interface IERC721CreatorMintPermissions is IERC165 {
/**
* @dev get approval to mint
*/
function approveMint(address extension, address to, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "./ICreatorCore.sol";
/**
* @dev Core ERC721 creator interface
*/
interface IERC721CreatorCore is ICreatorCore {
/**
* @dev mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBase(address to) external returns (uint256);
/**
* @dev mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBase(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBaseBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBaseBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtension(address to) external returns (uint256);
/**
* @dev mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtension(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token. Can only be called by a registered extension.
* Returns tokenIds minted
*/
function mintExtensionBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtensionBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev burn a token. Can only be called by token owner or approved address.
* On burn, calls back to the registered extension's onBurn method
*/
function burn(uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../extensions/ICreatorExtensionTokenURI.sol";
import "./ICreatorCore.sol";
/**
* @dev Core creator implementation
*/
abstract contract CreatorCore is ReentrancyGuard, ICreatorCore, ERC165 {
using Strings for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
using AddressUpgradeable for address;
uint256 public _tokenCount = 0;
uint256 public MAX_TICKETS = 25000; // max number of tokens to mint
// Track registered extensions data
EnumerableSet.AddressSet internal _extensions;
EnumerableSet.AddressSet internal _blacklistedExtensions;
mapping (address => address) internal _extensionPermissions;
mapping (address => bool) internal _extensionApproveTransfers;
// For tracking which extension a token was minted by
mapping (uint256 => address) internal _tokensExtension;
// The baseURI for a given extension
mapping (address => string) private _extensionBaseURI;
mapping (address => bool) private _extensionBaseURIIdentical;
// The prefix for any tokens with a uri configured
mapping (address => string) private _extensionURIPrefix;
// Mapping for individual token URIs
mapping (uint256 => string) internal _tokenURIs;
// Royalty configurations
mapping (address => address payable[]) internal _extensionRoyaltyReceivers;
mapping (address => uint256[]) internal _extensionRoyaltyBPS;
mapping (uint256 => address payable[]) internal _tokenRoyaltyReceivers;
mapping (uint256 => uint256[]) internal _tokenRoyaltyBPS;
/**
* External interface identifiers for royalties
*/
/**
* @dev CreatorCore
*
* bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6
*
* => 0xbb3bafd6 = 0xbb3bafd6
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6;
/**
* @dev Rarible: RoyaltiesV1
*
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
*
* => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584;
/**
* @dev Foundation
*
* bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c
*
* => 0xd5a06d4c = 0xd5a06d4c
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c;
/**
* @dev EIP-2981
*
* bytes4(keccak256("royaltyInfo(uint256,uint256,bytes)")) == 0x6057361d
*
* => 0x6057361d = 0x6057361d
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(ICreatorCore).interfaceId || super.supportsInterface(interfaceId)
|| interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE
|| interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981;
}
/**
* @dev Only allows registered extensions to call the specified function
*/
modifier extensionRequired() {
require(_extensions.contains(msg.sender), "Must be registered extension");
_;
}
/**
* @dev Only allows non-blacklisted extensions
*/
modifier nonBlacklistRequired(address extension) {
require(!_blacklistedExtensions.contains(extension), "Extension blacklisted");
_;
}
/**
* @dev See {ICreatorCore-getExtensions}.
*/
function getExtensions() external view override returns (address[] memory extensions) {
extensions = new address[](_extensions.length());
for (uint i = 0; i < _extensions.length(); i++) {
extensions[i] = _extensions.at(i);
}
return extensions;
}
/**
* @dev Register an extension
*/
function _registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) internal {
require(extension != address(this), "Creator: Invalid");
require(extension.isContract(), "Creator: Extension must be a contract");
if (!_extensions.contains(extension)) {
_extensionBaseURI[extension] = baseURI;
_extensionBaseURIIdentical[extension] = baseURIIdentical;
emit ExtensionRegistered(extension, msg.sender);
_extensions.add(extension);
}
}
/**
* @dev Unregister an extension
*/
function _unregisterExtension(address extension) internal {
if (_extensions.contains(extension)) {
emit ExtensionUnregistered(extension, msg.sender);
_extensions.remove(extension);
}
}
/**
* @dev Blacklist an extension
*/
function _blacklistExtension(address extension) internal {
require(extension != address(this), "Cannot blacklist yourself");
if (_extensions.contains(extension)) {
emit ExtensionUnregistered(extension, msg.sender);
_extensions.remove(extension);
}
if (!_blacklistedExtensions.contains(extension)) {
emit ExtensionBlacklisted(extension, msg.sender);
_blacklistedExtensions.add(extension);
}
}
/**
* @dev Set base token uri for an extension
*/
function _setBaseTokenURIExtension(string calldata uri, bool identical) internal {
_extensionBaseURI[msg.sender] = uri;
_extensionBaseURIIdentical[msg.sender] = identical;
}
/**
* @dev Set token uri prefix for an extension
*/
function _setTokenURIPrefixExtension(string calldata prefix) internal {
_extensionURIPrefix[msg.sender] = prefix;
}
/**
* @dev Set token uri for a token of an extension
*/
function _setTokenURIExtension(uint256 tokenId, string calldata uri) internal {
require(_tokensExtension[tokenId] == msg.sender, "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Set base token uri for tokens with no extension
*/
function _setBaseTokenURI(string memory uri) internal {
_extensionBaseURI[address(this)] = uri;
}
/**
* @dev Set token uri prefix for tokens with no extension
*/
function _setTokenURIPrefix(string calldata prefix) internal {
_extensionURIPrefix[address(this)] = prefix;
}
/**
* @dev Set token uri for a token with no extension
*/
function _setTokenURI(uint256 tokenId, string calldata uri) internal {
require(_tokensExtension[tokenId] == address(this), "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Retrieve a token's URI
*/
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
address extension = _tokensExtension[tokenId];
require(!_blacklistedExtensions.contains(extension), "Extension blacklisted");
if (bytes(_tokenURIs[tokenId]).length != 0) {
if (bytes(_extensionURIPrefix[extension]).length != 0) {
return string(abi.encodePacked(_extensionURIPrefix[extension],_tokenURIs[tokenId]));
}
return _tokenURIs[tokenId];
}
if (ERC165Checker.supportsInterface(extension, type(ICreatorExtensionTokenURI).interfaceId)) {
return ICreatorExtensionTokenURI(extension).tokenURI(address(this), tokenId);
}
if (!_extensionBaseURIIdentical[extension]) {
return string(abi.encodePacked(_extensionBaseURI[extension], tokenId.toString()));
} else {
return _extensionBaseURI[extension];
}
}
/**
* Get token extension
*/
function _tokenExtension(uint256 tokenId) internal view returns (address extension) {
extension = _tokensExtension[tokenId];
require(extension != address(this), "No extension for token");
require(!_blacklistedExtensions.contains(extension), "Extension blacklisted");
return extension;
}
/**
* Helper to get royalties for a token
*/
function _getRoyalties(uint256 tokenId) view internal returns (address payable[] storage, uint256[] storage) {
return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId));
}
/**
* Helper to get royalty receivers for a token
*/
function _getRoyaltyReceivers(uint256 tokenId) view internal returns (address payable[] storage) {
if (_tokenRoyaltyReceivers[tokenId].length > 0) {
return _tokenRoyaltyReceivers[tokenId];
} else if (_extensionRoyaltyReceivers[_tokensExtension[tokenId]].length > 0) {
return _extensionRoyaltyReceivers[_tokensExtension[tokenId]];
}
return _extensionRoyaltyReceivers[address(this)];
}
/**
* Helper to get royalty basis points for a token
*/
function _getRoyaltyBPS(uint256 tokenId) view internal returns (uint256[] storage) {
if (_tokenRoyaltyBPS[tokenId].length > 0) {
return _tokenRoyaltyBPS[tokenId];
} else if (_extensionRoyaltyBPS[_tokensExtension[tokenId]].length > 0) {
return _extensionRoyaltyBPS[_tokensExtension[tokenId]];
}
return _extensionRoyaltyBPS[address(this)];
}
function _getRoyaltyInfo(uint256 tokenId, uint256 value) view internal returns (address receiver, uint256 amount, bytes memory data){
address payable[] storage receivers = _getRoyaltyReceivers(tokenId);
require(receivers.length <= 1, "More than 1 royalty receiver");
if (receivers.length == 0) {
return (address(this), 0, data);
}
return (receivers[0], _getRoyaltyBPS(tokenId)[0]*value/10000, data);
}
/**
* Set royalties for a token
*/
function _setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_tokenRoyaltyReceivers[tokenId] = receivers;
_tokenRoyaltyBPS[tokenId] = basisPoints;
emit RoyaltiesUpdated(tokenId, receivers, basisPoints);
}
/**
* Set royalties for all tokens of an extension
*/
function _setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_extensionRoyaltyReceivers[extension] = receivers;
_extensionRoyaltyBPS[extension] = basisPoints;
if (extension == address(this)) {
emit DefaultRoyaltiesUpdated(receivers, basisPoints);
} else {
emit ExtensionRoyaltiesUpdated(extension, receivers, basisPoints);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Core creator interface
*/
interface ICreatorCore is IERC165 {
event ExtensionRegistered(address indexed extension, address indexed sender);
event ExtensionUnregistered(address indexed extension, address indexed sender);
event ExtensionBlacklisted(address indexed extension, address indexed sender);
event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender);
event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints);
event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints);
event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints);
event ExtensionApproveTransferUpdated(address indexed extension, bool enabled);
/**
* @dev gets address of all extensions
*/
function getExtensions() external view returns (address[] memory);
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(address extension, string calldata baseURI) external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* Returns True if removed, False if already removed.
*/
function unregisterExtension(address extension) external;
/**
* @dev blacklist an extension. Can only be called by contract owner or admin.
* This function will destroy all ability to reference the metadata of any tokens created
* by the specified extension. It will also unregister the extension if needed.
* Returns True if removed, False if already removed.
*/
function blacklistExtension(address extension) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
*/
function setBaseTokenURIExtension(string calldata uri) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURIExtension(string calldata uri, bool identical) external;
/**
* @dev set the common prefix of an extension. Can only be called by extension.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefixExtension(string calldata prefix) external;
/**
* @dev set the tokenURI of a token extension. Can only be called by extension that minted token.
*/
function setTokenURIExtension(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token.
*/
function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external;
/**
* @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURI(string calldata uri) external;
/**
* @dev set the common prefix for tokens with no extension. Can only be called by owner/admin.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefix(string calldata prefix) external;
/**
* @dev set the tokenURI of a token with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external;
/**
* @dev set a permissions contract for an extension. Used to control minting.
*/
function setMintPermissions(address extension, address permissions) external;
/**
* @dev Configure so transfers of tokens created by the caller (must be extension) gets approval
* from the extension before transferring
*/
function setApproveTransferExtension(bool enabled) external;
/**
* @dev get the extension of a given token
*/
function tokenExtension(uint256 tokenId) external view returns (address);
/**
* @dev Set default royalties
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Set royalties of a token
*/
function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Set royalties of an extension
*/
function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Get royalites of a token. Returns list of receivers and basisPoints
*/
function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
// Royalty support for various other standards
function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory);
function getFeeBps(uint256 tokenId) external view returns (uint[] memory);
function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata data) external view returns (address, uint256, bytes memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, type(IERC165).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
bytes memory encodedParams = abi.encodeWithSelector(IERC165(account).supportsInterface.selector, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return false;
return success && abi.decode(result, (bool));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// 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.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Implement this if you want your extension to have overloadable URI's
*/
interface ICreatorExtensionTokenURI is IERC165 {
/**
* Get the uri for a given creator/tokenId
*/
function tokenURI(address creator, uint256 tokenId) external view returns (string memory);
}
|
See {ICreatorCore-registerExtension}./
|
function registerExtension(address extension, string calldata baseURI) external override adminRequired nonBlacklistRequired(extension) {
_registerExtension(extension, baseURI, false);
}
| 6,210 |
./partial_match/1/0x8Fbc2bD0F023c282EB6913444f26Ec8EC73DE967/sources/src/Pool.sol
|
/ Burn liquidity tokens in exchange for base. The liquidity provider needs to have called `pool.approve`. Only usable before maturity. to Wallet receiving the base and fyToken. minRatio Minimum ratio of shares to fyToken in the pool (fp18). maxRatio Maximum ratio of shares to fyToken in the pool (fp18). return lpTokensBurned The amount of lp tokens burned. return baseOut The amount of base tokens returned.
|
function burnForBase(
address to,
uint256 minRatio,
uint256 maxRatio
)
external
virtual
override
unpaused
beforeMaturity
returns (uint256 lpTokensBurned, uint256 baseOut)
{
(lpTokensBurned, baseOut, ) = _burn(
to,
address(0),
true,
minRatio,
maxRatio
);
}
| 4,162,615 |
./partial_match/4/0xE0677C0D36aABb209A38954428c0e3A6739E80d4/sources/Orchestrator.sol
|
wrapper to call the encoded transactions on downstream consumers. destination Address of destination contract. data The encoded data payload. return True on success/ "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) First 32 bytes are the padded length of data, so exclude that 34710 is the value that solidity is currently emitting It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + callNewAccountGas (25000, in case the destination address does not exist and needs creating)
|
function externalCall(address destination, bytes memory data)
internal
returns (bool)
{
bool result;
let outputAddress := mload(0x40)
let dataAddress := add(data, 32)
result := call(
sub(gas() ,34710),
destination,
dataAddress,
outputAddress,
)
}
return result;
| 8,512,841 |
// SPDX-License-Identifier: MIT
// Created by Flux Team
pragma solidity 0.6.8;
import "./Interface.sol";
import "../lib/SafeMath.sol";
import "../lib/Exponential.sol";
import "../lib/PubContract.sol";
import "../lib/Ownable.sol";
import "./FToken.sol";
import { MarketStatus } from "../FluxApp.sol";
import { IFluxCross } from "../cross/Interface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { INormalERC20 } from "./Interface.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
/**
@title 借贷市场
@dev 在 Flux 中被借贷的资产(标的物)是符合 ERC20 标准的 Token, 资产即可以是 Conflux 上的原始代币,也可是通过侧链系统链接的以太坊 ERC20 代币,我们统称资产为 *cToken*。
任一资产需要在批准后才能被允许交易,且 Flux 专门为 *cToken* 开设**独立的**借贷市场 $a$,但该场所也符合 ERC20 标准,因此命名为 *fToken*。 fToken 价值由兑换汇率决定。
*/
abstract contract Market is Initializable, Ownable, FToken, ReentrancyGuard, MarketStorage {
using SafeMath for uint256;
using Exponential for Exp;
using SafeERC20 for IERC20;
string private constant CONFIG_TAX_RATE = "MKT_BORROW_INTEREST_TAX_RATE";
uint256 private constant MAX_LIQUIDATE_FEERATE = 0.1 * 1e18; //10%
/**
* @notice 存款事件
@param supplyer 取款人(兑换人)
@param ctokens 最终兑换的标的资产数量
@param ftokens 用于兑换标的资产的 ftoken 数量
*/
event Supply(address indexed supplyer, uint256 ctokens, uint256 ftokens, uint256 balance);
/**
* @notice 取款事件
@param redeemer 取款人(兑换人)
@param receiver 接收代币的账户(如果不为空则为以太坊账户地址)
@param ftokens 用于兑换标的资产的 ftoken 数量
@param ctokens 最终兑换的标的资产数量
*/
event Redeem(address indexed redeemer, string receiver, uint256 ftokens, uint256 ctokens);
/**
@notice 借款事件
@param borrower 借款人
@param receiver 接收代币的账户(如果不为空则为以太坊账户地址)
@param ctokens 借款人所借走的标的资产数量
@param borrows 借款人当前的借款余额,含应付利息
@param totalBorrows 市场总借款额,含应付利息
*/
event Borrow(address indexed borrower, string receiver, uint256 ctokens, uint256 borrows, uint256 totalBorrows);
/**
@notice 还款事件
@param repayer 还款人
@param repaid 还款人实际还款的标的资产数量
@param borrows 还款人剩余的借款余额,含应付利息
@param totalBorrows 市场总借款额,含应付利息
*/
event Repay(address indexed repayer, uint256 repaid, uint256 borrows, uint256 totalBorrows);
/**
@notice 借款人抵押品被清算事件
@param liquidator 清算人
@param borrower 借款人
@param supplies 存款
@param borrows 借款
*/
event Liquidated(address indexed liquidator, address indexed borrower, uint256 supplies, uint256 borrows);
event ChangeOracle(IPriceOracle oldValue, IPriceOracle newValue);
/**
* @notice 初始化
* @dev 在借贷市场初始化时设置货币基础信息。
* @param guard_ Flux核心合约
* @param oracle_ 预言机
* @param interestRateModel_ 利率模型
* @param underlying_ FToken 的标的资产地址
* @param name_ FToken名称
* @param symbol_ FToken 货币标识符
*/
function initialize(
address guard_,
address oracle_,
address interestRateModel_,
address underlying_,
string calldata name_,
string calldata symbol_
) external initializer {
_name = name_;
_symbol = symbol_;
_decimals = INormalERC20(underlying_).decimals(); //精度等同于标的资产精度
interestIndex = 1e18; //设置为最小值
initialExchangeRateMan = 1e18;
lastAccrueInterest = block.timestamp;
underlying = IERC20(underlying_);
guard = Guard(guard_);
app = FluxApp(guard.flux());
oracle = IPriceOracle(oracle_);
interestRateModel = IRModel(interestRateModel_);
//set admin
initOwner(guard.owner());
//safe check
uint256 price = underlyingPrice();
bool ye = app.IS_FLUX();
uint256 rate = getBorrowRate();
require(price > 0, "UNDERLYING_PRICE_IS_ZERO");
require(ye, "REQUIRE_FLUX");
require(rate > 0, "BORROW_RATE_IS_ZERO");
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override {
app.beforeTransferLP(address(this), from, to, amount);
}
function _afterTokenTransfer(
address from,
address to,
uint256
) internal override {
if (from != address(0)) {
_updateJoinStatus(from);
}
if (to != address(0)) {
_updateJoinStatus(to);
}
}
/**
@dev 允许为每个市场设置不同的价格预言机,以便从不同的数据源中获取价格。比如 MoonDex,Chainlink.
*/
function changeOracle(IPriceOracle oracle_) external onlyOwner {
emit ChangeOracle(oracle, oracle_);
oracle = oracle_;
//check
underlyingPrice();
}
/**
* @notice 获取该市场所拥有的标的资产余额(现金)
* @dev 仅仅是 fToken.balaceOf(借贷市场)
* @return 借贷市场合约所拥有的标的资产数量
*/
function cashPrior() public view virtual returns (uint256) {
return underlying.balanceOf(address(this));
}
function underlyingTransferIn(address sender, uint256 amount) internal virtual returns (uint256 actualAmount);
function underlyingTransferOut(address receipt, uint256 amount) internal virtual returns (uint256 actualAmount);
function getBorrowRate() internal view returns (uint256 rateMan) {
return interestRateModel.borrowRatePerSecond(cashPrior(), totalBorrows, taxBalance);
}
// -------------------------借贷业务 -------------------------
/**
@dev 复利计算
*/
function calcCompoundInterest() public virtual {
// 区块间隔 times = 当前区块时间 block.timestarp - 最后一次计息时间 lastAccrueInterest
// 区间借款利率 rate = 区间间隔 times * 单区块借款利率 blockBorrowRate
// 总借款 totalBorrows = 总借款 totalBorrows + 借款利息
// = totalBorrows + totalBorrows * 利率 rate
uint256 currentNumber = block.timestamp;
uint256 times = currentNumber.sub(lastAccrueInterest);
// 一个区块仅允许更新一次
if (times == 0) {
return;
}
uint256 oldBorrows = totalBorrows;
uint256 reserves = taxBalance;
//执行利率模型的 execute
interestRateModel.execute(cashPrior(), oldBorrows, reserves);
Exp memory rate = Exp(getBorrowRate()).mulScalar(times);
uint256 oldIndex = interestIndex;
uint256 interest = rate.mulScalarTruncate(oldBorrows);
//收取借款利息税
uint256 taxRate = getTaxRate();
taxBalance = reserves.add(interest.mul(taxRate).div(1e18));
totalBorrows = oldBorrows.add(rate.mulScalarTruncate(oldBorrows));
interestIndex = oldIndex.add(rate.mulScalarTruncate(oldIndex));
lastAccrueInterest = currentNumber;
}
function getTaxRate() public view returns (uint256 taxRate) {
string memory key = string(abi.encodePacked("TAX_RATE_", _symbol));
taxRate = app.configs(key);
if (taxRate == 0) {
taxRate = app.configs(CONFIG_TAX_RATE);
}
}
function _supply(address minter, uint256 ctokens) internal nonReentrant {
require(borrowBalanceOf(minter) == 0, "YOU_HAVE_BORROW");
require(ctokens > 0, "SUPPLY_IS_ZERO");
calcCompoundInterest();
// / 风控检查
app.beforeSupply(minter, address(this), ctokens);
require(underlyingTransferIn(msg.sender, ctokens) == ctokens, "TRANSFER_INVLIAD_AMOUNT");
_mintStorage(minter, ctokens);
}
function _mintStorage(address minter, uint256 ctokens) private {
Exp memory exchangeRate = Exp(_exchangeRate(ctokens));
require(!exchangeRate.isZero(), "EXCHANGERATE_IS_ZERO");
uint256 ftokens = Exponential.divScalarByExpTruncate(ctokens, exchangeRate);
ftokens = ftokens == 0 && ctokens > 0 ? 1 : ftokens;
_mint(minter, ftokens);
emit Supply(minter, ctokens, ftokens, balanceOf(minter));
}
/**
@notice 取款(兑换标的资产)
@dev 放贷人将其账户下 将 `amount` 量的资产提现 ,并转给指定的接受者 *recevier* ,
但需要确保待兑换的 fToken 充足,不可透支,账户总借款抵押率不能低于 110% 。
@param amount 待用于兑换标的资产的 ftoken 数量
@param isWithdraw 表示是否是提现,提现将有更多检查
@return actual 成功时返回成功兑换的标的资产数量。
*/
function _redeem(
address redeemer,
address to,
uint256 amount,
bool isWithdraw
) internal nonReentrant returns (uint256 actual) {
calcCompoundInterest();
uint256 ftokens;
uint256 ctokenAmount;
Exp memory exchangeRate = Exp(exchangeRate());
require(!exchangeRate.isZero(), "EXCHANGERATE_IS_ZERO");
//当为外部提现时,amount 表示要提现的资产数量,需要计算对于的 ftoken 数量
//但当 amount==0 时需要根据 ftoken 计算
if (isWithdraw && amount > 0) {
ctokenAmount = amount;
ftokens = Exponential.divScalarByExpTruncate(ctokenAmount, exchangeRate);
ftokens = ftokens == 0 && ctokenAmount > 0 ? 1 : ftokens; //弥补精度缺失
} else {
// amount 为 0 表示提现全部
ftokens = amount == 0 ? balanceOf(redeemer) : amount;
ctokenAmount = exchangeRate.mulScalarTruncate(ftokens);
ctokenAmount = ftokens > 0 && ctokenAmount == 0 ? 1 : ctokenAmount; //弥补精度缺失
}
//检查该市场是否有足够的现金供使用
// 更新
_burn(redeemer, ftokens, isWithdraw);
require(underlyingTransferOut(to, ctokenAmount) == ctokenAmount, "INVALID_TRANSFER_OUT");
//风控检查
//取款则销毁ftoken, ftoken 已被兑换成 ctoken
emit Redeem(redeemer, "", ftokens, ctokenAmount);
return ctokenAmount;
}
/**
@dev 借入标的资产,借款必须有足够的资产进行抵押
*/
function _borrow(address to, uint256 ctokens) internal nonReentrant {
address borrower = msg.sender;
require(balanceOf(borrower) == 0, "YOUR_HAVE_SUPPLY");
calcCompoundInterest();
// 为了避免出现资产价值用整数表达时归零的问题,而做出的借款限制
require(ctokens >= 10**(uint256((_decimals * 2) / 5 + 1)), "BORROWS_TOO_SMALL");
//检查市场是否有足够的现金供借出
// require(cashPrior() >= ctokens, "Marekt: Insufficient cash available"); //skip: transfer token will be check
// 风控检查
app.beforeBorrow(borrower, address(this), ctokens);
/**
更新当前借款
borrows= borrowBalanceOf(borrower) + ctokens;
totalBorrows += ctokens;
*/
totalBorrows = totalBorrows.add(ctokens);
uint256 borrowsNew = borrowBalanceOf(borrower).add(ctokens);
_borrowStorage(borrower, borrowsNew);
//转账
require(underlyingTransferOut(to, ctokens) == ctokens, "INVALID_TRANSFER_OUT");
emit Borrow(borrower, "", ctokens, borrowsNew, totalBorrows);
}
function _repay(address repayer, uint256 ctokens) internal {
// guard by _repayFor
_repayFor(repayer, repayer, ctokens);
}
/**
@notice 还款
@dev 借款人偿还本息,多余还款将作为存款存入市场。
@param repayer 还款人
@param borrower 借款人
@param ctokens 还款的标的资产数量
*/
function _repayFor(
address repayer,
address borrower,
uint256 ctokens
) internal nonReentrant {
calcCompoundInterest();
// 风控检查
app.beforeRepay(repayer, address(this), ctokens);
require(_repayBorrows(repayer, borrower, ctokens) > 0, "REPAY_IS_ZERO");
}
/// @dev 任何人均可帮助借款人还款,还款剩余部分转入还款人名下
function _repayBorrows(
address repayer,
address borrower,
uint256 repays
) private returns (uint256 actualRepays) {
uint256 borrowsOld = borrowBalanceOf(borrower);
if (borrowsOld == 0) {
return 0;
}
if (repays == 0) {
repays = actualRepays = borrowsOld;
} else {
actualRepays = SafeMath.min(repays, borrowsOld);
}
// 转移资产
require(underlyingTransferIn(repayer, actualRepays) == actualRepays, "TRANSFER_INVLIAD_AMOUNT");
//更新
totalBorrows = totalBorrows.sub(actualRepays);
uint256 borrowsNew = borrowsOld - actualRepays;
_borrowStorage(borrower, borrowsNew);
emit Repay(borrower, actualRepays, borrowsNew, totalBorrows);
}
///@dev 更新借款信息
function _borrowStorage(address borrower, uint256 borrowsNew) private {
if (borrowsNew == 0) {
delete userFounds[borrower];
return;
}
CheckPoint storage user = userFounds[borrower];
user.interestIndex = interestIndex;
user.borrows = borrowsNew;
_updateJoinStatus(borrower);
}
function liquidatePrepare(address borrower)
external
returns (
IERC20 asset,
uint256 ftokens,
uint256 borrows
)
{
calcCompoundInterest();
asset = underlying;
ftokens = balanceOf(borrower);
borrows = borrowBalanceOf(borrower);
}
/**
* @notice 清算账户资产
* @param liquidator 清算人
* @param borrower 借款人
* @param feeCollector 清算收费员
* @param feeRate 清算费率
*/
function liquidate(
address liquidator,
address borrower,
address feeCollector,
uint256 feeRate
) external returns (bool ok) {
address guardAddr = address(guard);
require(msg.sender == guardAddr, "LIQUIDATE_INVALID_CALLER");
require(liquidator != borrower, "LIQUIDATE_DISABLE_YOURSELF");
calcCompoundInterest();
uint256 ftokens = balanceOf(borrower);
uint256 borrows = borrowBalanceOf(borrower);
//偿还借款
if (borrows > 0) {
require(underlyingTransferIn(msg.sender, borrows) == borrows, "TRANSFER_INVLIAD_AMOUNT");
totalBorrows = totalBorrows.sub(borrows);
_borrowStorage(borrower, 0);
}
//获得抵押品
uint256 supplies;
if (ftokens > 0) {
require(feeRate <= MAX_LIQUIDATE_FEERATE, "INVALID_FEERATE");
Exp memory exchangeRate = Exp(exchangeRate());
supplies = exchangeRate.mulScalarTruncate(ftokens);
require(cashPrior() >= supplies, "MARKET_CASH_INSUFFICIENT");
_burn(borrower, ftokens, false);
uint256 fee = supplies.mul(feeRate).div(1e18);
underlyingTransferOut(liquidator, supplies.sub(fee)); //剩余归清算人
if (fee > 0) {
if (feeCollector != address(0)) {
uint256 feeHalf = fee / 2;
underlyingTransferOut(feeCollector, fee - feeHalf); //一半手续费归Flux 团队
underlyingTransferOut(guardAddr, feeHalf); //一半手续费用于穿仓清算备用
} else {
underlyingTransferOut(guardAddr, fee); //手续费用于穿仓清算
}
}
}
emit Liquidated(liquidator, borrower, supplies, borrows);
return true;
}
/**
@notice 穿仓清算
@dev 当穿仓时Flux将在交易所中卖出用户所有资产,以便偿还借款。注意,只有 Flux 合约才有权限执行操作。
*/
function killLoan(address borrower) external returns (uint256 supplies, uint256 borrows) {
address guardAddr = address(guard);
//只能由Guard执行
require(msg.sender == guardAddr, "MARGINCALL_INVALID_CALLER");
require(guardAddr != borrower, "DISABLE_KILL_GURAD");
//计息
calcCompoundInterest();
//没收全部存款到Guard名下
uint256 ftokens = balanceOf(borrower);
app.beforeLiquidate(msg.sender, borrower, ftokens);
if (ftokens > 0) {
Exp memory exchangeRate = Exp(exchangeRate());
supplies = exchangeRate.mulScalarTruncate(ftokens);
//潜在风险,资金池借空无法提现
uint256 cash = cashPrior();
if (cash < supplies) {
//将存款凭证转移给 Guard
_transfer(borrower, guardAddr, ftokens, false);
} else {
_burn(borrower, ftokens, false);
underlyingTransferOut(guardAddr, supplies); //迁移至清算合约
}
}
// 将借款转移到Guard名下
borrows = borrowBalanceOf(borrower);
if (borrows > 0) {
_borrowStorage(borrower, 0); // 转移到 Gurad 名下
_borrowStorage(guardAddr, borrowBalanceOf(guardAddr).add(borrows));
}
if (borrows > 0 || supplies > 0) {
emit Liquidated(guardAddr, borrower, supplies, borrows);
}
}
///@dev 实时更新账户在各借贷市场的进出情况,如果更新时机不正确,会影响账户借贷资产的统计
function _updateJoinStatus(address acct) internal {
app.setAcctMarket(acct, balanceOf(acct) > 0 || borrowBalanceOf(acct) > 0);
}
// ------------------------- 借贷业务 end-------------------------
/**
@notice 获取该市场的借贷利率
@return borrowRate 借款年利率(尾数)
@return supplyRate 存款年利率(尾数)
@return utilizationRate 资金使用率(尾数)
*/
function getAPY()
external
view
returns (
uint256 borrowRate,
uint256 supplyRate,
uint256 utilizationRate
)
{
uint256 taxRate = getTaxRate();
uint256 balance = cashPrior();
borrowRate = interestRateModel.borrowRatePerSecond(balance, totalBorrows, taxBalance) * (365 days);
supplyRate = interestRateModel.supplyRatePerSecond(balance, totalSupply(), totalBorrows, taxBalance, taxRate) * (365 days);
utilizationRate = interestRateModel.utilizationRate(balance, totalBorrows, taxBalance);
}
// 各类系数计算
/**
* @notice 获取 fToken 与标的资产 cToken 的兑换汇率
* @dev fToken 的兑换率等于(总现金+ 总借款 - 总储备金) / 总fToken代币 == ( totalCash + totalBorrows - totalReservers )/ totalSupply
* @return (exchangeRateMan)
*/
function exchangeRate() public view virtual returns (uint256) {
return _exchangeRate(0);
}
/**
@dev 允许调整cash数量,因为一些操作时实际上 cash 或 supply 已不精准,需要调整。
*/
function _exchangeRate(uint256 ctokens) private view returns (uint256) {
uint256 totalSupply_ = totalSupply();
if (totalSupply_ == 0) {
// 尚未供给时,兑换汇率为初始默认汇率
return initialExchangeRateMan;
}
//汇率
//= cToken量 / fToken量
//=(总现金+ 总借款 - 总储备金 - 利息税) / 总fToken代币
//= ( totalCash + totalBorrows - totalReservers -taxBalance )/ totalSupply
uint256 totalCash = cashPrior();
totalCash = totalCash.sub(ctokens);
uint256 cTokenAmount = totalCash.add(totalBorrows).sub(taxBalance);
uint256 rate = Exponential.get(cTokenAmount, totalSupply_).mantissa;
if (rate == 0) {
return initialExchangeRateMan;
}
return rate;
}
/**
@notice 查询账户借款数量
@param acct 需要查询的账户地址
@return uint256 账户下的标的资产借款数量,包括应付利息
*/
function borrowBalanceOf(address acct) public view returns (uint256) {
/**
借款本息
= 当前本息 * 复利
= borrower.borrows* ( interestIndex/borrower.interestIndex)
*/
CheckPoint storage borrower = userFounds[acct];
uint256 borrows = borrower.borrows;
if (borrows == 0) {
return 0;
}
uint256 index = borrower.interestIndex;
if (index == 0) {
return borrows;
}
Exp memory rate = Exponential.get(interestIndex, index);
return rate.mulScalarTruncate(borrows);
}
/**
@notice 获取账户借贷信息快照
@param acct 待查询的账户地址
@return ftokens 存款余额
@return borrows 借款余额,含利息
@return xrate 汇率
*/
function getAcctSnapshot(address acct)
external
view
returns (
uint256 ftokens,
uint256 borrows,
uint256 xrate
)
{
return (balanceOf(acct), borrowBalanceOf(acct), exchangeRate());
}
/**
@dev 用于复杂计算时的数据存储
*/
struct CalcVars {
uint256 supplies;
uint256 borrows;
uint256 priceMan;
Exp borrowLimit;
Exp supplyValue;
Exp borrowValue;
}
/**
@notice 计算账户借贷资产信息
@dev 通过提供多个参数来灵活的计算账户的借贷时的资产变动信息,比如可以查询出账户如果继续借入 200 个 FC 后的借贷情况。
@param acct 待查询账户
@param collRatioMan 计算时使用的借款抵押率
@param addBorrows 计算时需要增加的借款数量
@param subSupplies 计算时需要减少的存款数量
@return supplyValueMan 存款额(尾数)
@return borrowValueMan 借款额(尾数)
@return borrowLimitMan 借款所需抵押额(尾数)
*/
function accountValues(
address acct,
uint256 collRatioMan,
uint256 addBorrows,
uint256 subSupplies
)
external
view
returns (
uint256 supplyValueMan,
uint256 borrowValueMan,
uint256 borrowLimitMan
)
{
CalcVars memory vars;
// 存款 = 当前存款 - subSupplies
vars.supplies = balanceOf(acct).sub(subSupplies, "TOKEN_INSUFFICIENT_BALANCE");
// 借款数 = 当前借款 + addBorrows
vars.borrows = borrowBalanceOf(acct).add(addBorrows);
if (vars.supplies == 0 && vars.borrows == 0) {
return (0, 0, 0);
}
// 自此的价格是 一个币的价格,比如 1 FC ,
// 但下面计算时 存款量/借款量 都是最小精度表达的。
// 因此,计算时需要除以 10^decimals 。
vars.priceMan = underlyingPrice();
require(vars.priceMan > 0, "MARKET_ZERO_PRICE");
if (vars.supplies > 0) {
// 存款市值 = 汇率 * 存款量 * 价格
// supplyValue = exchangeRate * supplies * price
// supplyValue * 1e18 = 1e18 * exchangeRate/1e18 * supplies/10^_decimals * price/1e18
// = exchangeRate * supplies * price/(10^(18+_decimals) )
supplyValueMan = exchangeRate().mul(vars.supplies).mul(vars.priceMan).div(10**(18 + uint256(_decimals)));
//借款限额 = 存款市值 / 抵
borrowLimitMan = supplyValueMan.mul(1e18).div(collRatioMan);
}
if (vars.borrows > 0) {
// 借款市值 = 借款量 * 价格
// borrowValue = borrows * price
borrowValueMan = vars.priceMan.mul(vars.borrows).div(10**uint256(_decimals));
}
}
function underlyingPrice() public view returns (uint256) {
return oracle.getPriceMan(address(underlying));
}
function isFluxMarket() external pure returns (bool) {
return true;
}
function borrowAmount(address acct) external view returns (uint256) {
return userFounds[acct].borrows;
}
/**
@notice 任意账户可以执行提取利差到团队收益账户
*/
function withdrawTax() external {
address receiver = app.getFluxTeamIncomeAddress();
require(receiver != address(0), "RECEIVER_IS_EMPTY");
uint256 tax = taxBalance; //save gas
require(tax > 0, "TAX_IS_ZERO");
taxBalance = 0;
require(underlyingTransferOut(receiver, tax) == tax, "TAX_TRANSFER_FAILED");
}
function enableCross(address fluxCrossHandler) external onlyOwner {
fluxCross = fluxCrossHandler; //ignore event
}
/**
* @notice 跨链调仓
* @dev 允许将资产从跨链提取到其他链中
* @param tragetChainId 目标链ID
* @param amount 跨链调仓 token 数量
* @param maxFluxFee 跨链调仓支付的FLUX手续费最大数量
*/
function crossRefinance(
uint64 tragetChainId,
uint256 amount,
uint256 maxFluxFee
) external payable {
address cross = fluxCross;
require(cross != address(0), "CROSS_NOT_READY");
_redeem(msg.sender, cross, amount, true);
IFluxCross(cross).deposit{ value: msg.value }(tragetChainId, msg.sender, address(underlying), amount, maxFluxFee);
}
function crossRedeem(
uint64 tragetChainId,
uint256 amount,
uint256 maxFluxFee
) external payable {
address cross = fluxCross;
require(cross != address(0), "CROSS_NOT_READY");
_redeem(msg.sender, cross, amount, true);
IFluxCross(cross).withdraw{ value: msg.value }(tragetChainId, msg.sender, address(underlying), amount, maxFluxFee);
}
function crossBorrow(
uint64 tragetChainId,
uint256 amount,
uint256 maxFluxFee
) external payable {
address cross = fluxCross;
require(cross != address(0), "CROSS_NOT_READY");
_borrow(cross, amount);
IFluxCross(cross).withdraw{ value: msg.value }(tragetChainId, msg.sender, address(underlying), amount, maxFluxFee);
}
}
|
获取该市场所拥有的标的资产余额(现金) 仅仅是 fToken.balaceOf(借贷市场) return 借贷市场合约所拥有的标的资产数量/
|
function cashPrior() public view virtual returns (uint256) {
return underlying.balanceOf(address(this));
}
| 13,049,907 |
pragma solidity ^0.8.0;
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
// File: @openzeppelin/contracts/token/ERC21/IERC20.sol
// 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);
}
pragma solidity ^0.8.0;
/**
* @dev A token holder contract that will allow a beneficiary to extract the
* tokens after a given release time - the amount of coin allowed to be recovered
* is proportional to the time taken.
*
* This contract will be used to lock up 40% of minted ChowCoin (40 million coins)
* over the course of 40 months specified in 30 day increments. Calling the release
* method will recover the total number of available tokens after the given time period
* and transfer the tokens back into the minting account.
*/
contract EATTokenLockup {
// ERC20 basic token contract being held
IERC20 immutable private _token;
// beneficiary of tokens after they are released
address immutable private _beneficiary;
// time in seconds that the lockup should occur for
uint256 immutable private _totalLockupDuration;
// total number of increments of coin that should be released by
uint256 immutable private _totalIncrements;
// total number of tokens saved at this address
uint256 immutable private _totalNumTokens;
// start time of the lockup in epoch seconds
uint256 immutable private _startTime;
constructor (IERC20 token_, uint256 duration_, uint256 increments_, uint256 numTokens_) {
_token = token_;
_beneficiary = msg.sender;
_totalLockupDuration = duration_;
_totalIncrements = increments_;
_totalNumTokens = numTokens_;
_startTime = block.timestamp;
}
/**
* @return the token being held.
*/
function token() public view virtual returns (IERC20) {
return _token;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view virtual returns (address) {
return _beneficiary;
}
/**
* @return the total duration of the lockup in seconds
*/
function duration() public view virtual returns (uint256) {
return _totalLockupDuration;
}
/**
* @return the total remaining time for the lockup
*/
function remainingDuration() public view virtual returns (uint256) {
require(block.timestamp <= _startTime + _totalLockupDuration, "EATTokenLockup: all tokens are avilable for release");
return _startTime + _totalLockupDuration - block.timestamp;
}
/**
* @return the total number of tokens available for release.
*/
function numReleasableTokens() public view virtual returns (uint256) {
uint256 timeIncrementSize = _totalLockupDuration / _totalIncrements;
uint256 timeDuration = block.timestamp - _startTime;
uint256 numTokensInIncrement = _totalNumTokens / _totalIncrements;
uint256 incrementsAvailable = Math.min256(timeDuration / timeIncrementSize, _totalIncrements);
uint256 maxNumTokensAvailable = incrementsAvailable * numTokensInIncrement;
uint256 numTokensReleased = _totalNumTokens - remainingTokens();
uint256 numTokensAvailable = maxNumTokensAvailable - numTokensReleased;
return numTokensAvailable;
}
/**
* @return the total number of increments in which coins are released
*/
function increments() public view virtual returns (uint256) {
return _totalIncrements;
}
/**
* @return the total remaining coins held within the lockup
*/
function remainingTokens() public view virtual returns (uint256) {
return _token.balanceOf(address(this));
}
/**
* @return the total remaining coins held within the lockup
*/
function tokensReleased() public view virtual returns (uint256) {
return _totalNumTokens - _token.balanceOf(address(this));
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public virtual {
uint256 amount = token().balanceOf(address(this));
require(amount > 0, "EATTokenLockup: no tokens remaining to release");
// solhint-disable-next-line not-rely-on-time
uint256 numTokensAvailable = numReleasableTokens();
require(amount >= numTokensAvailable, "EATTokenLockup: not enough tokens available");
token().transfer(beneficiary(), numTokensAvailable);
}
}
|
return the total remaining coins held within the lockup/
|
function tokensReleased() public view virtual returns (uint256) {
return _totalNumTokens - _token.balanceOf(address(this));
}
| 57,193 |
pragma solidity ^0.4.18;
// Etheremon ERC721
// copyright [email protected]
contract SafeMath {
/* function assert(bool assertion) internal { */
/* if (!assertion) { */
/* throw; */
/* } */
/* } // assert no longer needed once solidity is on 0.4.10 */
function safeAdd(uint256 x, uint256 y) pure internal returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) pure internal returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) pure internal returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
}
contract BasicAccessControl {
address public owner;
// address[] public moderators;
uint16 public totalModerators = 0;
mapping (address => bool) public moderators;
bool public isMaintaining = true;
function BasicAccessControl() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyModerators() {
require(moderators[msg.sender] == true);
_;
}
modifier isActive {
require(!isMaintaining);
_;
}
function ChangeOwner(address _newOwner) onlyOwner public {
if (_newOwner != address(0)) {
owner = _newOwner;
}
}
function AddModerator(address _newModerator) onlyOwner public {
if (moderators[_newModerator] == false) {
moderators[_newModerator] = true;
totalModerators += 1;
}
}
function RemoveModerator(address _oldModerator) onlyOwner public {
if (moderators[_oldModerator] == true) {
moderators[_oldModerator] = false;
totalModerators -= 1;
}
}
function UpdateMaintaining(bool _isMaintaining) onlyOwner public {
isMaintaining = _isMaintaining;
}
}
contract EtheremonEnum {
enum ResultCode {
SUCCESS,
ERROR_CLASS_NOT_FOUND,
ERROR_LOW_BALANCE,
ERROR_SEND_FAIL,
ERROR_NOT_TRAINER,
ERROR_NOT_ENOUGH_MONEY,
ERROR_INVALID_AMOUNT
}
enum ArrayType {
CLASS_TYPE,
STAT_STEP,
STAT_START,
STAT_BASE,
OBJ_SKILL
}
enum PropertyType {
ANCESTOR,
XFACTOR
}
}
contract EtheremonDataBase is EtheremonEnum, BasicAccessControl, SafeMath {
uint64 public totalMonster;
uint32 public totalClass;
// write
function withdrawEther(address _sendTo, uint _amount) onlyOwner public returns(ResultCode);
function addElementToArrayType(ArrayType _type, uint64 _id, uint8 _value) onlyModerators public returns(uint);
function updateIndexOfArrayType(ArrayType _type, uint64 _id, uint _index, uint8 _value) onlyModerators public returns(uint);
function setMonsterClass(uint32 _classId, uint256 _price, uint256 _returnPrice, bool _catchable) onlyModerators public returns(uint32);
function addMonsterObj(uint32 _classId, address _trainer, string _name) onlyModerators public returns(uint64);
function setMonsterObj(uint64 _objId, string _name, uint32 _exp, uint32 _createIndex, uint32 _lastClaimIndex) onlyModerators public;
function increaseMonsterExp(uint64 _objId, uint32 amount) onlyModerators public;
function decreaseMonsterExp(uint64 _objId, uint32 amount) onlyModerators public;
function removeMonsterIdMapping(address _trainer, uint64 _monsterId) onlyModerators public;
function addMonsterIdMapping(address _trainer, uint64 _monsterId) onlyModerators public;
function clearMonsterReturnBalance(uint64 _monsterId) onlyModerators public returns(uint256 amount);
function collectAllReturnBalance(address _trainer) onlyModerators public returns(uint256 amount);
function transferMonster(address _from, address _to, uint64 _monsterId) onlyModerators public returns(ResultCode);
function addExtraBalance(address _trainer, uint256 _amount) onlyModerators public returns(uint256);
function deductExtraBalance(address _trainer, uint256 _amount) onlyModerators public returns(uint256);
function setExtraBalance(address _trainer, uint256 _amount) onlyModerators public;
// read
function getSizeArrayType(ArrayType _type, uint64 _id) constant public returns(uint);
function getElementInArrayType(ArrayType _type, uint64 _id, uint _index) constant public returns(uint8);
function getMonsterClass(uint32 _classId) constant public returns(uint32 classId, uint256 price, uint256 returnPrice, uint32 total, bool catchable);
function getMonsterObj(uint64 _objId) constant public returns(uint64 objId, uint32 classId, address trainer, uint32 exp, uint32 createIndex, uint32 lastClaimIndex, uint createTime);
function getMonsterName(uint64 _objId) constant public returns(string name);
function getExtraBalance(address _trainer) constant public returns(uint256);
function getMonsterDexSize(address _trainer) constant public returns(uint);
function getMonsterObjId(address _trainer, uint index) constant public returns(uint64);
function getExpectedBalance(address _trainer) constant public returns(uint256);
function getMonsterReturn(uint64 _objId) constant public returns(uint256 current, uint256 total);
}
interface EtheremonBattle {
function isOnBattle(uint64 _objId) constant external returns(bool);
}
interface EtheremonTradeInterface {
function isOnTrading(uint64 _objId) constant external returns(bool);
}
contract ERC721 {
// ERC20 compatible functions
// function name() constant returns (string name);
// function symbol() constant returns (string symbol);
function totalSupply() public constant returns (uint256 supply);
function balanceOf(address _owner) public constant returns (uint256 balance);
// Functions that define ownership
function ownerOf(uint256 _tokenId) public constant returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function takeOwnership(uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint tokenId);
// Token metadata
//function tokenMetadata(uint256 _tokenId) constant returns (string infoUrl);
// Events
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
}
contract EtheremonAsset is BasicAccessControl, ERC721 {
string public constant name = "EtheremonAsset";
string public constant symbol = "EMONA";
mapping (address => mapping (uint256 => address)) public allowed;
// data contract
address public dataContract;
address public battleContract;
address public tradeContract;
// helper struct
struct MonsterClassAcc {
uint32 classId;
uint256 price;
uint256 returnPrice;
uint32 total;
bool catchable;
}
struct MonsterObjAcc {
uint64 monsterId;
uint32 classId;
address trainer;
string name;
uint32 exp;
uint32 createIndex;
uint32 lastClaimIndex;
uint createTime;
}
// modifier
modifier requireDataContract {
require(dataContract != address(0));
_;
}
modifier requireBattleContract {
require(battleContract != address(0));
_;
}
modifier requireTradeContract {
require(tradeContract != address(0));
_;
}
function EtheremonAsset(address _dataContract, address _battleContract, address _tradeContract) public {
dataContract = _dataContract;
battleContract = _battleContract;
tradeContract = _tradeContract;
}
function setContract(address _dataContract, address _battleContract, address _tradeContract) onlyModerators external {
dataContract = _dataContract;
battleContract = _battleContract;
tradeContract = _tradeContract;
}
// public
function totalSupply() public constant requireDataContract returns (uint256 supply){
EtheremonDataBase data = EtheremonDataBase(dataContract);
return data.totalMonster();
}
function balanceOf(address _owner) public constant requireDataContract returns (uint balance) {
EtheremonDataBase data = EtheremonDataBase(dataContract);
return data.getMonsterDexSize(_owner);
}
function ownerOf(uint256 _tokenId) public constant requireDataContract returns (address owner) {
EtheremonDataBase data = EtheremonDataBase(dataContract);
MonsterObjAcc memory obj;
(obj.monsterId, obj.classId, obj.trainer, obj.exp, obj.createIndex, obj.lastClaimIndex, obj.createTime) = data.getMonsterObj(uint64(_tokenId));
require(obj.monsterId == uint64(_tokenId));
return obj.trainer;
}
function isApprovable(address _owner, uint256 _tokenId) public constant requireDataContract requireBattleContract requireTradeContract returns(bool) {
EtheremonDataBase data = EtheremonDataBase(dataContract);
MonsterObjAcc memory obj;
(obj.monsterId, obj.classId, obj.trainer, obj.exp, obj.createIndex, obj.lastClaimIndex, obj.createTime) = data.getMonsterObj(uint64(_tokenId));
if (obj.monsterId != uint64(_tokenId))
return false;
if (obj.trainer != _owner)
return false;
// check battle & trade contract
EtheremonBattle battle = EtheremonBattle(battleContract);
EtheremonTradeInterface trade = EtheremonTradeInterface(tradeContract);
return (!battle.isOnBattle(obj.monsterId) && !trade.isOnTrading(obj.monsterId));
}
function approve(address _to, uint256 _tokenId) requireBattleContract requireTradeContract isActive external {
EtheremonDataBase data = EtheremonDataBase(dataContract);
MonsterObjAcc memory obj;
(obj.monsterId, obj.classId, obj.trainer, obj.exp, obj.createIndex, obj.lastClaimIndex, obj.createTime) = data.getMonsterObj(uint64(_tokenId));
require(obj.monsterId == uint64(_tokenId));
require(msg.sender == obj.trainer);
require(msg.sender != _to);
// check battle & trade contract
EtheremonBattle battle = EtheremonBattle(battleContract);
EtheremonTradeInterface trade = EtheremonTradeInterface(tradeContract);
if (battle.isOnBattle(obj.monsterId) || trade.isOnTrading(obj.monsterId))
revert();
allowed[msg.sender][_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
function takeOwnership(uint256 _tokenId) requireDataContract requireBattleContract requireTradeContract isActive external {
EtheremonDataBase data = EtheremonDataBase(dataContract);
MonsterObjAcc memory obj;
(obj.monsterId, obj.classId, obj.trainer, obj.exp, obj.createIndex, obj.lastClaimIndex, obj.createTime) = data.getMonsterObj(uint64(_tokenId));
require(obj.monsterId == uint64(_tokenId));
require(msg.sender != obj.trainer);
require(allowed[obj.trainer][_tokenId] == msg.sender);
// check battle & trade contract
EtheremonBattle battle = EtheremonBattle(battleContract);
EtheremonTradeInterface trade = EtheremonTradeInterface(tradeContract);
if (battle.isOnBattle(obj.monsterId) || trade.isOnTrading(obj.monsterId))
revert();
// remove allowed
allowed[obj.trainer][_tokenId] = address(0);
// transfer owner
data.removeMonsterIdMapping(obj.trainer, obj.monsterId);
data.addMonsterIdMapping(msg.sender, obj.monsterId);
Transfer(obj.trainer, msg.sender, _tokenId);
}
function transfer(address _to, uint256 _tokenId) requireDataContract isActive external {
EtheremonDataBase data = EtheremonDataBase(dataContract);
MonsterObjAcc memory obj;
(obj.monsterId, obj.classId, obj.trainer, obj.exp, obj.createIndex, obj.lastClaimIndex, obj.createTime) = data.getMonsterObj(uint64(_tokenId));
require(obj.monsterId == uint64(_tokenId));
require(obj.trainer == msg.sender);
require(msg.sender != _to);
require(_to != address(0));
// check battle & trade contract
EtheremonBattle battle = EtheremonBattle(battleContract);
EtheremonTradeInterface trade = EtheremonTradeInterface(tradeContract);
if (battle.isOnBattle(obj.monsterId) || trade.isOnTrading(obj.monsterId))
revert();
// remove allowed
allowed[obj.trainer][_tokenId] = address(0);
// transfer owner
data.removeMonsterIdMapping(obj.trainer, obj.monsterId);
data.addMonsterIdMapping(_to, obj.monsterId);
Transfer(obj.trainer, _to, _tokenId);
}
function transferFrom(address _from, address _to, uint256 _tokenId) requireDataContract requireBattleContract requireTradeContract external {
EtheremonDataBase data = EtheremonDataBase(dataContract);
MonsterObjAcc memory obj;
(obj.monsterId, obj.classId, obj.trainer, obj.exp, obj.createIndex, obj.lastClaimIndex, obj.createTime) = data.getMonsterObj(uint64(_tokenId));
require(obj.monsterId == uint64(_tokenId));
require(obj.trainer == _from);
require(_to != address(0));
require(_to != _from);
require(allowed[_from][_tokenId] == msg.sender);
// check battle & trade contract
EtheremonBattle battle = EtheremonBattle(battleContract);
EtheremonTradeInterface trade = EtheremonTradeInterface(tradeContract);
if (battle.isOnBattle(obj.monsterId) || trade.isOnTrading(obj.monsterId))
revert();
// remove allowed
allowed[_from][_tokenId] = address(0);
// transfer owner
data.removeMonsterIdMapping(obj.trainer, obj.monsterId);
data.addMonsterIdMapping(_to, obj.monsterId);
Transfer(obj.trainer, _to, _tokenId);
}
function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant requireDataContract returns (uint tokenId) {
EtheremonDataBase data = EtheremonDataBase(dataContract);
return data.getMonsterObjId(_owner, _index);
}
}
|
function assert(bool assertion) internal { / if (!assertion) { / throw; / } /
|
function safeAdd(uint256 x, uint256 y) pure internal returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
| 360,946 |
./partial_match/1/0x22Df9DFc1E8FD71524381D23A16F3a90E431B8a0/sources/contracts/Token.sol
|
View the amount of dividend in wei that an address has earned in total. accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) = (magnifiedDividendPerShare balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude _owner The address of a token holder. return The amount of dividend in wei that `_owner` has earned in total.
|
function accumulativeDividendOf(
address _owner,
address _rewardToken
) public view override returns (uint256) {
return
magnifiedDividendPerShare[_rewardToken]
.mul(holderBalance[_owner])
.toInt256Safe()
.add(magnifiedDividendCorrections[_rewardToken][_owner])
.toUint256Safe() / magnitude;
}
| 4,125,584 |
./full_match/1/0x16945cD33CfF5F4f0b18bd6B397f95914724955a/sources/src/Kong/StakingToken.sol
|
Sets initial index _index Initial index
|
function setIndex(uint256 _index) external {
require(msg.sender == initializer, "Initializer: caller is not initializer");
require(INDEX == 0, "Cannot set INDEX again");
INDEX = gonsForBalance(_index);
}
| 4,927,849 |
./full_match/80001/0x841BeC97B1246663a8fB52A7148Fb3405a4880e7/sources/contracts/Workbench.sol
|
See IWorkbench/
|
function hashBlueprint(
uint256[] calldata inputIds,
uint256[] calldata inputAmounts,
uint256[] calldata outputIds,
uint256[] calldata outputAmounts
) public pure virtual override returns (uint256 blueprintId) {
return
uint256(
keccak256(
abi.encode(inputIds, inputAmounts, outputIds, outputAmounts)
)
);
}
| 5,620,471 |
pragma solidity ^0.4.18;
// COMP9900 Demo 2 Client
//
// Author: Yunqiu Xu
//
// [1] postRequest()
// [2] updateRequest(): update the modelAddr / modelTestResult / frelancerAddr
// [3] getRequestCount(): get the number of requests
// [4] getRequestByIndex() : get one request by its index (within this client)
// [4-1] Get visible part of request by index
// [4-2] Get invisible part of request by index (only when requestEnd = False can they be seen)
// Why divide these: too many variables will cause exception
// [5] closeRequest() : set requestEnd = True and perform transaction
// [6] depositToContract()
contract Client {
address private owner; // the owner of this contract owner = msg.sender = client
// event to view information from web3js
event RequestPosted(address _clientAddr, uint _requestClientIndex, string _requestName, string _requestDescriptionAddr, string _testCodeAddr, uint _reward, uint _threshold, uint256 _requestPostTime, bool _requestEnd);
event RequestUpdated(address _clientAddr, uint _requestClientIndex, uint _threshold, string _modelAddr, uint _testResult, address _freelancerAddr);
event RequestClosed(address _clientAddr, uint _requestClientIndex, bool _requestEnd, string _modelAddr, uint _testResult, address _freelancerAddr);
// Modifier, owner -> msg.sender -> client
modifier isOwner {
require(owner == msg.sender);
_;
}
function Client() public payable {
owner = msg.sender;
}
// A request's structure
struct Request {
string requestName; // the name of request
string requestDescriptionAddr; // the description
string testCodeAddr; // the test code (address)
uint reward; // the reward (ether)
uint threshold; // a threshold for test result, e.g. for accuracy 0.9500 --> threshold = 9500
uint256 requestPostTime; // different from model before, only postTime will be loded, and it will not be changed
bool requestEnd; // if true, perform transaction
string modelAddr; // the model to be submitted
uint testResult; // the test result to compare with threshold
address freelancerAddr; // the freelancer who posted "modelAddr" and get "testResult"
}
// Collect the requests for this client
Request[] public postedRequests;
// [1] Post a new request
// input: requestName, requestDescriptionAddr, testCodeAddr, reward, threshold, requestPostTime
// other initializations:
// requestEnd = false
// modelAddr = ''
// testResult = 0
// freelancerAddr = owner
function postRequest(string _requestName, string _requestDescriptionAddr, string _testCodeAddr, uint _reward, uint _threshold, uint256 _requestPostTime) public isOwner() {
// add a request
postedRequests.push(Request(_requestName, _requestDescriptionAddr, _testCodeAddr, _reward, _threshold, _requestPostTime, false, "", 0, owner));
// get its index within this client
uint requestClientIndex = getRequestCount() - 1;
// add event
RequestPosted(owner, requestClientIndex, _requestName, _requestDescriptionAddr, _testCodeAddr, _reward, _threshold, _requestPostTime, false);
}
// [2] Update a request
// This function will be called when a freelancer submit a model as well as its test result
// Input: requestClientIndex, newModelAddr, newTestResult, newFreelancerAddr
function updateRequest(uint _requestClientIndex, string _newModelAddr, uint _newTestResult, address _newFreelancerAddr) public isOwner() {
// check whether new test result is better than both threshold and result
// other wise no update will be performed
if (postedRequests[_requestClientIndex].threshold <= _newTestResult && postedRequests[_requestClientIndex].testResult <= _newTestResult) {
postedRequests[_requestClientIndex].modelAddr = _newModelAddr;
postedRequests[_requestClientIndex].testResult = _newTestResult;
postedRequests[_requestClientIndex].freelancerAddr = _newFreelancerAddr;
}
// add event
RequestUpdated(owner, _requestClientIndex, postedRequests[_requestClientIndex].threshold, postedRequests[_requestClientIndex].modelAddr, postedRequests[_requestClientIndex].testResult, postedRequests[_requestClientIndex].freelancerAddr);
}
// [3] get request count
function getRequestCount() view public returns(uint) {
return postedRequests.length;
}
// [4-1] Get visible part of request by index
function getRequestByIndexVisible(uint _requestClientIndex) view public returns(address, string, string, string, uint, uint, uint256) {
Request storage currentRequest = postedRequests[_requestClientIndex];
return (owner, currentRequest.requestName, currentRequest.requestDescriptionAddr, currentRequest.testCodeAddr, currentRequest.reward, currentRequest.threshold, currentRequest.requestPostTime);
}
// [4-2] Get invisible part of request by index
// Only when "requestEnd = true" can the other attibutes by invisible, otherwise we can only see "requestEnd = false"
function getRequestByIndexInvisible(uint _requestClientIndex) view public returns(address, bool, string, uint, address, uint) {
Request storage currentRequest = postedRequests[_requestClientIndex];
return (owner, currentRequest.requestEnd, currentRequest.modelAddr, currentRequest.testResult, currentRequest.freelancerAddr, _requestClientIndex);
}
// [5] closeRequest
// if client chooses to close this request, requestEnd will be set as "true" first
// if owner != freelancerAddr, then transfer the money: owner -> contract -> freelancer : the request is finished successfully
// if owner == freelancerAddr, then the money in contract goes back to client : no one satisfies the request
function closeRequest(uint _requestClientIndex) public isOwner() payable {
// close the request
postedRequests[_requestClientIndex].requestEnd = true;
// transfer the reward from this contract to freelancerAddr
postedRequests[_requestClientIndex].freelancerAddr.transfer(postedRequests[_requestClientIndex].reward);
// add the event
RequestClosed(owner, _requestClientIndex, postedRequests[_requestClientIndex].requestEnd, postedRequests[_requestClientIndex].modelAddr, postedRequests[_requestClientIndex].testResult, postedRequests[_requestClientIndex].freelancerAddr);
}
// [6] Client should deposit some money to this contract when posting a request
// E.g. if he posts 3 requests with reward 1,2,3, then the balance in this contract should be 6
function depositToContract() public payable {}
// Call back
function () public payable {}
}
|
[2] Update a request This function will be called when a freelancer submit a model as well as its test result Input: requestClientIndex, newModelAddr, newTestResult, newFreelancerAddr check whether new test result is better than both threshold and result other wise no update will be performed
|
function updateRequest(uint _requestClientIndex, string _newModelAddr, uint _newTestResult, address _newFreelancerAddr) public isOwner() {
if (postedRequests[_requestClientIndex].threshold <= _newTestResult && postedRequests[_requestClientIndex].testResult <= _newTestResult) {
postedRequests[_requestClientIndex].modelAddr = _newModelAddr;
postedRequests[_requestClientIndex].testResult = _newTestResult;
postedRequests[_requestClientIndex].freelancerAddr = _newFreelancerAddr;
}
}
| 12,964,948 |
pragma solidity >=0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
struct Airlines {
bool isRegistered;
address accountAddress;
string airlinesName;
uint insuranceFund;
}
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airlines;
string flightName;
}
struct Passenger {
address passengerAddress;
uint256 insuranceAmount;
}
// uint8 private constant STATUS_CODE_INSURED = 0;
// uint8 private constant STATUS_CODE_CREDITED = 1;
// uint8 private constant STATUS_CODE_WITHDRAWN = 2;
mapping(string => Flight) private flights;
//address[] registeredAirlineList = new address[](0);
mapping(address => Airlines) registeredAirlines;
mapping(address => Flight) registeredFlights;
//mapping(address => address[]) registrationAuthorizers; // Airlines that have authorized the registration
mapping(address => bool) authorizedCallers;
//mapping(bytes32 => mapping(address => uint256)) insuredPassengers;
mapping(bytes32 => Passenger) insuredPassengers;
mapping(bytes32 => address[]) insuredPassengerList;
mapping(bytes32 => uint256) creditedPassengers;
// Airlines[] registrationApprovedBy = new Airlines[](0);
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event RegisteredAirline(string name, address account);
event RegisteredFlight(string name, address account);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
string memory firstAirlines,
address firstAirlineAddress
)
public
{
contractOwner = tx.origin;
//authorizedCallers[contractOwner] = 1;
operational = true;
// registeredAirlineList.push(firstAirlineAddress);
registeredAirlines[firstAirlineAddress] = Airlines({
isRegistered: true,
accountAddress: firstAirlineAddress,
airlinesName: firstAirlines,
insuranceFund: 0
});
// emit RegisteredAirline( firstAirlines, firstAirlineAddress); // First airline registered
}
/********************************************************************************************/
/* 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(tx.origin == contractOwner, "Caller is not contract owner");
_;
}
// modifier requireAlreadyNotRegistered(address newAirlines)
// {
// require(!registeredAirlines[newAirlines].isRegistered, "Airlines is already registered" );
// _;
// }
modifier requireAuthorizedCaller()
{
require(authorizedCallers[msg.sender] == true , "Authorized caller" );
_;
}
modifier requireMinimumFund(uint amount)
{
require(msg.value >= amount, "Minimum amount is needed");
_;
}
modifier requireRegisteredAirline(address airlines)
{
require(registeredAirlines[airlines].isRegistered, "Airlines is not registered" );
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
//function addAddress(address authadd ) public {authorizedCallers[authadd] = true;}
function authorizeCaller(address authCaller ) public requireContractOwner
{
authorizedCallers[authCaller] = true;
}
function deauthorizeCaller
(
address authCaller
)
public
requireContractOwner
{
delete authorizedCallers[authCaller];
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
external
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
requireAuthorizedCaller
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
function getRegisteredAirlineFund(address airline ) external view requireAuthorizedCaller returns (uint){
return registeredAirlines[airline].insuranceFund;
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
string airlinesName,
address newAirlines // airlines that needs to be registered
)
external
requireIsOperational
requireAuthorizedCaller
// requireAlreadyNotRegistered (newAirlines) // require airlines is not already registered
// returns( int votesNeeded)
{
// registeredAirlineList.push(newAirlines);
registeredAirlines[newAirlines] = Airlines({
isRegistered: true,
accountAddress: newAirlines,
airlinesName: airlinesName,
insuranceFund: 0
});
emit RegisteredAirline(airlinesName, newAirlines);
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(
address passenger,
address airlines,
string flight,
uint256 timestamp
)
external
payable
requireAuthorizedCaller
requireRegisteredAirline(airlines)
requireIsOperational
returns(uint256)
{
//maybe add timestamp later
bytes32 flightKey = keccak256(abi.encodePacked( airlines, flight, timestamp));
bytes32 passengerKey = keccak256(abi.encodePacked( passenger, airlines, flight, timestamp));
Passenger storage existingPassenger = insuredPassengers[passengerKey];
require(existingPassenger.insuranceAmount <= 0, "Passenger already bought insurance for the flight");
insuredPassengers[passengerKey] = Passenger({
passengerAddress: passenger,
insuranceAmount: msg.value
});
//add all insured passenger address to the list for that specific flight
insuredPassengerList[flightKey].push(passenger);
return insuredPassengers[passengerKey].insuranceAmount;
}
function getInsuranceAmount (
address passenger,
address airlines,
string flight,
uint256 timestamp
)
external view
requireAuthorizedCaller
requireIsOperational
returns(uint256)
{
//maybe add timestamp later
bytes32 key = keccak256(abi.encodePacked( passenger, airlines, flight, timestamp));
return insuredPassengers[key].insuranceAmount;
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
address airlines,
string flight,
uint256 timestamp,
uint256 suretyAmtMultiplier,
uint256 suretyAmtDivider
)
external
requireIsOperational
requireAuthorizedCaller
returns (int numOfPassengers)
{
bytes32 flightKey = keccak256(abi.encodePacked( airlines, flight, timestamp));
bytes32 passengerKey = 0;
address[] storage passengers = insuredPassengerList[flightKey];
numOfPassengers = 0;
for (uint index=0; index < passengers.length; index++) {
address passenger = passengers[index];
passengerKey = keccak256(abi.encodePacked( passenger, airlines, flight, timestamp));
uint256 insurancePaid = insuredPassengers[passengerKey].insuranceAmount;
require(insurancePaid > 0, "There is no insurance bought to refund");
// if the passenger has bought insurance, credit their account 1.5*insurance
creditedPassengers[passengerKey] = insurancePaid.mul(suretyAmtMultiplier).div(suretyAmtDivider);
insuredPassengers[passengerKey].insuranceAmount = 0;
numOfPassengers++;
//emit CreditInsured(passenger, airlines, flight, timestamp, insuredPassengers[key].insuranceAmount);
}
}
function getCreditedInsuranceAmount (
address passenger,
address airlines,
string flight,
uint256 timestamp
)
external view
requireIsOperational
requireAuthorizedCaller
returns(uint256)
{
bytes32 passengerKey = keccak256(abi.encodePacked(passenger, airlines, flight, timestamp));
return creditedPassengers[passengerKey] ;
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function withdraw (
address passenger,
address airlines,
string flight,
uint256 timestamp
)
external
requireIsOperational
requireAuthorizedCaller
returns (uint256)
{
//address passenger = tx.origin;
bytes32 passengerKey = keccak256(abi.encodePacked(passenger, airlines, flight, timestamp));
uint256 amountToBeCredited = creditedPassengers[passengerKey];
require(amountToBeCredited > 0, "There is no amount to be credited");
require(amountToBeCredited < registeredAirlines[airlines].insuranceFund, "Airlines doesn't have fund");
//make the amount to be credited 0 - to avoid reentrancy
creditedPassengers[passengerKey] = 0;
passenger.transfer(amountToBeCredited);
//subtract the amount credited from the airlines fund
registeredAirlines[airlines].insuranceFund = registeredAirlines[airlines].insuranceFund.sub(amountToBeCredited);
return registeredAirlines[airlines].insuranceFund;
}
/**
* @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( )
public
payable
// requireMinimumFund(10)
requireIsOperational
requireAuthorizedCaller
requireRegisteredAirline(tx.origin)
returns (uint)
{
//store the amount that the airlines has paid
registeredAirlines[tx.origin].insuranceFund = registeredAirlines[tx.origin].insuranceFund.add(msg.value);
return registeredAirlines[tx.origin].insuranceFund;
//return 10;
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
|
Transfers eligible payout funds to insuree/address passenger = tx.origin;make the amount to be credited 0 - to avoid reentrancysubtract the amount credited from the airlines fund
|
function withdraw (
address passenger,
address airlines,
string flight,
uint256 timestamp
)
external
requireIsOperational
requireAuthorizedCaller
returns (uint256)
{
bytes32 passengerKey = keccak256(abi.encodePacked(passenger, airlines, flight, timestamp));
uint256 amountToBeCredited = creditedPassengers[passengerKey];
require(amountToBeCredited > 0, "There is no amount to be credited");
require(amountToBeCredited < registeredAirlines[airlines].insuranceFund, "Airlines doesn't have fund");
creditedPassengers[passengerKey] = 0;
passenger.transfer(amountToBeCredited);
registeredAirlines[airlines].insuranceFund = registeredAirlines[airlines].insuranceFund.sub(amountToBeCredited);
return registeredAirlines[airlines].insuranceFund;
}
| 12,637,542 |
pragma ton-solidity >=0.32.0;
pragma AbiHeader expire;
import "20_interface.sol";
contract Bomber is IBomber {
uint constant param0 = 10;
uint constant param1 = 100;
mapping(uint => uint) map;
modifier onlyOwner {
// Check that function is called by external message
require(tvm.pubkey() != 0 && tvm.pubkey() == msg.pubkey());
tvm.accept();
_;
}
function testSend0(address addr) public pure onlyOwner {
// Bomber sends 1 ever but Sink will get less than 1 ever (~ 0.998 ever).
// Because forward fee is subtracted from 1 ever
ISink(addr).receive0{value: 1 ever, flag: 0}(param0, param1);
}
function testSend1(address addr) public pure onlyOwner {
// Bomber sends 1 ever and Sink will get 1 ever exactly.
// Forward fee is subtracted from balance of this contract.
ISink(addr).receive0{value: 1 ever, flag: 1}(param0, param1);
}
function testSend128(address addr) public pure onlyOwner {
// Bomber sends all its balance and Sink will get all that funds minus forward fee.
// The Bomber's balance will be equal to zero.
ISink(addr).receive0{value: 0, flag: 128}(param0, param1);
// Note: parameter "value" is ignored by the virtual machine. It can be set to any value, for example zero.
}
function testSend160(address addr) public pure onlyOwner {
// Bomber sends all its balance and Sink will get all that funds minus forward fee.
// The Bomber's balance will be equal to zero and the contract will be destroyed.
ISink(addr).receive0{value: 0, flag: 128 + 32}(param0, param1);
// Note: parameter "value" is ignored by the virtual machine. It can be set to any value, for example zero.
// Note: After destroying the contract can be redeployed on the same address.
}
// The function can be called only by internal message (in function there is no `tvm.accept()`)
function testValue0Flag64() external override {
// This function was called by internal message. In this function works with mapping. In this case amount of
// used gas depends on size of the mapping. Caller doesn't know how much value should be attached to cover gas.
// So, caller can attach some big value and this contract will return change.
map[rnd.next()] = rnd.next();
// Return change.
// Forward fee is subtracted from change. See also function `testSend0`.
ISink(msg.sender).receive0{value: 0, flag: 64}(param0, param1);
}
function testValue1Flag64() external override {
map[rnd.next()] = rnd.next();
// Returns change and sends 1 ever.
// Forward fee is subtracted from (change + 1 ever). See also function `testSend0`.
ISink(msg.sender).receive0{value: 1 ever, flag: 64}(param0, param1);
}
function testValue1Flag65() external override {
map[rnd.next()] = rnd.next();
// Returns change and sends 1 ever.
// Forward fee is subtracted from Bomber's balance. See also function `testSend1`
ISink(msg.sender).receive0{value: 1 ever, flag: 64 + 1}(param0, param1);
}
function testFlag2(address addr) public pure onlyOwner {
// Contract sends 3 messages with values: 1 ever, 1e9 ever and 1 ever.
// Let contract has balance equal to 5 ever. Then it's obvious that it can't send 1e9 ever. It should cause fail
// of action phase. But the second message has flag: 2. It means that any errors arising while processing this
// message during the action phase should be ignored.
// That's why contract will send successfully the first and third messages. The second message will be ignored.
ISink(addr).receive0{value: 1 ever, flag: 0}(param0, param1);
ISink(addr).receive0{value: 1e9 ever, flag: 2}(param0, param1);
ISink(addr).receive0{value: 1 ever, flag: 0}(param0, param1);
}
}
|
Bomber sends 1 ever and Sink will get 1 ever exactly. Forward fee is subtracted from balance of this contract.
|
function testSend1(address addr) public pure onlyOwner {
}
| 15,831,240 |
./full_match/4/0xDE58156AC65F0c26Fc5eEF3F666bDFd753187058/sources/browser/Vault.sol
|
Asgard calls to transfer to recipient
|
function asgardTransfer(address to, address asset, uint value, string memory memo) public onlyAsgard {
require(asset != address(0), "Ether must be sent from asgard");
asgardAllowance[asset] = asgardAllowance[asset].sub(value);
ERC20(asset).transfer(to, value);
emit Transfer(to, asset, value, memo);
}
| 12,371,207 |
./full_match/44787/0x4F63c931BC78b5c9Cd3AE45Bba90Ab7C7be2195F/sources/contracts/cross-chain/ToucanCrosschainMessenger.sol
|
Receive messages sent via Optics from other remote xApp Routers; parse the contents of the message and enact the message's effects on the local chain Called by an Optics Replica contract while processing a message sent via Optics _origin The domain the message is coming from _sender The address the message is coming from _message The message in the form of raw bytes/ route message to appropriate _handle function based on what type of message is encoded
|
function handle(
uint32 _origin,
bytes32 _sender,
bytes calldata _message
) external override onlyReplica onlyRemoteRouter(_origin, _sender) {
(
uint8 messageType,
address receiver,
address token,
uint256 amount,
uint32 toDomain,
bytes32 requestHash
) = abi.decode(
_message,
(uint8, address, address, uint256, uint32, bytes32)
);
require(
requests[requestHash].requestType ==
BridgeRequestType.NOT_REGISTERED,
'Bridge Request Executed'
);
requests[requestHash] = BridgeRequest(
false,
BridgeRequestType.RECEIVED,
MessageTypes(messageType)
);
if (MessageTypes(messageType) == MessageTypes.MINT) {
IBridgeableToken(token).bridgeMint(receiver, amount);
emit BridgeRequestReceived(
_origin,
toDomain,
receiver,
token,
amount,
requestHash
);
revert('Unsopported Operation');
}
}
| 13,245,806 |
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./ERC20LockableAccount.sol";
import "../../../../common-solidity/crosschain-precompile-calls/contracts/Crosschain.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* The balances are stored in their own contracts, to allow for the router / lockable item pattern.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Router is IERC20, Crosschain {
mapping (address => address[]) private lockableAccounts;
mapping (address => mapping (address => uint256)) private allowances;
uint256 private theTotalSupply;
address public owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
constructor() public {
owner = msg.sender;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return theTotalSupply;
}
/**
* Only return the balance of the [0] account.
*/
function balanceOf(address account) public view returns (uint256) {
address[] memory lockableAccountAddresses = lockableAccounts[account];
if (lockableAccountAddresses.length == 0) {
return 0;
}
ERC20LockableAccount lockableAccount = ERC20LockableAccount(lockableAccountAddresses[0]);
return lockableAccount.balance();
}
/**
* Move all unlocked accounts into the [0] account.
*/
function condense(address _account) public {
address[] memory lockableAccountAddresses = lockableAccounts[_account];
require(lockableAccountAddresses.length != 0);
require(!crosschainIsLocked(lockableAccountAddresses[0]));
ERC20LockableAccount rootLockableAccount = ERC20LockableAccount(lockableAccountAddresses[0]);
uint256 total = 0;
for (uint256 i=1; i< lockableAccountAddresses.length; i++) {
if (!crosschainIsLocked(lockableAccountAddresses[i])) {
ERC20LockableAccount lockableAccount = ERC20LockableAccount(lockableAccountAddresses[i]);
total += lockableAccount.withdrawAll();
}
}
rootLockableAccount.add(total);
}
function createAccount(address[] memory _lockableAccountContracts) public {
for (uint256 i=0; i<_lockableAccountContracts.length; i++) {
ERC20LockableAccount lockableAccount = ERC20LockableAccount(_lockableAccountContracts[i]);
require(lockableAccount.owner() == msg.sender);
lockableAccounts[msg.sender].push(_lockableAccountContracts[i]);
}
}
function createAccountFor(address account, address[] calldata _lockableAccountContracts) external onlyOwner{
for (uint256 i=0; i<_lockableAccountContracts.length; i++) {
ERC20LockableAccount lockableAccount = ERC20LockableAccount(_lockableAccountContracts[i]);
require(lockableAccount.owner() == account);
lockableAccounts[msg.sender].push(_lockableAccountContracts[i]);
}
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address _recipient, uint256 _amount) public returns (bool) {
_transfer(msg.sender, _recipient, _amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowances[_owner][_spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address _spender, uint256 _amount) public returns (bool) {
_approve(msg.sender, _spender, _amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address _sender, address _recipient, uint256 _amount) public returns (bool) {
_transfer(_sender, _recipient, _amount);
// uint256 accAllowance = allowances[_sender][msg.sender];
// require(accAllowance >= _amount, "ERC20: transfer amount exceeds allowance");
// TODO allowances need to be moved out into separate lockable contracts
// _approve(_sender, msg.sender, accAllowance - _amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
uint256 accAllowance = allowances[_spender][msg.sender];
_approve(msg.sender, _spender, accAllowance + _addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
uint256 accAllowance = allowances[msg.sender][_spender];
require(accAllowance >= _subtractedValue, "ERC20: decreased allowance below zero");
_approve(msg.sender, _spender, accAllowance - _subtractedValue);
return true;
}
// Some functions to help debug
function accSize(address _acc) external view returns (uint256) {
address[] memory lockableAccountAddresses = lockableAccounts[_acc];
return lockableAccountAddresses.length;
}
function getLockableAccountAddress(address _account, uint256 _instance) public view returns (address) {
return lockableAccounts[_account][_instance];
}
function accGetBalance(address _acc, uint256 _index) external view returns (uint256) {
address[] memory lockableAccountAddresses = lockableAccounts[_acc];
ERC20LockableAccount lockableAccount = ERC20LockableAccount(lockableAccountAddresses[_index]);
return lockableAccount.balance();
}
function accGetOwner(address _acc, uint256 _index) external view returns (address) {
address[] memory lockableAccountAddresses = lockableAccounts[_acc];
ERC20LockableAccount lockableAccount = ERC20LockableAccount(lockableAccountAddresses[_index]);
return lockableAccount.owner();
}
function accGetRouter(address _acc, uint256 _index) external view returns (address) {
address[] memory lockableAccountAddresses = lockableAccounts[_acc];
ERC20LockableAccount lockableAccount = ERC20LockableAccount(lockableAccountAddresses[_index]);
return lockableAccount.erc20RouterContract();
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
* Moves from sender[0] to an instance of recipient that is unlocked.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address _sender, address _recipient, uint256 _amount) internal {
require(_sender != address(0), "ERC20: transfer from the zero address");
require(_recipient != address(0), "ERC20: transfer to the zero address");
address[] memory senderLockableAccountAddresses = lockableAccounts[_sender];
require(senderLockableAccountAddresses.length != 0, "ERC20: no sender lockable contract");
ERC20LockableAccount senderLockableAccount = ERC20LockableAccount(senderLockableAccountAddresses[0]);
address[] memory recipientLockableAccountAddresses = lockableAccounts[_recipient];
require(recipientLockableAccountAddresses.length != 0);
ERC20LockableAccount recipientLockableAccount;
for (uint256 i=0; i<recipientLockableAccountAddresses.length; i++) {
if (!crosschainIsLocked(recipientLockableAccountAddresses[i])) {
recipientLockableAccount = ERC20LockableAccount(recipientLockableAccountAddresses[i]);
break;
}
}
require(address(recipientLockableAccount) != address(0));
senderLockableAccount.sub(_amount);
recipientLockableAccount.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(uint256 _amount) onlyOwner public {
theTotalSupply = theTotalSupply + _amount;
address[] memory recipientLockableAccountAddresses = lockableAccounts[msg.sender];
require(recipientLockableAccountAddresses.length != 0);
ERC20LockableAccount recipientLockableAccount = ERC20LockableAccount(recipientLockableAccountAddresses[0]);
recipientLockableAccount.add(_amount);
emit Transfer(address(0), msg.sender, _amount);
}
// /**
// * @dev Destroys `amount` tokens from `account`, reducing the
// * total supply.
// *
// * Emits a {Transfer} event with `to` set to the zero address.
// *
// * Requirements
// *
// * - `account` cannot be the zero address.
// * - `account` must have at least `amount` tokens.
// */
// function _burn(address _account, uint256 _amount) internal {
// require(_account != address(0), "ERC20: burn from the zero address");
//
// address recipientLockableAccountAddress = lockableAccounts[_account];
// if (receiverLockableAccountAddress == address(0)) {
// lockableAccounts[_account] = recipientLockableAccountAddress = new ERC20LockableAccount(this);
// }
// ERC20LockableAccount recipientLockableAccount = ERC20LockableAccount(recipientLockableAccountAddress);
// recipientLockableAccount.sub(_amount);
// totalSupply = totalSupply.sub(_amount);
// emit Transfer(_account, address(0), _amount);
// }
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address _owner, address _spender, uint256 _amount) internal {
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
allowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
// /**
// * @dev Destroys `amount` tokens from `account`.`amount` is then deducted
// * from the caller's allowance.
// *
// * See {_burn} and {_approve}.
// */
// function _burnFrom(address account, uint256 amount) internal {
// _burn(account, amount);
// _approve(account, _msgSender(), allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
// }
}
|
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`./ uint256 accAllowance = allowances[_sender][msg.sender]; require(accAllowance >= _amount, "ERC20: transfer amount exceeds allowance"); TODO allowances need to be moved out into separate lockable contracts _approve(_sender, msg.sender, accAllowance - _amount);
|
function transferFrom(address _sender, address _recipient, uint256 _amount) public returns (bool) {
_transfer(_sender, _recipient, _amount);
return true;
}
| 1,790,685 |
./full_match/4/0x2134a37B62808e31525744588e719E84E8eA8c21/sources/contracts/ArtSale_ERC721A.sol
|
Set signer who can generate whitelist signatures
|
function setSignerAddress(address _addr) external onlyOwner {
signerAddress = _addr;
}
| 787,918 |
./partial_match/42/0xD8ADbda80801278Bd1Bf8C1107DDF035f81a8F64/sources/Unwind.sol
|
interface for the End contract from MakerDAO
|
interface IEnd {
function tag(bytes32) external returns(uint256);
function fix(bytes32) external returns(uint256);
function skim(bytes32, address) external;
function free(bytes32) external;
function pack(uint256) external;
function cash(bytes32, uint) external;
}
| 3,381,263 |
// SPDX-License-Identifier: GPL-2.0
pragma solidity 0.8.8;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB)
external
view
returns (address);
}
interface IUniswapV2Pair {
function token0() external pure returns (address);
function token1() external pure returns (address);
function getReserves()
external
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
);
}
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
abstract contract Zap {
using SafeERC20 for IERC20;
using SafeMath for uint256;
IERC20 public immutable koromaru; // Koromaru token
IERC20 public immutable koromaruUniV2; // Uniswap V2 LP token for Koromaru
IUniswapV2Factory public immutable UniSwapV2FactoryAddress;
IUniswapV2Router02 public uniswapRouter;
address public immutable WETHAddress;
uint256 private constant swapDeadline =
0xf000000000000000000000000000000000000000000000000000000000000000;
struct ZapVariables {
uint256 LP;
uint256 koroAmount;
uint256 wethAmount;
address tokenToZap;
uint256 amountToZap;
}
event ZappedIn(address indexed account, uint256 amount);
event ZappedOut(
address indexed account,
uint256 amount,
uint256 koroAmount,
uint256 Eth
);
constructor(
address _koromaru,
address _koromaruUniV2,
address _UniSwapV2FactoryAddress,
address _uniswapRouter
) {
koromaru = IERC20(_koromaru);
koromaruUniV2 = IERC20(_koromaruUniV2);
UniSwapV2FactoryAddress = IUniswapV2Factory(_UniSwapV2FactoryAddress);
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
WETHAddress = uniswapRouter.WETH();
}
function ZapIn(uint256 _amount, bool _multi)
internal
returns (
uint256 _LP,
uint256 _WETHBalance,
uint256 _KoromaruBalance
)
{
(uint256 _koroAmount, uint256 _ethAmount) = _moveTokensToContract(
_amount
);
_approveRouterIfNotApproved();
(_LP, _WETHBalance, _KoromaruBalance) = !_multi
? _zapIn(_koroAmount, _ethAmount)
: _zapInMulti(_koroAmount, _ethAmount);
require(_LP > 0, "ZapIn: Invalid LP amount");
emit ZappedIn(msg.sender, _LP);
}
function zapOut(uint256 _koroLPAmount)
internal
returns (uint256 _koroTokens, uint256 _ether)
{
_approveRouterIfNotApproved();
uint256 balanceBefore = koromaru.balanceOf(address(this));
_ether = uniswapRouter.removeLiquidityETHSupportingFeeOnTransferTokens(
address(koromaru),
_koroLPAmount,
1,
1,
address(this),
swapDeadline
);
require(_ether > 0, "ZapOut: Eth Output Low");
uint256 balanceAfter = koromaru.balanceOf(address(this));
require(balanceAfter > balanceBefore, "ZapOut: Nothing to ZapOut");
_koroTokens = balanceAfter.sub(balanceBefore);
emit ZappedOut(msg.sender, _koroLPAmount, _koroTokens, _ether);
}
//-------------------- Zap Utils -------------------------
function _zapIn(uint256 _koroAmount, uint256 _wethAmount)
internal
returns (
uint256 _LP,
uint256 _WETHBalance,
uint256 _KoromaruBalance
)
{
ZapVariables memory zapVars;
zapVars.tokenToZap; // koro or eth
zapVars.amountToZap; // koro or weth
(address _Token0, address _Token1) = _getKoroLPPairs(
address(koromaruUniV2)
);
if (_koroAmount > 0 && _wethAmount < 1) {
// if only koro
zapVars.amountToZap = _koroAmount;
zapVars.tokenToZap = address(koromaru);
} else if (_wethAmount > 0 && _koroAmount < 1) {
// if only weth
zapVars.amountToZap = _wethAmount;
zapVars.tokenToZap = WETHAddress;
}
(uint256 token0Out, uint256 token1Out) = _executeSwapForPairs(
zapVars.tokenToZap,
_Token0,
_Token1,
zapVars.amountToZap
);
(_LP, _WETHBalance, _KoromaruBalance) = _toLiquidity(
_Token0,
_Token1,
token0Out,
token1Out
);
}
function _zapInMulti(uint256 _koroAmount, uint256 _wethAmount)
internal
returns (
uint256 _LPToken,
uint256 _WETHBalance,
uint256 _KoromaruBalance
)
{
ZapVariables memory zapVars;
zapVars.koroAmount = _koroAmount;
zapVars.wethAmount = _wethAmount;
zapVars.tokenToZap; // koro or eth
zapVars.amountToZap; // koro or weth
{
(
uint256 _kLP,
uint256 _kWETHBalance,
uint256 _kKoromaruBalance
) = _zapIn(zapVars.koroAmount, 0);
_LPToken += _kLP;
_WETHBalance += _kWETHBalance;
_KoromaruBalance += _kKoromaruBalance;
}
{
(
uint256 _kLP,
uint256 _kWETHBalance,
uint256 _kKoromaruBalance
) = _zapIn(0, zapVars.wethAmount);
_LPToken += _kLP;
_WETHBalance += _kWETHBalance;
_KoromaruBalance += _kKoromaruBalance;
}
}
function _toLiquidity(
address _Token0,
address _Token1,
uint256 token0Out,
uint256 token1Out
)
internal
returns (
uint256 _LP,
uint256 _WETHBalance,
uint256 _KoromaruBalance
)
{
_approveToken(_Token0, address(uniswapRouter), token0Out);
_approveToken(_Token1, address(uniswapRouter), token1Out);
(uint256 amountA, uint256 amountB, uint256 LP) = uniswapRouter
.addLiquidity(
_Token0,
_Token1,
token0Out,
token1Out,
1,
1,
address(this),
swapDeadline
);
_LP = LP;
_WETHBalance = token0Out.sub(amountA);
_KoromaruBalance = token1Out.sub(amountB);
}
function _approveRouterIfNotApproved() private {
if (koromaru.allowance(address(this), address(uniswapRouter)) == 0) {
koromaru.approve(address(uniswapRouter), type(uint256).max);
}
if (
koromaruUniV2.allowance(address(this), address(uniswapRouter)) == 0
) {
koromaruUniV2.approve(address(uniswapRouter), type(uint256).max);
}
}
function _moveTokensToContract(uint256 _amount)
internal
returns (uint256 _koroAmount, uint256 _ethAmount)
{
_ethAmount = msg.value;
if (msg.value > 0) IWETH(WETHAddress).deposit{value: _ethAmount}();
if (msg.value < 1) {
// ZapIn must have either both Koro and Eth, just Eth or just Koro
require(_amount > 0, "KOROFARM: Invalid ZapIn Call");
}
if (_amount > 0) {
koromaru.safeTransferFrom(msg.sender, address(this), _amount);
}
_koroAmount = _amount;
}
function _getKoroLPPairs(address _pairAddress)
internal
pure
returns (address token0, address token1)
{
IUniswapV2Pair uniPair = IUniswapV2Pair(_pairAddress);
token0 = uniPair.token0();
token1 = uniPair.token1();
}
function _executeSwapForPairs(
address _inToken,
address _token0,
address _token1,
uint256 _amount
) internal returns (uint256 _token0Out, uint256 _token1Out) {
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
if (_inToken == _token0) {
uint256 swapAmount = determineSwapInAmount(resv0, _amount);
if (swapAmount < 1) swapAmount = _amount.div(2);
// swap Weth tokens to koro
_token1Out = _swapTokenForToken(_inToken, _token1, swapAmount);
_token0Out = _amount.sub(swapAmount);
} else {
uint256 swapAmount = determineSwapInAmount(resv1, _amount);
if (swapAmount < 1) swapAmount = _amount.div(2);
_token0Out = _swapTokenForToken(_inToken, _token0, swapAmount);
_token1Out = _amount.sub(swapAmount);
}
}
function _swapTokenForToken(
address _swapFrom,
address _swapTo,
uint256 _tokensToSwap
) internal returns (uint256 tokenBought) {
if (_swapFrom == _swapTo) {
return _tokensToSwap;
}
_approveToken(
_swapFrom,
address(uniswapRouter),
_tokensToSwap.mul(1e12)
);
address pair = UniSwapV2FactoryAddress.getPair(_swapFrom, _swapTo);
require(pair != address(0), "SwapTokenForToken: Swap path error");
address[] memory path = new address[](2);
path[0] = _swapFrom;
path[1] = _swapTo;
uint256 balanceBefore = IERC20(_swapTo).balanceOf(address(this));
uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(
_tokensToSwap,
0,
path,
address(this),
swapDeadline
);
uint256 balanceAfter = IERC20(_swapTo).balanceOf(address(this));
tokenBought = balanceAfter.sub(balanceBefore);
// Ideal, but fails to work with Koromary due to fees
// tokenBought = uniswapRouter.swapExactTokensForTokens(
// _tokensToSwap,
// 1,
// path,
// address(this),
// swapDeadline
// )[path.length - 1];
// }
require(tokenBought > 0, "SwapTokenForToken: Error Swapping Tokens 2");
}
function determineSwapInAmount(uint256 _pairResIn, uint256 _userAmountIn)
internal
pure
returns (uint256)
{
return
(_sqrt(
_pairResIn *
((_userAmountIn * 3988000) + (_pairResIn * 3988009))
) - (_pairResIn * 1997)) / 1994;
}
function _sqrt(uint256 _val) internal pure returns (uint256 z) {
if (_val > 3) {
z = _val;
uint256 x = _val / 2 + 1;
while (x < z) {
z = x;
x = (_val / x + x) / 2;
}
} else if (_val != 0) {
z = 1;
}
}
function _approveToken(
address token,
address spender,
uint256 amount
) internal {
IERC20 _token = IERC20(token);
_token.safeApprove(spender, 0);
_token.safeApprove(spender, amount);
}
//---------------- End of Zap Utils ----------------------
}
contract KoroFarms is Ownable, Pausable, ReentrancyGuard, Zap {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
struct UserInfo {
uint256 amount;
uint256 koroDebt;
uint256 ethDebt;
uint256 unpaidKoro;
uint256 unpaidEth;
uint256 lastRewardHarvestedTime;
}
struct FarmInfo {
uint256 accKoroRewardsPerShare;
uint256 accEthRewardsPerShare;
uint256 lastRewardTimestamp;
}
AggregatorV3Interface internal priceFeed;
uint256 internal immutable koromaruDecimals;
uint256 internal constant EthPriceFeedDecimal = 1e8;
uint256 internal constant precisionScaleUp = 1e30;
uint256 internal constant secsPerDay = 1 days / 1 seconds;
uint256 private taxRefundPercentage;
uint256 internal constant _1hundred_Percent = 10000;
uint256 public APR; // 100% = 10000, 50% = 5000, 15% = 1500
uint256 rewardHarvestingInterval;
uint256 public koroRewardAllocation;
uint256 public ethRewardAllocation;
uint256 internal maxLPLimit;
uint256 internal zapKoroLimit;
FarmInfo public farmInfo;
mapping(address => UserInfo) public userInfo;
uint256 public totalEthRewarded; // total amount of eth given as rewards
uint256 public totalKoroRewarded; // total amount of Koro given as rewards
//---------------- Contract Events -------------------
event Compound(address indexed account, uint256 koro, uint256 eth);
event Withdraw(address indexed account, uint256 amount);
event Deposit(address indexed account, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event KoroRewardsHarvested(address indexed account, uint256 Kororewards);
event EthRewardsHarvested(address indexed account, uint256 Ethrewards);
event APRUpdated(uint256 OldAPR, uint256 NewAPR);
event Paused();
event Unpaused();
event IncreaseKoroRewardPool(uint256 amount);
event IncreaseEthRewardPool(uint256 amount);
//------------- End of Contract Events ----------------
constructor(
address _koromaru,
address _koromaruUniV2,
address _UniSwapV2FactoryAddress,
address _uniswapRouter,
uint256 _apr,
uint256 _taxToRefund,
uint256 _koromaruTokenDecimals,
uint256 _koroRewardAllocation,
uint256 _rewardHarvestingInterval,
uint256 _zapKoroLimit
) Zap(_koromaru, _koromaruUniV2, _UniSwapV2FactoryAddress, _uniswapRouter) {
require(
_koroRewardAllocation <= 10000,
"setRewardAllocations: Invalid rewards allocation"
);
require(_apr <= 10000, "SetDailyAPR: Invalid APR Value");
approveRouterIfNotApproved();
koromaruDecimals = 10**_koromaruTokenDecimals;
zapKoroLimit = _zapKoroLimit * 10**_koromaruTokenDecimals;
APR = _apr;
koroRewardAllocation = _koroRewardAllocation;
ethRewardAllocation = _1hundred_Percent.sub(_koroRewardAllocation);
taxRefundPercentage = _taxToRefund;
farmInfo = FarmInfo({
lastRewardTimestamp: block.timestamp,
accKoroRewardsPerShare: 0,
accEthRewardsPerShare: 0
});
rewardHarvestingInterval = _rewardHarvestingInterval * 1 seconds;
priceFeed = AggregatorV3Interface(
0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419
);
}
//---------------- Contract Owner ----------------------
/**
* @notice Update chainLink Eth Price feed
*/
function updatePriceFeed(address _usdt_eth_aggregator) external onlyOwner {
priceFeed = AggregatorV3Interface(_usdt_eth_aggregator);
}
/**
* @notice Set's tax refund percentage for Koromaru
* @dev User 100% = 10000, 50% = 5000, 15% = 1500 etc.
*/
function setTaxRefundPercent(uint256 _taxToRefund) external onlyOwner {
taxRefundPercentage = _taxToRefund;
}
/**
* @notice Set's max koromaru per transaction
* @dev Decimals will be added automatically
*/
function setZapLimit(uint256 _limit) external onlyOwner {
zapKoroLimit = _limit * koromaruDecimals;
}
/**
* @notice Set's daily ROI percentage for the farm
* @dev User 100% = 10000, 50% = 5000, 15% = 1500 etc.
*/
function setDailyAPR(uint256 _dailyAPR) external onlyOwner {
updateFarm();
require(_dailyAPR <= 10000, "SetDailyAPR: Invalid APR Value");
uint256 oldAPr = APR;
APR = _dailyAPR;
emit APRUpdated(oldAPr, APR);
}
/**
* @notice Set's reward allocation for reward pool
* @dev Set for Koromaru only, eth's allocation will be calcuated. User 100% = 10000, 50% = 5000, 15% = 1500 etc.
*/
function setRewardAllocations(uint256 _koroAllocation) external onlyOwner {
// setting 10000 (100%) will set eth rewards to 0.
require(
_koroAllocation <= 10000,
"setRewardAllocations: Invalid rewards allocation"
);
koroRewardAllocation = _koroAllocation;
ethRewardAllocation = _1hundred_Percent.sub(_koroAllocation);
}
/**
* @notice Set's maximum amount of LPs that can be staked in this farm
* @dev When 0, no limit is imposed. When max is reached farmers cannot stake more LPs or compound.
*/
function setMaxLPLimit(uint256 _maxLPLimit) external onlyOwner {
// A new user’s stake cannot cause the amount of LP tokens in the farm to exceed this value
// MaxLP can be set to 0(nomax)
maxLPLimit = _maxLPLimit;
}
/**
* @notice Reset's the chainLink price feed to the default price feed
*/
function resetPriceFeed() external onlyOwner {
priceFeed = AggregatorV3Interface(
0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419
);
}
/**
* @notice Withdraw foreign tokens sent to this contract
* @dev Can only withdraw none koromaru tokens and KoroV2 tokens
*/
function withdrawForeignToken(address _token)
external
nonReentrant
onlyOwner
{
require(_token != address(0), "KOROFARM: Invalid Token");
require(
_token != address(koromaru),
"KOROFARM: Token cannot be same as koromaru tokens"
);
require(
_token != address(koromaruUniV2),
"KOROFARM: Token cannot be same as farmed tokens"
);
uint256 amount = IERC20(_token).balanceOf(address(this));
if (amount > 0) {
IERC20(_token).safeTransfer(msg.sender, amount);
}
}
/**
* @notice Deposit Koromaru tokens into reward pool
*/
function depositKoroRewards(uint256 _amount)
external
onlyOwner
nonReentrant
{
require(_amount > 0, "KOROFARM: Invalid Koro Amount");
koromaru.safeTransferFrom(msg.sender, address(this), _amount);
emit IncreaseKoroRewardPool(_amount);
}
/**
* @notice Deposit Eth tokens into reward pool
*/
function depositEthRewards() external payable onlyOwner nonReentrant {
require(msg.value > 0, "KOROFARM: Invalid Eth Amount");
emit IncreaseEthRewardPool(msg.value);
}
/**
* @notice This function will pause the farm and withdraw all rewards in case of failure or emergency
*/
function pauseAndRemoveRewardPools() external onlyOwner whenNotPaused {
// only to be used by admin in critical situations
uint256 koroBalance = koromaru.balanceOf(address(this));
uint256 ethBalance = payable(address(this)).balance;
if (koroBalance > 0) {
koromaru.safeTransfer(msg.sender, koroBalance);
}
if (ethBalance > 0) {
(bool sent, ) = payable(msg.sender).call{value: ethBalance}("");
require(sent, "Failed to send Ether");
}
}
/**
* @notice Initiate stopped state
* @dev Only possible when contract not paused.
*/
function pause() external onlyOwner whenNotPaused {
_pause();
emit Paused();
}
/**
* @notice Initiate normal state
* @dev Only possible when contract is paused.
*/
function unpause() external onlyOwner whenPaused {
_unpause();
emit Unpaused();
}
//-------------- End Contract Owner --------------------
//---------------- Contract Farmer ----------------------
/**
* @notice Calculates and returns pending rewards for a farmer
*/
function getPendingRewards(address _farmer)
public
view
returns (uint256 pendinKoroTokens, uint256 pendingEthWei)
{
UserInfo storage user = userInfo[_farmer];
uint256 accKoroRewardsPerShare = farmInfo.accKoroRewardsPerShare;
uint256 accEthRewardsPerShare = farmInfo.accEthRewardsPerShare;
uint256 stakedTVL = getStakedTVL();
if (block.timestamp > farmInfo.lastRewardTimestamp && stakedTVL != 0) {
uint256 timeElapsed = block.timestamp.sub(
farmInfo.lastRewardTimestamp
);
uint256 koroReward = timeElapsed.mul(
getNumberOfKoroRewardsPerSecond(koroRewardAllocation)
);
uint256 ethReward = timeElapsed.mul(
getAmountOfEthRewardsPerSecond(ethRewardAllocation)
);
accKoroRewardsPerShare = accKoroRewardsPerShare.add(
koroReward.mul(precisionScaleUp).div(stakedTVL)
);
accEthRewardsPerShare = accEthRewardsPerShare.add(
ethReward.mul(precisionScaleUp).div(stakedTVL)
);
}
pendinKoroTokens = user
.amount
.mul(accKoroRewardsPerShare)
.div(precisionScaleUp)
.sub(user.koroDebt)
.add(user.unpaidKoro);
pendingEthWei = user
.amount
.mul(accEthRewardsPerShare)
.div(precisionScaleUp)
.sub(user.ethDebt)
.add(user.unpaidEth);
}
/**
* @notice Calculates and returns the TVL in USD staked in the farm
* @dev Uses the price of 1 Koromaru to calculate the TVL in USD
*/
function getStakedTVL() public view returns (uint256) {
uint256 stakedLP = koromaruUniV2.balanceOf(address(this));
uint256 totalLPsupply = koromaruUniV2.totalSupply();
return stakedLP.mul(getTVLUsingKoro()).div(totalLPsupply);
}
/**
* @notice Calculates and updates the farm's rewards per share
* @dev Called by other function to update the function state
*/
function updateFarm() public whenNotPaused returns (FarmInfo memory farm) {
farm = farmInfo;
uint256 WETHBalance = IERC20(WETHAddress).balanceOf(address(this));
if (WETHBalance > 0) IWETH(WETHAddress).withdraw(WETHBalance);
if (block.timestamp > farm.lastRewardTimestamp) {
uint256 stakedTVL = getStakedTVL();
if (stakedTVL > 0) {
uint256 timeElapsed = block.timestamp.sub(
farm.lastRewardTimestamp
);
uint256 koroReward = timeElapsed.mul(
getNumberOfKoroRewardsPerSecond(koroRewardAllocation)
);
uint256 ethReward = timeElapsed.mul(
getAmountOfEthRewardsPerSecond(ethRewardAllocation)
);
farm.accKoroRewardsPerShare = farm.accKoroRewardsPerShare.add(
(koroReward.mul(precisionScaleUp) / stakedTVL)
);
farm.accEthRewardsPerShare = farm.accEthRewardsPerShare.add(
(ethReward.mul(precisionScaleUp) / stakedTVL)
);
}
farm.lastRewardTimestamp = block.timestamp;
farmInfo = farm;
}
}
/**
* @notice Deposit Koromaru tokens into farm
* @dev Deposited Koromaru will zap into Koro/WETH LP tokens, a refund of TX fee % will be issued
*/
function depositKoroTokensOnly(uint256 _amount)
external
whenNotPaused
nonReentrant
{
require(_amount > 0, "KOROFARM: Invalid Koro Amount");
require(
_amount <= zapKoroLimit,
"KOROFARM: Can't deposit more than Zap Limit"
);
(uint256 lpZappedIn, , ) = ZapIn(_amount, false);
// do tax refund
userInfo[msg.sender].unpaidKoro += _amount.mul(taxRefundPercentage).div(
_1hundred_Percent
);
onDeposit(msg.sender, lpZappedIn);
}
/**
* @notice Deposit Koro/WETH LP tokens into farm
*/
function depositKoroLPTokensOnly(uint256 _amount)
external
whenNotPaused
nonReentrant
{
require(_amount > 0, "KOROFARM: Invalid KoroLP Amount");
koromaruUniV2.safeTransferFrom(msg.sender, address(this), _amount);
onDeposit(msg.sender, _amount);
}
/**
* @notice Deposit Koromaru, Koromaru/Eth LP and Eth at once into farm requires all 3
*/
function depositMultipleAssets(uint256 _koro, uint256 _koroLp)
external
payable
whenNotPaused
nonReentrant
{
// require(_koro > 0, "KOROFARM: Invalid Koro Amount");
// require(_koroLp > 0, "KOROFARM: Invalid LP Amount");
require(
_koro <= zapKoroLimit,
"KOROFARM: Can't deposit more than Zap Limit"
);
// execute the zap
// (uint256 lpZappedIn,uint256 wethBalance, uint256 korobalance)= ZapIn(_koro, true);
(uint256 lpZappedIn, , ) = msg.value > 0
? ZapIn(_koro, true)
: ZapIn(_koro, false);
// transfer the lp in
if (_koroLp > 0)
koromaruUniV2.safeTransferFrom(
address(msg.sender),
address(this),
_koroLp
);
uint256 sumOfLps = lpZappedIn + _koroLp;
// do tax refund
userInfo[msg.sender].unpaidKoro += _koro.mul(taxRefundPercentage).div(
_1hundred_Percent
);
onDeposit(msg.sender, sumOfLps);
}
/**
* @notice Deposit Eth only into farm
* @dev Deposited Eth will zap into Koro/WETH LP tokens
*/
function depositEthOnly() external payable whenNotPaused nonReentrant {
require(msg.value > 0, "KOROFARM: Invalid Eth Amount");
// (uint256 lpZappedIn, uint256 wethBalance, uint256 korobalance)= ZapIn(0, false);
(uint256 lpZappedIn, , ) = ZapIn(0, false);
onDeposit(msg.sender, lpZappedIn);
}
/**
* @notice Withdraw all staked LP tokens + rewards from farm. Only possilbe after harvest interval.
Use emergency withdraw if you want to withdraw before harvest interval. No rewards will be returned.
* @dev Farmer's can choose to get back LP tokens or Zap out to get Koromaru and Eth
*/
function withdraw(bool _useZapOut) external whenNotPaused nonReentrant {
uint256 balance = userInfo[msg.sender].amount;
require(balance > 0, "Withdraw: You have no balance");
updateFarm();
if (_useZapOut) {
zapLPOut(balance);
} else {
koromaruUniV2.transfer(msg.sender, balance);
}
onWithdraw(msg.sender);
emit Withdraw(msg.sender, balance);
}
/**
* @notice Harvest all rewards from farm
*/
function harvest() external whenNotPaused nonReentrant {
updateFarm();
harvestRewards(msg.sender);
}
/**
* @notice Compounds rewards from farm. Only available after harvest interval is reached for farmer.
*/
function compound() external whenNotPaused nonReentrant {
updateFarm();
UserInfo storage user = userInfo[msg.sender];
require(
block.timestamp - user.lastRewardHarvestedTime >=
rewardHarvestingInterval,
"HarvestRewards: Not yet ripe"
);
uint256 koroCompounded;
uint256 ethCompounded;
uint256 pendinKoroTokens = user
.amount
.mul(farmInfo.accKoroRewardsPerShare)
.div(precisionScaleUp)
.sub(user.koroDebt)
.add(user.unpaidKoro);
uint256 pendingEthWei = user
.amount
.mul(farmInfo.accEthRewardsPerShare)
.div(precisionScaleUp)
.sub(user.ethDebt)
.add(user.unpaidEth);
{
uint256 koromaruBalance = koromaru.balanceOf(address(this));
if (pendinKoroTokens > 0) {
if (pendinKoroTokens > koromaruBalance) {
// not enough koro balance to reward farmer
user.unpaidKoro = pendinKoroTokens.sub(koromaruBalance);
totalKoroRewarded = totalKoroRewarded.add(koromaruBalance);
koroCompounded = koromaruBalance;
} else {
user.unpaidKoro = 0;
totalKoroRewarded = totalKoroRewarded.add(pendinKoroTokens);
koroCompounded = pendinKoroTokens;
}
}
}
{
uint256 ethBalance = getEthBalance();
if (pendingEthWei > ethBalance) {
// not enough Eth balance to reward farmer
user.unpaidEth = pendingEthWei.sub(ethBalance);
totalEthRewarded = totalEthRewarded.add(ethBalance);
IWETH(WETHAddress).deposit{value: ethBalance}();
ethCompounded = ethBalance;
} else {
user.unpaidEth = 0;
totalEthRewarded = totalEthRewarded.add(pendingEthWei);
IWETH(WETHAddress).deposit{value: pendingEthWei}();
ethCompounded = pendingEthWei;
}
}
(uint256 LP, , ) = _zapInMulti(koroCompounded, ethCompounded);
onCompound(msg.sender, LP);
emit Compound(msg.sender, koroCompounded, ethCompounded);
}
/**
* @notice Returns time in seconds to next harvest.
*/
function timeToHarvest(address _user)
public
view
whenNotPaused
returns (uint256)
{
UserInfo storage user = userInfo[_user];
if (
block.timestamp - user.lastRewardHarvestedTime >=
rewardHarvestingInterval
) {
return 0;
}
return
user.lastRewardHarvestedTime.sub(
block.timestamp.sub(rewardHarvestingInterval)
);
}
/**
* @notice Withdraw all staked LP tokens without rewards.
*/
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
koromaruUniV2.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, user.amount);
userInfo[msg.sender] = UserInfo(0, 0, 0, 0, 0, 0);
}
//--------------- End Contract Farmer -------------------
//---------------- Contract Utils ----------------------
/**
* @notice Calculates the total amount of rewards per day in USD
* @dev The returned value is in USD * 1e18 (WETH decimals), actual USD value is calculated by dividing the value by 1e18
*/
function getUSDDailyRewards() public view whenNotPaused returns (uint256) {
uint256 stakedLP = koromaruUniV2.balanceOf(address(this));
uint256 totalLPsupply = koromaruUniV2.totalSupply();
uint256 stakedTVL = stakedLP.mul(getTVLUsingKoro()).div(totalLPsupply);
return APR.mul(stakedTVL).div(_1hundred_Percent);
}
/**
* @notice Calculates the total amount of rewards per second in USD
* @dev The returned value is in USD * 1e18 (WETH decimals), actual USD value is calculated by dividing the value by 1e18
*/
function getUSDRewardsPerSecond() internal view returns (uint256) {
// final return value should be divided by (1e18) (i.e WETH decimals) to get USD value
uint256 dailyRewards = getUSDDailyRewards();
return dailyRewards.div(secsPerDay);
}
/**
* @notice Calculates the total number of koromaru token rewards per second
* @dev The returned value must be divided by the koromaru token decimals to get the actual value
*/
function getNumberOfKoroRewardsPerSecond(uint256 _koroRewardAllocation)
internal
view
returns (uint256)
{
uint256 priceOfUintKoro = getLatestKoroPrice(); // 1e18
uint256 rewardsPerSecond = getUSDRewardsPerSecond(); // 1e18
return
rewardsPerSecond
.mul(_koroRewardAllocation)
.mul(koromaruDecimals)
.div(priceOfUintKoro)
.div(_1hundred_Percent); //to be div by koro decimals (i.e 1**(18-18+korodecimals)
}
/**
* @notice Calculates the total amount of Eth rewards per second
* @dev The returned value must be divided by the 1e18 to get the actual value
*/
function getAmountOfEthRewardsPerSecond(uint256 _ethRewardAllocation)
internal
view
returns (uint256)
{
uint256 priceOfUintEth = getLatestEthPrice(); // 1e8
uint256 rewardsPerSecond = getUSDRewardsPerSecond(); // 1e18
uint256 scaleUpToWei = 1e8;
return
rewardsPerSecond
.mul(_ethRewardAllocation)
.mul(scaleUpToWei)
.div(priceOfUintEth)
.div(_1hundred_Percent); // to be div by 1e18 (i.e 1**(18-8+8)
}
/**
* @notice Returns the rewards rate/second for both koromaru and eth
*/
function getRewardsPerSecond()
public
view
whenNotPaused
returns (uint256 koroRewards, uint256 ethRewards)
{
require(
koroRewardAllocation.add(ethRewardAllocation) == _1hundred_Percent,
"getRewardsPerSecond: Invalid reward allocation ratio"
);
koroRewards = getNumberOfKoroRewardsPerSecond(koroRewardAllocation);
ethRewards = getAmountOfEthRewardsPerSecond(ethRewardAllocation);
}
/**
* @notice Calculates and returns the TVL in USD (actaul TVL, not staked TVL)
* @dev Uses Eth price from price feed to calculate the TVL in USD
*/
function getTVL() public view returns (uint256 tvl) {
// final return value should be divided by (1e18) (i.e WETH decimals) to get USD value
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
address token0 = koroPair.token0();
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
uint256 TVLEth = 2 *
(address(token0) == address(koromaru) ? resv1 : resv0);
uint256 priceOfEth = getLatestEthPrice();
tvl = TVLEth.mul(priceOfEth).div(EthPriceFeedDecimal);
}
/**
* @notice Calculates and returns the TVL in USD (actaul TVL, not staked TVL)
* @dev Uses minimum Eth price in USD for 1 koromaru token to calculate the TVL in USD
*/
function getTVLUsingKoro() public view whenNotPaused returns (uint256 tvl) {
// returned value should be divided by (1e18) (i.e WETH decimals) to get USD value
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
address token0 = koroPair.token0();
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
uint256 TVLKoro = 2 *
(address(token0) == address(koromaru) ? resv0 : resv1);
uint256 priceOfKoro = getLatestKoroPrice();
tvl = TVLKoro.mul(priceOfKoro).div(koromaruDecimals);
}
/**
* @notice Get's the latest Eth price in USD
* @dev Uses ChainLink price feed to get the latest Eth price in USD
*/
function getLatestEthPrice() internal view returns (uint256) {
// final return value should be divided by 1e8 to get USD value
(, int256 price, , , ) = priceFeed.latestRoundData();
return uint256(price);
}
/**
* @notice Get's the latest Unit Koro price in USD
* @dev Uses estimated price per koromaru token in USD
*/
function getLatestKoroPrice() internal view returns (uint256) {
// returned value must be divided by 1e18 (i.e WETH decimals) to get USD value
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
address token0 = koroPair.token0();
bool isKoro = address(token0) == address(koromaru);
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
uint256 oneKoro = 1 * koromaruDecimals;
uint256 optimalWethAmount = uniswapRouter.getAmountOut(
oneKoro,
isKoro ? resv0 : resv1,
isKoro ? resv1 : resv0
); //uniswapRouter.quote(oneKoro, isKoro ? resv1 : resv0, isKoro ? resv0 : resv1);
uint256 priceOfEth = getLatestEthPrice();
return optimalWethAmount.mul(priceOfEth).div(EthPriceFeedDecimal);
}
function onDeposit(address _user, uint256 _amount) internal {
require(!reachedMaxLimit(), "KOROFARM: Farm is full");
UserInfo storage user = userInfo[_user];
updateFarm();
if (user.amount > 0) {
// record as unpaid
user.unpaidKoro = user
.amount
.mul(farmInfo.accKoroRewardsPerShare)
.div(precisionScaleUp)
.sub(user.koroDebt)
.add(user.unpaidKoro);
user.unpaidEth = user
.amount
.mul(farmInfo.accEthRewardsPerShare)
.div(precisionScaleUp)
.sub(user.ethDebt)
.add(user.unpaidEth);
}
user.amount = user.amount.add(_amount);
user.koroDebt = user.amount.mul(farmInfo.accKoroRewardsPerShare).div(
precisionScaleUp
);
user.ethDebt = user.amount.mul(farmInfo.accEthRewardsPerShare).div(
precisionScaleUp
);
if (
(block.timestamp - user.lastRewardHarvestedTime >=
rewardHarvestingInterval) || (rewardHarvestingInterval == 0)
) {
user.lastRewardHarvestedTime = block.timestamp;
}
emit Deposit(_user, _amount);
}
function onWithdraw(address _user) internal {
harvestRewards(_user);
userInfo[msg.sender].amount = 0;
userInfo[msg.sender].koroDebt = 0;
userInfo[msg.sender].ethDebt = 0;
}
function onCompound(address _user, uint256 _amount) internal {
require(!reachedMaxLimit(), "KOROFARM: Farm is full");
UserInfo storage user = userInfo[_user];
user.amount = user.amount.add(_amount);
user.koroDebt = user.amount.mul(farmInfo.accKoroRewardsPerShare).div(
precisionScaleUp
);
user.ethDebt = user.amount.mul(farmInfo.accEthRewardsPerShare).div(
precisionScaleUp
);
user.lastRewardHarvestedTime = block.timestamp;
}
function harvestRewards(address _user) internal {
UserInfo storage user = userInfo[_user];
require(
block.timestamp - user.lastRewardHarvestedTime >=
rewardHarvestingInterval,
"HarvestRewards: Not yet ripe"
);
uint256 pendinKoroTokens = user
.amount
.mul(farmInfo.accKoroRewardsPerShare)
.div(precisionScaleUp)
.sub(user.koroDebt)
.add(user.unpaidKoro);
uint256 pendingEthWei = user
.amount
.mul(farmInfo.accEthRewardsPerShare)
.div(precisionScaleUp)
.sub(user.ethDebt)
.add(user.unpaidEth);
{
uint256 koromaruBalance = koromaru.balanceOf(address(this));
if (pendinKoroTokens > 0) {
if (pendinKoroTokens > koromaruBalance) {
// not enough koro balance to reward farmer
koromaru.safeTransfer(_user, koromaruBalance);
user.unpaidKoro = pendinKoroTokens.sub(koromaruBalance);
totalKoroRewarded = totalKoroRewarded.add(koromaruBalance);
emit KoroRewardsHarvested(_user, koromaruBalance);
} else {
koromaru.safeTransfer(_user, pendinKoroTokens);
user.unpaidKoro = 0;
totalKoroRewarded = totalKoroRewarded.add(pendinKoroTokens);
emit KoroRewardsHarvested(_user, pendinKoroTokens);
}
}
}
{
uint256 ethBalance = getEthBalance();
if (pendingEthWei > ethBalance) {
// not enough Eth balance to reward farmer
(bool sent, ) = _user.call{value: ethBalance}("");
require(sent, "Failed to send Ether");
user.unpaidEth = pendingEthWei.sub(ethBalance);
totalEthRewarded = totalEthRewarded.add(ethBalance);
emit EthRewardsHarvested(_user, ethBalance);
} else {
(bool sent, ) = _user.call{value: pendingEthWei}("");
require(sent, "Failed to send Ether");
user.unpaidEth = 0;
totalEthRewarded = totalEthRewarded.add(pendingEthWei);
emit EthRewardsHarvested(_user, pendingEthWei);
}
}
user.koroDebt = user.amount.mul(farmInfo.accKoroRewardsPerShare).div(
precisionScaleUp
);
user.ethDebt = user.amount.mul(farmInfo.accEthRewardsPerShare).div(
precisionScaleUp
);
user.lastRewardHarvestedTime = block.timestamp;
}
/**
* @notice Convert's Koro LP tokens back to Koro and Eth
*/
function zapLPOut(uint256 _amount)
private
returns (uint256 _koroTokens, uint256 _ether)
{
(_koroTokens, _ether) = zapOut(_amount);
(bool sent, ) = msg.sender.call{value: _ether}("");
require(sent, "Failed to send Ether");
koromaru.safeTransfer(msg.sender, _koroTokens);
}
function getEthBalance() public view returns (uint256) {
return address(this).balance;
}
function getUserInfo(address _user)
public
view
returns (
uint256 amount,
uint256 stakedInUsd,
uint256 timeToHarves,
uint256 pendingKoro,
uint256 pendingEth
)
{
amount = userInfo[_user].amount;
timeToHarves = timeToHarvest(_user);
(pendingKoro, pendingEth) = getPendingRewards(_user);
uint256 stakedLP = koromaruUniV2.balanceOf(address(this));
stakedInUsd = stakedLP > 0
? userInfo[_user].amount.mul(getStakedTVL()).div(stakedLP)
: 0;
}
function getFarmInfo()
public
view
returns (
uint256 tvl,
uint256 totalStaked,
uint256 circSupply,
uint256 dailyROI,
uint256 ethDistribution,
uint256 koroDistribution
)
{
tvl = getStakedTVL();
totalStaked = koromaruUniV2.balanceOf(address(this));
circSupply = getCirculatingSupplyLocked();
dailyROI = APR;
ethDistribution = ethRewardAllocation;
koroDistribution = koroRewardAllocation;
}
function getCirculatingSupplyLocked() public view returns (uint256) {
address deadWallet = address(
0x000000000000000000000000000000000000dEaD
);
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
address token0 = koroPair.token0();
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
uint256 koroResv = address(token0) == address(koromaru) ? resv0 : resv1;
uint256 lpSupply = koromaruUniV2.totalSupply();
uint256 koroCirculatingSupply = koromaru.totalSupply().sub(
koromaru.balanceOf(deadWallet)
);
uint256 stakedLp = koromaruUniV2.balanceOf(address(this));
return
(stakedLp.mul(koroResv).mul(1e18).div(lpSupply)).div(
koroCirculatingSupply
); // divide by 1e18
}
function approveRouterIfNotApproved() private {
if (koromaru.allowance(address(this), address(uniswapRouter)) == 0) {
koromaru.safeApprove(address(uniswapRouter), type(uint256).max);
}
if (
koromaruUniV2.allowance(address(this), address(uniswapRouter)) == 0
) {
koromaruUniV2.approve(address(uniswapRouter), type(uint256).max);
}
}
function reachedMaxLimit() public view returns (bool) {
uint256 lockedLP = koromaruUniV2.balanceOf(address(this));
if (maxLPLimit < 1) return false; // unlimited
if (lockedLP >= maxLPLimit) return true;
return false;
}
//--------------- End Contract Utils -------------------
receive() external payable {
emit IncreaseEthRewardPool(msg.value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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 `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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;
}
}
|
ZapIn must have either both Koro and Eth, just Eth or just Koro
|
function _moveTokensToContract(uint256 _amount)
internal
returns (uint256 _koroAmount, uint256 _ethAmount)
{
_ethAmount = msg.value;
if (msg.value < 1) {
require(_amount > 0, "KOROFARM: Invalid ZapIn Call");
}
if (_amount > 0) {
koromaru.safeTransferFrom(msg.sender, address(this), _amount);
}
_koroAmount = _amount;
}
| 12,599,114 |
./partial_match/1313161554/0x964630b8327A6EB8730e3addcB8563d1e61b0100/sources/Comptroller.sol
|
Checks if the account should be allowed to redeem tokens in the given market chToken The market to verify the redeem against redeemer The account which would redeem the tokens redeechTokens The number of chTokens to exchange for the underlying asset in the market return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)/
|
function redeemAllowed(
address chToken,
address redeemer,
uint256 redeechTokens
) external returns (uint256) {
uint256 allowed = redeemAllowedInternal(chToken, redeemer, redeechTokens);
if (allowed != uint256(Error.NO_ERROR)) {
return allowed;
}
distributeSupplierReward(chToken, redeemer);
return uint256(Error.NO_ERROR);
}
| 16,919,322 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./FixedPoint.sol";
library Position {
using FixedPoint for uint256;
uint256 internal constant ONE = 1e18;
uint256 internal constant RATIO_PRECISION_SHIFT = 1e4; // RATIO_PRECISION = 1e14
struct Info {
uint96 notional; // initial notional = collateral * leverage
uint96 debt; // debt
uint48 entryToMidRatio; // ratio of entryPrice / _midFromFeed() at build
bool isLong; // whether long or short
bool liquidated; // whether has been liquidated
uint256 oiShares; // shares of aggregate open interest on side
}
/*///////////////////////////////////////////////////////////////
POSITIONS MAPPING FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Retrieves a position from positions mapping
function get(
mapping(bytes32 => Info) storage self,
address owner,
uint256 id
) internal view returns (Info storage position_) {
position_ = self[keccak256(abi.encodePacked(owner, id))];
}
/// @notice Stores a position in positions mapping
function set(
mapping(bytes32 => Info) storage self,
address owner,
uint256 id,
Info memory position
) internal {
self[keccak256(abi.encodePacked(owner, id))] = position;
}
/*///////////////////////////////////////////////////////////////
POSITION CAST GETTER FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Computes the position's initial notional cast to uint256
function _notional(Info memory self) private pure returns (uint256) {
return uint256(self.notional);
}
/// @notice Computes the position's initial open interest cast to uint256
function _oiShares(Info memory self) private pure returns (uint256) {
return uint256(self.oiShares);
}
/// @notice Computes the position's debt cast to uint256
function _debt(Info memory self) private pure returns (uint256) {
return uint256(self.debt);
}
/// @notice Whether the position exists
/// @dev Is false if position has been liquidated or has zero oi
function exists(Info memory self) internal pure returns (bool exists_) {
return (!self.liquidated && self.notional > 0);
}
/*///////////////////////////////////////////////////////////////
POSITION ENTRY PRICE FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Computes the entryToMidRatio cast to uint48 to be set
/// @notice on position build
function calcEntryToMidRatio(uint256 _entryPrice, uint256 _midPrice)
internal
pure
returns (uint48)
{
require(_entryPrice <= 2 * _midPrice, "OVLV1: value == 0 at entry");
return uint48(_entryPrice.divDown(_midPrice) / RATIO_PRECISION_SHIFT);
}
/// @notice Computes the ratio of the entryPrice of position to the midPrice
/// @notice at build cast to uint256
function getEntryToMidRatio(Info memory self) internal pure returns (uint256) {
return (uint256(self.entryToMidRatio) * RATIO_PRECISION_SHIFT);
}
/// @notice Computes the entryPrice of the position cast to uint256
/// @dev entryPrice = entryToMidRatio * midPrice (at build)
function entryPrice(Info memory self) internal pure returns (uint256 entryPrice_) {
uint256 priceRatio = getEntryToMidRatio(self);
uint256 oi = _oiShares(self);
uint256 q = _notional(self);
// will only be zero if all oi shares unwound; handles 0/0 case
// of notion / oi
if (oi == 0) {
return 0;
}
// entry = ratio * mid = ratio * (notional / oi)
entryPrice_ = priceRatio.mulUp(q).divUp(oi);
}
/*///////////////////////////////////////////////////////////////
POSITION FRACTIONAL GETTER FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Computes the initial notional of position when built
/// @dev use mulUp to avoid rounding leftovers on unwind
function notionalInitial(Info memory self, uint256 fraction) internal pure returns (uint256) {
return _notional(self).mulUp(fraction);
}
/// @notice Computes the initial open interest of position when built
/// @dev use mulUp to avoid rounding leftovers on unwind
function oiInitial(Info memory self, uint256 fraction) internal pure returns (uint256) {
return _oiShares(self).mulUp(fraction);
}
/// @notice Computes the current shares of open interest position holds
/// @notice on pos.isLong side of the market
/// @dev use mulUp to avoid rounding leftovers on unwind
function oiSharesCurrent(Info memory self, uint256 fraction) internal pure returns (uint256) {
return _oiShares(self).mulUp(fraction);
}
/// @notice Computes the current debt position holds
/// @dev use mulUp to avoid rounding leftovers on unwind
function debtCurrent(Info memory self, uint256 fraction) internal pure returns (uint256) {
return _debt(self).mulUp(fraction);
}
/// @notice Computes the current open interest of a position accounting for
/// @notice potential funding payments between long/short sides
/// @dev returns zero when oiShares = oiTotalOnSide = oiTotalSharesOnSide = 0 to avoid
/// @dev div by zero errors
/// @dev use mulUp, divUp to avoid rounding leftovers on unwind
function oiCurrent(
Info memory self,
uint256 fraction,
uint256 oiTotalOnSide,
uint256 oiTotalSharesOnSide
) internal pure returns (uint256) {
uint256 posOiShares = oiSharesCurrent(self, fraction);
if (posOiShares == 0 || oiTotalOnSide == 0) return 0;
return posOiShares.mulUp(oiTotalOnSide).divUp(oiTotalSharesOnSide);
}
/*///////////////////////////////////////////////////////////////
POSITION CALC FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Computes the position's cost cast to uint256
/// WARNING: be careful modifying notional and debt on unwind
function cost(Info memory self, uint256 fraction) internal pure returns (uint256) {
uint256 posNotionalInitial = notionalInitial(self, fraction);
uint256 posDebt = debtCurrent(self, fraction);
// should always be > 0 but use subFloor to be safe w reverts
uint256 posCost = posNotionalInitial;
posCost = posCost.subFloor(posDebt);
return posCost;
}
/// @notice Computes the value of a position
/// @dev Floors to zero, so won't properly compute if self is underwater
function value(
Info memory self,
uint256 fraction,
uint256 oiTotalOnSide,
uint256 oiTotalSharesOnSide,
uint256 currentPrice,
uint256 capPayoff
) internal pure returns (uint256 val_) {
uint256 posOiInitial = oiInitial(self, fraction);
uint256 posNotionalInitial = notionalInitial(self, fraction);
uint256 posDebt = debtCurrent(self, fraction);
uint256 posOiCurrent = oiCurrent(self, fraction, oiTotalOnSide, oiTotalSharesOnSide);
uint256 posEntryPrice = entryPrice(self);
// NOTE: PnL = +/- oiCurrent * [currentPrice - entryPrice]; ... (w/o capPayoff)
// NOTE: fundingPayments = notionalInitial * ( oiCurrent / oiInitial - 1 )
// NOTE: value = collateralInitial + PnL + fundingPayments
// NOTE: = notionalInitial - debt + PnL + fundingPayments
if (self.isLong) {
// val = notionalInitial * oiCurrent / oiInitial
// + oiCurrent * min[currentPrice, entryPrice * (1 + capPayoff)]
// - oiCurrent * entryPrice - debt
val_ =
posNotionalInitial.mulUp(posOiCurrent).divUp(posOiInitial) +
Math.min(
posOiCurrent.mulUp(currentPrice),
posOiCurrent.mulUp(posEntryPrice).mulUp(ONE + capPayoff)
);
// floor to 0
val_ = val_.subFloor(posDebt + posOiCurrent.mulUp(posEntryPrice));
} else {
// NOTE: capPayoff >= 1, so no need to include w short
// val = notionalInitial * oiCurrent / oiInitial + oiCurrent * entryPrice
// - oiCurrent * currentPrice - debt
val_ =
posNotionalInitial.mulUp(posOiCurrent).divUp(posOiInitial) +
posOiCurrent.mulUp(posEntryPrice);
// floor to 0
val_ = val_.subFloor(posDebt + posOiCurrent.mulUp(currentPrice));
}
}
/// @notice Computes the current notional of a position including PnL
/// @dev Floors to debt if value <= 0
function notionalWithPnl(
Info memory self,
uint256 fraction,
uint256 oiTotalOnSide,
uint256 oiTotalSharesOnSide,
uint256 currentPrice,
uint256 capPayoff
) internal pure returns (uint256 notionalWithPnl_) {
uint256 posValue = value(
self,
fraction,
oiTotalOnSide,
oiTotalSharesOnSide,
currentPrice,
capPayoff
);
uint256 posDebt = debtCurrent(self, fraction);
notionalWithPnl_ = posValue + posDebt;
}
/// @notice Computes the trading fees to be imposed on a position for build/unwind
function tradingFee(
Info memory self,
uint256 fraction,
uint256 oiTotalOnSide,
uint256 oiTotalSharesOnSide,
uint256 currentPrice,
uint256 capPayoff,
uint256 tradingFeeRate
) internal pure returns (uint256 tradingFee_) {
uint256 posNotional = notionalWithPnl(
self,
fraction,
oiTotalOnSide,
oiTotalSharesOnSide,
currentPrice,
capPayoff
);
tradingFee_ = posNotional.mulUp(tradingFeeRate);
}
/// @notice Whether a position can be liquidated
/// @dev is true when value * (1 - liq fee rate) < maintenance margin
/// @dev liq fees are reward given to liquidator
function liquidatable(
Info memory self,
uint256 oiTotalOnSide,
uint256 oiTotalSharesOnSide,
uint256 currentPrice,
uint256 capPayoff,
uint256 maintenanceMarginFraction,
uint256 liquidationFeeRate
) internal pure returns (bool can_) {
uint256 fraction = ONE;
uint256 posNotionalInitial = notionalInitial(self, fraction);
if (self.liquidated || posNotionalInitial == 0) {
// already been liquidated
return false;
}
uint256 val = value(
self,
fraction,
oiTotalOnSide,
oiTotalSharesOnSide,
currentPrice,
capPayoff
);
uint256 maintenanceMargin = posNotionalInitial.mulUp(maintenanceMarginFraction);
uint256 liquidationFee = val.mulDown(liquidationFeeRate);
can_ = val < maintenanceMargin + liquidationFee;
}
}
|
Stores a position in positions mapping
|
function set(
mapping(bytes32 => Info) storage self,
address owner,
uint256 id,
Info memory position
) internal {
self[keccak256(abi.encodePacked(owner, id))] = position;
}
POSITION CAST GETTER FUNCTIONS
| 15,830,168 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SendEther{
function send(address payable toReceiver) public payable{
// call function returns a boolean value indicating success or failure
// This is the current recommended method to use
(bool sent, ) = toReceiver.call{value:msg.value} (" ");
require(sent, "Failed to send Ether");
}
}
|
call function returns a boolean value indicating success or failure This is the current recommended method to use
|
function send(address payable toReceiver) public payable{
require(sent, "Failed to send Ether");
}
| 12,762,006 |
./full_match/1/0xfF88cbdbe3B9aD9eD3E928527186332eC3a394D6/sources/contracts/core/Front.sol
|
build the attestations from multiple user requests. Forwards to the build function of targeted attester attesters Targeted attesters requests User requests proofDataArray Data sent along the request to prove its validity return attestations Attestations that will be recorded/
|
function batchBuildAttestations(
address[] calldata attesters,
Request[] calldata requests,
bytes[] calldata proofDataArray
) external view override returns (Attestation[][] memory) {
Attestation[][] memory attestations = new Attestation[][](attesters.length);
for (uint256 i = 0; i < attesters.length; i++) {
attestations[i] = _forwardAttestationsBuild(attesters[i], requests[i], proofDataArray[i]);
}
return attestations;
}
| 4,962,829 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import './Manager.sol';
import '../interfaces/managers/IStrategyManager.sol';
import '../interfaces/aaveV2/ILendingPool.sol';
import '../interfaces/aaveV2/ILendingPoolAddressesProvider.sol';
import '../interfaces/aaveV2/IAaveIncentivesController.sol';
import '../interfaces/aaveV2/IStakeAave.sol';
import '../interfaces/aaveV2/IAToken.sol';
// This contract contains logic for depositing staker funds into Aave V2 as a yield strategy
contract AaveV2Strategy is IStrategyManager, Manager {
using SafeERC20 for IERC20;
// Need to call a provider because Aave has the ability to change the lending pool address
ILendingPoolAddressesProvider public constant LP_ADDRESS_PROVIDER =
ILendingPoolAddressesProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5);
// Aave contract that controls stkAAVE rewards
IAaveIncentivesController public immutable aaveIncentivesController;
// This is the token being deposited (USDC)
IERC20 public immutable override want;
// This is the receipt token Aave gives in exchange for a token deposit (aUSDC)
IAToken public immutable aWant;
// Address to receive stkAAVE rewards
address public immutable aaveLmReceiver;
// Constructor takes the aUSDC address and the rewards receiver address (a Sherlock address) as args
constructor(IAToken _aWant, address _aaveLmReceiver) {
if (address(_aWant) == address(0)) revert ZeroArgument();
if (_aaveLmReceiver == address(0)) revert ZeroArgument();
aWant = _aWant;
// This gets the underlying token associated with aUSDC (USDC)
want = IERC20(_aWant.UNDERLYING_ASSET_ADDRESS());
// Gets the specific rewards controller for this token type
aaveIncentivesController = _aWant.getIncentivesController();
aaveLmReceiver = _aaveLmReceiver;
}
// Returns the current Aave lending pool address that should be used
function getLp() internal view returns (ILendingPool) {
return ILendingPool(LP_ADDRESS_PROVIDER.getLendingPool());
}
/// @notice Checks the aUSDC balance in this contract
function balanceOf() public view override returns (uint256) {
return aWant.balanceOf(address(this));
}
/// @notice Deposits all USDC held in this contract into Aave's lending pool
function deposit() external override whenNotPaused {
ILendingPool lp = getLp();
// Checking the USDC balance of this contract
uint256 amount = want.balanceOf(address(this));
if (amount == 0) revert InvalidConditions();
// If allowance for this contract is too low, approve the max allowance
if (want.allowance(address(this), address(lp)) < amount) {
want.safeIncreaseAllowance(address(lp), type(uint256).max);
}
// Deposits the full balance of USDC held in this contract into Aave's lending pool
lp.deposit(address(want), amount, address(this), 0);
}
/// @notice Withdraws all USDC from Aave's lending pool back into the Sherlock core contract
/// @dev Only callable by the Sherlock core contract
/// @return The final amount withdrawn
function withdrawAll() external override onlySherlockCore returns (uint256) {
ILendingPool lp = getLp();
if (balanceOf() == 0) {
return 0;
}
// Withdraws all USDC from Aave's lending pool and sends it to the Sherlock core contract (msg.sender)
return lp.withdraw(address(want), type(uint256).max, msg.sender);
}
/// @notice Withdraws a specific amount of USDC from Aave's lending pool back into the Sherlock core contract
/// @param _amount Amount of USDC to withdraw
function withdraw(uint256 _amount) external override onlySherlockCore {
// Ensures that it doesn't execute a withdrawAll() call
// AAVE V2 uses uint256.max as a magic number to withdraw max amount
if (_amount == type(uint256).max) revert InvalidArgument();
ILendingPool lp = getLp();
// Withdraws _amount of USDC and sends it to the Sherlock core contract
// If the amount withdrawn is not equal to _amount, it reverts
if (lp.withdraw(address(want), _amount, msg.sender) != _amount) revert InvalidConditions();
}
// Claims the stkAAVE rewards and sends them to the receiver address
function claimRewards() external whenNotPaused {
// Creates an array with one slot
address[] memory assets = new address[](1);
// Sets the slot equal to the address of aUSDC
assets[0] = address(aWant);
// Claims all the rewards on aUSDC and sends them to the aaveLmReceiver (an address controlled by governance)
// Tokens are NOT meant to be (directly) distributed to stakers.
aaveIncentivesController.claimRewards(assets, type(uint256).max, aaveLmReceiver);
}
/// @notice Function used to check if this is the current active yield strategy
/// @return Boolean indicating it's active
/// @dev If inactive the owner can pull all ERC20s and ETH
/// @dev Will be checked by calling the sherlock contract
function isActive() public view returns (bool) {
return address(sherlockCore.yieldStrategy()) == address(this);
}
// Only contract owner can call this
// Sends all specified tokens in this contract to the receiver's address (as well as ETH)
function sweep(address _receiver, IERC20[] memory _extraTokens) external onlyOwner {
if (_receiver == address(0)) revert ZeroArgument();
// This contract must NOT be the current assigned yield strategy contract
if (isActive()) revert InvalidConditions();
// Executes the sweep for ERC-20s specified in _extraTokens as well as for ETH
_sweep(_receiver, _extraTokens);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/security/Pausable.sol';
import '../interfaces/managers/IManager.sol';
abstract contract Manager is IManager, Ownable, Pausable {
using SafeERC20 for IERC20;
address private constant DEPLOYER = 0x1C11bE636415973520DdDf1b03822b4e2930D94A;
ISherlock internal sherlockCore;
modifier onlySherlockCore() {
if (msg.sender != address(sherlockCore)) revert InvalidSender();
_;
}
/// @notice Set sherlock core address
/// @param _sherlock Current core contract
/// @dev Only deployer is able to set core address on all chains except Hardhat network
/// @dev One time function, will revert once `sherlock` != address(0)
/// @dev This contract will be deployed first, passed on as argument in core constuctor
/// @dev emits `SherlockCoreSet`
function setSherlockCoreAddress(ISherlock _sherlock) external override {
if (address(_sherlock) == address(0)) revert ZeroArgument();
// 31337 is of the Hardhat network blockchain
if (block.chainid != 31337 && msg.sender != DEPLOYER) revert InvalidSender();
if (address(sherlockCore) != address(0)) revert InvalidConditions();
sherlockCore = _sherlock;
emit SherlockCoreSet(_sherlock);
}
// Internal function to send tokens remaining in a contract to the receiver address
function _sweep(address _receiver, IERC20[] memory _extraTokens) internal {
// Loops through the extra tokens (ERC20) provided and sends all of them to the receiver address
for (uint256 i; i < _extraTokens.length; i++) {
IERC20 token = _extraTokens[i];
token.safeTransfer(_receiver, token.balanceOf(address(this)));
}
// Sends any remaining ETH to the receiver address (as long as receiver address is payable)
(bool success, ) = _receiver.call{ value: address(this).balance }('');
if (success == false) revert InvalidConditions();
}
function pause() external onlySherlockCore {
_pause();
}
function unpause() external onlySherlockCore {
_unpause();
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import './IManager.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IStrategyManager is IManager {
/// @return Returns the token type being deposited into a strategy
function want() external view returns (IERC20);
/// @notice Withdraws all USDC from the strategy back into the Sherlock core contract
/// @dev Only callable by the Sherlock core contract
/// @return The final amount withdrawn
function withdrawAll() external returns (uint256);
/// @notice Withdraws a specific amount of USDC from the strategy back into the Sherlock core contract
/// @param _amount Amount of USDC to withdraw
function withdraw(uint256 _amount) external;
/// @notice Deposits all USDC held in this contract into the strategy
function deposit() external;
/// @return Returns the USDC balance in this contract
function balanceOf() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.10;
pragma experimental ABIEncoderV2;
import { ILendingPoolAddressesProvider } from './ILendingPoolAddressesProvider.sol';
import { DataTypes } from './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.8.10;
/**
* @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.8.10;
pragma experimental ABIEncoderV2;
import { IAaveDistributionManager } from './IAaveDistributionManager.sol';
interface IAaveIncentivesController is IAaveDistributionManager {
event RewardsAccrued(address indexed user, uint256 amount);
event RewardsClaimed(
address indexed user,
address indexed to,
address indexed claimer,
uint256 amount
);
event ClaimerSet(address indexed user, address indexed claimer);
/**
* @dev Whitelists an address to claim the rewards on behalf of another address
* @param user The address of the user
* @param claimer The address of the claimer
*/
function setClaimer(address user, address claimer) external;
/**
* @dev Returns the whitelisted claimer for a certain address (0x0 if not set)
* @param user The address of the user
* @return The claimer address
*/
function getClaimer(address user) external view returns (address);
/**
* @dev Configure assets for a certain rewards emission
* @param assets The assets to incentivize
* @param emissionsPerSecond The emission for each asset
*/
function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond)
external;
/**
* @dev Called by the corresponding asset on any update that affects the rewards distribution
* @param asset The address of the user
* @param userBalance The balance of the user of the asset in the lending pool
* @param totalSupply The total supply of the asset in the lending pool
**/
function handleAction(
address asset,
uint256 userBalance,
uint256 totalSupply
) external;
/**
* @dev Returns the total of rewards of an user, already accrued + not yet accrued
* @param user The address of the user
* @return The rewards
**/
function getRewardsBalance(address[] calldata assets, address user)
external
view
returns (uint256);
/**
* @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards
* @param amount Amount of rewards to claim
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must
* be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager
* @param amount Amount of rewards to claim
* @param user Address to check and claim rewards
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewardsOnBehalf(
address[] calldata assets,
uint256 amount,
address user,
address to
) external returns (uint256);
/**
* @dev returns the unclaimed rewards of the user
* @param user the address of the user
* @return the unclaimed user rewards
*/
function getUserUnclaimedRewards(address user) external view returns (uint256);
/**
* @dev for backward compatibility with previous implementation of the Incentives controller
*/
function REWARD_TOKEN() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IStakeAave is IERC20 {
function cooldown() external;
function claimRewards(address to, uint256 amount) external;
function redeem(address to, uint256 amount) external;
function getTotalRewardsBalance(address staker) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.10;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import './IAaveIncentivesController.sol';
interface IAToken is IERC20 {
/**
* @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 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 aToken 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 incentives controller contract
**/
function getIncentivesController() external view returns (IAaveIncentivesController);
/**
* @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)
**/
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '../ISherlock.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IManager {
// An address or other value passed in is equal to zero (and shouldn't be)
error ZeroArgument();
// Occurs when a value already holds the desired property, or is not whitelisted
error InvalidArgument();
// If a required condition for executing the function is not met, it reverts and throws this error
error InvalidConditions();
// Throws if the msg.sender is not the required address
error InvalidSender();
event SherlockCoreSet(ISherlock sherlock);
/// @notice Set sherlock core address where premiums should be send too
/// @param _sherlock Current core contract
/// @dev Only deployer is able to set core address on all chains except Hardhat network
/// @dev One time function, will revert once `sherlock` != address(0)
/// @dev This contract will be deployed first, passed on as argument in core constuctor
/// @dev ^ that's needed for tvl accounting, once core is deployed this function is called
/// @dev emits `SherlockCoreSet`
function setSherlockCoreAddress(ISherlock _sherlock) external;
/// @notice Pause external functions in contract
function pause() external;
/// @notice Unpause external functions in contract
function unpause() external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import './ISherlockStake.sol';
import './ISherlockGov.sol';
import './ISherlockPayout.sol';
import './ISherlockStrategy.sol';
interface ISherlock is ISherlockStake, ISherlockGov, ISherlockPayout, ISherlockStrategy, IERC721 {
// msg.sender is not authorized to call this function
error Unauthorized();
// An address or other value passed in is equal to zero (and shouldn't be)
error ZeroArgument();
// Occurs when a value already holds the desired property, or is not whitelisted
error InvalidArgument();
// Required conditions are not true/met
error InvalidConditions();
// If the SHER tokens held in a contract are not the value they are supposed to be
error InvalidSherAmount(uint256 expected, uint256 actual);
// Checks the ERC-721 functions _exists() to see if an NFT ID actually exists and errors if not
error NonExistent();
event ArbRestaked(uint256 indexed tokenID, uint256 reward);
event Restaked(uint256 indexed tokenID);
}
// 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: GPL-2.0-or-later
pragma solidity 0.8.10;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
/// @title Sherlock core interface for stakers
/// @author Evert Kors
interface ISherlockStake {
/// @notice View the current lockup end timestamp of `_tokenID`
/// @return Timestamp when NFT position unlocks
function lockupEnd(uint256 _tokenID) external view returns (uint256);
/// @notice View the current SHER reward of `_tokenID`
/// @return Amount of SHER rewarded to owner upon reaching the end of the lockup
function sherRewards(uint256 _tokenID) external view returns (uint256);
/// @notice View the current token balance claimable upon reaching end of the lockup
/// @return Amount of tokens assigned to owner when unstaking position
function tokenBalanceOf(uint256 _tokenID) external view returns (uint256);
/// @notice View the current TVL for all stakers
/// @return Total amount of tokens staked
/// @dev Adds principal + strategy + premiums
/// @dev Will calculate the most up to date value for each piece
function totalTokenBalanceStakers() external view returns (uint256);
/// @notice Stakes `_amount` of tokens and locks up for `_period` seconds, `_receiver` will receive the NFT receipt
/// @param _amount Amount of tokens to stake
/// @param _period Period of time, in seconds, to lockup your funds
/// @param _receiver Address that will receive the NFT representing the position
/// @return _id ID of the position
/// @return _sher Amount of SHER tokens to be released to this ID after `_period` ends
/// @dev `_period` needs to be whitelisted
function initialStake(
uint256 _amount,
uint256 _period,
address _receiver
) external returns (uint256 _id, uint256 _sher);
/// @notice Redeem NFT `_id` and receive `_amount` of tokens
/// @param _id TokenID of the position
/// @return _amount Amount of tokens (USDC) owed to NFT ID
/// @dev Only the owner of `_id` will be able to redeem their position
/// @dev The SHER rewards are sent to the NFT owner
/// @dev Can only be called after lockup `_period` has ended
function redeemNFT(uint256 _id) external returns (uint256 _amount);
/// @notice Owner restakes position with ID: `_id` for `_period` seconds
/// @param _id ID of the position
/// @param _period Period of time, in seconds, to lockup your funds
/// @return _sher Amount of SHER tokens to be released to owner address after `_period` ends
/// @dev Only the owner of `_id` will be able to restake their position using this call
/// @dev `_period` needs to be whitelisted
/// @dev Can only be called after lockup `_period` has ended
function ownerRestake(uint256 _id, uint256 _period) external returns (uint256 _sher);
/// @notice Allows someone who doesn't own the position (an arbitrager) to restake the position for 26 weeks (ARB_RESTAKE_PERIOD)
/// @param _id ID of the position
/// @return _sher Amount of SHER tokens to be released to position owner on expiry of the 26 weeks lockup
/// @return _arbReward Amount of tokens (USDC) sent to caller (the arbitrager) in return for calling the function
/// @dev Can only be called after lockup `_period` is more than 2 weeks in the past (assuming ARB_RESTAKE_WAIT_TIME is 2 weeks)
/// @dev Max 20% (ARB_RESTAKE_MAX_PERCENTAGE) of tokens associated with a position are used to incentivize arbs (x)
/// @dev During a 2 week period the reward ratio will move from 0% to 100% (* x)
function arbRestake(uint256 _id) external returns (uint256 _sher, uint256 _arbReward);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import './managers/ISherDistributionManager.sol';
import './managers/ISherlockProtocolManager.sol';
import './managers/ISherlockClaimManager.sol';
import './managers/IStrategyManager.sol';
/// @title Sherlock core interface for governance
/// @author Evert Kors
interface ISherlockGov {
event ClaimPayout(address receiver, uint256 amount);
event YieldStrategyUpdateWithdrawAllError(bytes error);
event YieldStrategyUpdated(IStrategyManager previous, IStrategyManager current);
event ProtocolManagerUpdated(ISherlockProtocolManager previous, ISherlockProtocolManager current);
event ClaimManagerUpdated(ISherlockClaimManager previous, ISherlockClaimManager current);
event NonStakerAddressUpdated(address previous, address current);
event SherDistributionManagerUpdated(
ISherDistributionManager previous,
ISherDistributionManager current
);
event StakingPeriodEnabled(uint256 period);
event StakingPeriodDisabled(uint256 period);
/// @notice Allows stakers to stake for `_period` of time
/// @param _period Period of time, in seconds,
/// @dev should revert if already enabled
function enableStakingPeriod(uint256 _period) external;
/// @notice Disallow stakers to stake for `_period` of time
/// @param _period Period of time, in seconds,
/// @dev should revert if already disabled
function disableStakingPeriod(uint256 _period) external;
/// @notice View if `_period` is a valid period
/// @return Boolean indicating if period is valid
function stakingPeriods(uint256 _period) external view returns (bool);
/// @notice Update SHER distribution manager contract
/// @param _sherDistributionManager New adddress of the manager
function updateSherDistributionManager(ISherDistributionManager _sherDistributionManager)
external;
/// @notice Deletes the SHER distribution manager altogether (if Sherlock decides to no longer pay out SHER rewards)
function removeSherDistributionManager() external;
/// @notice Read SHER distribution manager
/// @return Address of current SHER distribution manager
function sherDistributionManager() external view returns (ISherDistributionManager);
/// @notice Update address eligible for non staker rewards from protocol premiums
/// @param _nonStakers Address eligible for non staker rewards
function updateNonStakersAddress(address _nonStakers) external;
/// @notice View current non stakers address
/// @return Current non staker address
/// @dev Is able to pull funds out of the contract
function nonStakersAddress() external view returns (address);
/// @notice View current address able to manage protocols
/// @return Protocol manager implemenation
function sherlockProtocolManager() external view returns (ISherlockProtocolManager);
/// @notice Transfer protocol manager implementation address
/// @param _protocolManager new implementation address
function updateSherlockProtocolManager(ISherlockProtocolManager _protocolManager) external;
/// @notice View current address able to pull payouts
/// @return Address able to pull payouts
function sherlockClaimManager() external view returns (ISherlockClaimManager);
/// @notice Transfer claim manager role to different address
/// @param _claimManager New address of claim manager
function updateSherlockClaimManager(ISherlockClaimManager _claimManager) external;
/// @notice Update yield strategy
/// @param _yieldStrategy New address of the strategy
/// @dev try a yieldStrategyWithdrawAll() on old, ignore failure
function updateYieldStrategy(IStrategyManager _yieldStrategy) external;
/// @notice Update yield strategy ignoring current state
/// @param _yieldStrategy New address of the strategy
/// @dev tries a yieldStrategyWithdrawAll() on old strategy, ignore failure
function updateYieldStrategyForce(IStrategyManager _yieldStrategy) external;
/// @notice Read current strategy
/// @return Address of current strategy
/// @dev can never be address(0)
function yieldStrategy() external view returns (IStrategyManager);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
/// @title Sherlock interface for payout manager
/// @author Evert Kors
interface ISherlockPayout {
/// @notice Initiate a payout of `_amount` to `_receiver`
/// @param _receiver Receiver of payout
/// @param _amount Amount to send
/// @dev only payout manager should call this
/// @dev should pull money out of strategy
function payoutClaim(address _receiver, uint256 _amount) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import './managers/IStrategyManager.sol';
/// @title Sherlock core interface for yield strategy
/// @author Evert Kors
interface ISherlockStrategy {
/// @notice Deposit `_amount` into active strategy
/// @param _amount Amount of tokens
/// @dev gov only
function yieldStrategyDeposit(uint256 _amount) external;
/// @notice Withdraw `_amount` from active strategy
/// @param _amount Amount of tokens
/// @dev gov only
function yieldStrategyWithdraw(uint256 _amount) external;
/// @notice Withdraw all funds from active strategy
/// @dev gov only
function yieldStrategyWithdrawAll() external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import './IManager.sol';
interface ISherDistributionManager is IManager {
// anyone can just send token to this contract to fund rewards
event Initialized(uint256 maxRewardsEndTVL, uint256 zeroRewardsStartTVL, uint256 maxRewardRate);
/// @notice Caller will receive `_sher` SHER tokens based on `_amount` and `_period`
/// @param _amount Amount of tokens (in USDC) staked
/// @param _period Period of time for stake, in seconds
/// @param _id ID for this NFT position
/// @param _receiver Address that will be linked to this position
/// @return _sher Amount of SHER tokens sent to Sherlock core contract
/// @dev Calling contract will depend on before + after balance diff and return value
/// @dev INCLUDES stake in calculation, function expects the `_amount` to be deposited already
/// @dev If tvl=50 and amount=50, this means it is calculating SHER rewards for the first 50 tokens going in
function pullReward(
uint256 _amount,
uint256 _period,
uint256 _id,
address _receiver
) external returns (uint256 _sher);
/// @notice Calculates how many `_sher` SHER tokens are owed to a stake position based on `_amount` and `_period`
/// @param _tvl TVL to use for reward calculation (pre-stake TVL)
/// @param _amount Amount of tokens (USDC) staked
/// @param _period Stake period (in seconds)
/// @return _sher Amount of SHER tokens owed to this stake position
/// @dev EXCLUDES `_amount` of stake, this will be added on top of TVL (_tvl is excluding _amount)
/// @dev If tvl=0 and amount=50, it would calculate for the first 50 tokens going in (different from pullReward())
function calcReward(
uint256 _tvl,
uint256 _amount,
uint256 _period
) external view returns (uint256 _sher);
/// @notice Function used to check if this is the current active distribution manager
/// @return Boolean indicating it's active
/// @dev If inactive the owner can pull all ERC20s and ETH
/// @dev Will be checked by calling the sherlock contract
function isActive() external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import './IManager.sol';
/// @title Sherlock core interface for protocols
/// @author Evert Kors
interface ISherlockProtocolManager is IManager {
// msg.sender is not authorized to call this function
error Unauthorized();
// If a protocol was never instantiated or was removed and the claim deadline has passed, this error is returned
error ProtocolNotExists(bytes32 protocol);
// When comparing two arrays and the lengths are not equal (but are supposed to be equal)
error UnequalArrayLength();
// If there is not enough balance in the contract for the amount requested (after any requirements are met), this is returned
error InsufficientBalance(bytes32 protocol);
event MinBalance(uint256 previous, uint256 current);
event AccountingError(bytes32 indexed protocol, uint256 amount, uint256 insufficientTokens);
event ProtocolAdded(bytes32 indexed protocol);
event ProtocolRemovedByArb(bytes32 indexed protocol, address arb, uint256 profit);
event ProtocolRemoved(bytes32 indexed protocol);
event ProtocolUpdated(
bytes32 indexed protocol,
bytes32 coverage,
uint256 nonStakers,
uint256 coverageAmount
);
event ProtocolAgentTransfer(bytes32 indexed protocol, address from, address to);
event ProtocolBalanceDeposited(bytes32 indexed protocol, uint256 amount);
event ProtocolBalanceWithdrawn(bytes32 indexed protocol, uint256 amount);
event ProtocolPremiumChanged(bytes32 indexed protocol, uint256 oldPremium, uint256 newPremium);
/// @notice View current amount of all premiums that are owed to stakers
/// @return Premiums claimable
/// @dev Will increase every block
/// @dev base + (now - last_settled) * ps
function claimablePremiums() external view returns (uint256);
/// @notice Transfer current claimable premiums (for stakers) to core Sherlock address
/// @dev Callable by everyone
/// @dev Funds will be transferred to Sherlock core contract
function claimPremiumsForStakers() external;
/// @notice View current protocolAgent of `_protocol`
/// @param _protocol Protocol identifier
/// @return Address able to submit claims
function protocolAgent(bytes32 _protocol) external view returns (address);
/// @notice View current premium of protocol
/// @param _protocol Protocol identifier
/// @return Amount of premium `_protocol` pays per second
function premium(bytes32 _protocol) external view returns (uint256);
/// @notice View current active balance of covered protocol
/// @param _protocol Protocol identifier
/// @return Active balance
/// @dev Accrued debt is subtracted from the stored active balance
function activeBalance(bytes32 _protocol) external view returns (uint256);
/// @notice View seconds of coverage left for `_protocol` before it runs out of active balance
/// @param _protocol Protocol identifier
/// @return Seconds of coverage left
function secondsOfCoverageLeft(bytes32 _protocol) external view returns (uint256);
/// @notice Add a new protocol to Sherlock
/// @param _protocol Protocol identifier
/// @param _protocolAgent Address able to submit a claim on behalf of the protocol
/// @param _coverage Hash referencing the active coverage agreement
/// @param _nonStakers Percentage of premium payments to nonstakers, scaled by 10**18
/// @param _coverageAmount Max amount claimable by this protocol
/// @dev Adding a protocol allows the `_protocolAgent` to submit a claim
/// @dev Coverage is not started yet as the protocol doesn't pay a premium at this point
/// @dev `_nonStakers` is scaled by 10**18
/// @dev Only callable by governance
function protocolAdd(
bytes32 _protocol,
address _protocolAgent,
bytes32 _coverage,
uint256 _nonStakers,
uint256 _coverageAmount
) external;
/// @notice Update info regarding a protocol
/// @param _protocol Protocol identifier
/// @param _coverage Hash referencing the active coverage agreement
/// @param _nonStakers Percentage of premium payments to nonstakers, scaled by 10**18
/// @param _coverageAmount Max amount claimable by this protocol
/// @dev Only callable by governance
function protocolUpdate(
bytes32 _protocol,
bytes32 _coverage,
uint256 _nonStakers,
uint256 _coverageAmount
) external;
/// @notice Remove a protocol from coverage
/// @param _protocol Protocol identifier
/// @dev Before removing a protocol the premium must be 0
/// @dev Removing a protocol basically stops the `_protocolAgent` from being active (can still submit claims until claim deadline though)
/// @dev Pays off debt + sends remaining balance to protocol agent
/// @dev This call should be subject to a timelock
/// @dev Only callable by governance
function protocolRemove(bytes32 _protocol) external;
/// @notice Remove a protocol with insufficient active balance
/// @param _protocol Protocol identifier
function forceRemoveByActiveBalance(bytes32 _protocol) external;
/// @notice Removes a protocol with insufficent seconds of coverage left
/// @param _protocol Protocol identifier
function forceRemoveBySecondsOfCoverage(bytes32 _protocol) external;
/// @notice View minimal balance needed before liquidation can start
/// @return Minimal balance needed
function minActiveBalance() external view returns (uint256);
/// @notice Sets the minimum active balance before an arb can remove a protocol
/// @param _minActiveBalance Minimum balance needed (in USDC)
/// @dev Only gov
function setMinActiveBalance(uint256 _minActiveBalance) external;
/// @notice Set premium of `_protocol` to `_premium`
/// @param _protocol Protocol identifier
/// @param _premium Amount of premium `_protocol` pays per second
/// @dev The value 0 would mean inactive coverage
/// @dev Only callable by governance
function setProtocolPremium(bytes32 _protocol, uint256 _premium) external;
/// @notice Set premium of multiple protocols
/// @param _protocol Array of protocol identifiers
/// @param _premium Array of premium amounts protocols pay per second
/// @dev The value 0 would mean inactive coverage
/// @dev Only callable by governance
function setProtocolPremiums(bytes32[] calldata _protocol, uint256[] calldata _premium) external;
/// @notice Deposits `_amount` of token to the active balance of `_protocol`
/// @param _protocol Protocol identifier
/// @param _amount Amount of tokens to deposit
/// @dev Approval should be made before calling
function depositToActiveBalance(bytes32 _protocol, uint256 _amount) external;
/// @notice Withdraws `_amount` of token from the active balance of `_protocol`
/// @param _protocol Protocol identifier
/// @param _amount Amount of tokens to withdraw
/// @dev Only protocol agent is able to withdraw
/// @dev Balance can be withdrawn up until 7 days worth of active balance
function withdrawActiveBalance(bytes32 _protocol, uint256 _amount) external;
/// @notice Transfer protocol agent role
/// @param _protocol Protocol identifier
/// @param _protocolAgent Account able to submit a claim on behalf of the protocol
/// @dev Only the active protocolAgent is able to transfer the role
function transferProtocolAgent(bytes32 _protocol, address _protocolAgent) external;
/// @notice View the amount nonstakers can claim from this protocol
/// @param _protocol Protocol identifier
/// @return Amount of tokens claimable by nonstakers
/// @dev this reads from a storage variable + (now-lastsettled) * premiums
function nonStakersClaimable(bytes32 _protocol) external view returns (uint256);
/// @notice Choose an `_amount` of tokens that nonstakers (`_receiver` address) will receive from `_protocol`
/// @param _protocol Protocol identifier
/// @param _amount Amount of tokens
/// @param _receiver Address to receive tokens
/// @dev Only callable by nonstakers role
function nonStakersClaim(
bytes32 _protocol,
uint256 _amount,
address _receiver
) external;
/// @param _protocol Protocol identifier
/// @return current and previous are the current and previous coverage amounts for this protocol
function coverageAmounts(bytes32 _protocol)
external
view
returns (uint256 current, uint256 previous);
/// @notice Function used to check if this is the current active protocol manager
/// @return Boolean indicating it's active
/// @dev If inactive the owner can pull all ERC20s and ETH
/// @dev Will be checked by calling the sherlock contract
function isActive() external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import './callbacks/ISherlockClaimManagerCallbackReceiver.sol';
import '../UMAprotocol/OptimisticRequester.sol';
import './IManager.sol';
interface ISherlockClaimManager is IManager, OptimisticRequester {
// Doesn't allow a new claim to be submitted by a protocol agent if a claim is already active for that protocol
error ClaimActive();
// If the current state of a claim does not match the expected state, this error is thrown
error InvalidState();
event ClaimCreated(
uint256 claimID,
bytes32 indexed protocol,
uint256 amount,
address receiver,
bool previousCoverageUsed
);
event CallbackAdded(ISherlockClaimManagerCallbackReceiver callback);
event CallbackRemoved(ISherlockClaimManagerCallbackReceiver callback);
event ClaimStatusChanged(uint256 indexed claimID, State previousState, State currentState);
event ClaimPayout(uint256 claimID, address receiver, uint256 amount);
event ClaimHalted(uint256 claimID);
event UMAHORenounced();
enum State {
NonExistent, // Claim doesn't exist (this is the default state on creation)
SpccPending, // Claim is created, SPCC is able to set state to valid
SpccApproved, // Final state, claim is valid
SpccDenied, // Claim denied by SPCC, claim can be escalated within 4 weeks
UmaPriceProposed, // Price is proposed but not escalated
ReadyToProposeUmaDispute, // Price is proposed, callback received, ready to submit dispute
UmaDisputeProposed, // Escalation is done, waiting for confirmation
UmaPending, // Claim is escalated, in case Spcc denied or didn't act within 7 days.
UmaApproved, // Final state, claim is valid, claim can be enacted after 1 day, umaHaltOperator has 1 day to change to denied
UmaDenied, // Final state, claim is invalid
Halted, // UMAHO can halt claim if state is UmaApproved
Cleaned // Claim is removed by protocol agent
}
struct Claim {
uint256 created;
uint256 updated;
address initiator;
bytes32 protocol;
uint256 amount;
address receiver;
uint32 timestamp;
State state;
bytes ancillaryData;
}
// requestAndProposePriceFor() --> proposer = sherlockCore (address to receive BOND if UMA denies claim)
// disputePriceFor() --> disputer = protocolAgent
// priceSettled will be the the callback that contains the main data
// Assume BOND = 9600, UMA's final fee = 1500.
// Claim initiator (Sherlock) has to pay 22.2k to dispute a claim,
// so we will execute a safeTransferFrom(claimInitiator, address(this), 22.2k).
// We need to approve the contract 22.2k as it will be transferred from address(this).
// The 22.2k consists of 2 * (BOND + final fee charged by UMA), as follows:
// 1. On requestAndProposePriceFor(), the fee will be 10k: 9600 BOND + 1500 UMA's final fee;
// 2. On disputePriceFor(), the fee will be the same 10k.
// note that half of the BOND (4800) + UMA's final fee (1500) is "burnt" and sent to UMA
// UMA's final fee can be changed in the future, which may result in lower or higher required staked amounts for escalating a claim.
// On settle, either the protocolAgent (dispute success) or sherlockCore (dispute failure)
// will receive 9600 + 4800 + 1500 = 15900. In addition, the protocolAgent will be entitled to
// the claimAmount if the dispute is successful/
// lastClaimID <-- starts with 0, so initial id = 1
// have claim counter, easy to identify certain claims by their number
// but use hash(callback.request.propose + callback.timestamp) as the internal UUID to handle the callbacks
// So SPCC and UMAHO are hardcoded (UMAHO can be renounced)
// In case these need to be updated, deploy different contract and upgrade it on the sherlock gov side.
// On price proposed callback --> call disputePriceFor with callbackdata + sherlock.strategyManager() and address(this)
/// @notice `SHERLOCK_CLAIM` in utf8
function UMA_IDENTIFIER() external view returns (bytes32);
function sherlockProtocolClaimsCommittee() external view returns (address);
/// @notice operator is able to deny approved UMA claims
function umaHaltOperator() external view returns (address);
/// @notice gov is able to renounce the role
function renounceUmaHaltOperator() external;
function claim(uint256 _claimID) external view returns (Claim memory);
/// @notice Initiate a claim for a specific protocol as the protocol agent
/// @param _protocol protocol ID (different from the internal or public claim ID fields)
/// @param _amount amount of USDC which is being claimed by the protocol
/// @param _receiver address to receive the amount of USDC being claimed
/// @param _timestamp timestamp at which the exploit first occurred
/// @param ancillaryData other data associated with the claim, such as the coverage agreement
/// @dev The protocol agent that starts a claim will be the protocol agent during the claims lifecycle
/// @dev Even if the protocol agent role is tranferred during the lifecycle
function startClaim(
bytes32 _protocol,
uint256 _amount,
address _receiver,
uint32 _timestamp,
bytes memory ancillaryData
) external;
function spccApprove(uint256 _claimID) external;
function spccRefuse(uint256 _claimID) external;
/// @notice Callable by protocol agent
/// @param _claimID Public claim ID
/// @param _amount Bond amount sent by protocol agent
/// @dev Use hardcoded USDC address
/// @dev Use hardcoded bond amount
/// @dev Use hardcoded liveness 7200 (2 hours)
/// @dev proposedPrice = _amount
function escalate(uint256 _claimID, uint256 _amount) external;
/// @notice Execute claim, storage will be removed after
/// @param _claimID Public ID of the claim
/// @dev Needs to be SpccApproved or UmaApproved && >UMAHO_TIME
/// @dev Funds will be pulled from core
function payoutClaim(uint256 _claimID) external;
/// @notice UMAHO is able to execute a halt if the state is UmaApproved and state was updated less than UMAHO_TIME ago
function executeHalt(uint256 _claimID) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.10;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
interface ISherlockClaimManagerCallbackReceiver {
/// @notice Calls this function on approved contracts and passes args
/// @param _protocol The protocol that is receiving the payout
/// @param _claimID The claim ID that is receiving the payout
/// @param _amount The amount of USDC being paid out for this claim
function PreCorePayoutCallback(
bytes32 _protocol,
uint256 _claimID,
uint256 _amount
) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import './SkinnyOptimisticOracleInterface.sol';
/**
* @title Optimistic Requester.
* @notice Optional interface that requesters can implement to receive callbacks.
* @dev This contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
interface OptimisticRequester {
/**
* @notice Callback for proposals.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param request request params after proposal.
*/
function priceProposed(
bytes32 identifier,
uint32 timestamp,
bytes memory ancillaryData,
SkinnyOptimisticOracleInterface.Request memory request
) external;
/**
* @notice Callback for disputes.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param request request params after dispute.
*/
function priceDisputed(
bytes32 identifier,
uint32 timestamp,
bytes memory ancillaryData,
SkinnyOptimisticOracleInterface.Request memory request
) external;
/**
* @notice Callback for settlement.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param request request params after settlement.
*/
function priceSettled(
bytes32 identifier,
uint32 timestamp,
bytes memory ancillaryData,
SkinnyOptimisticOracleInterface.Request memory request
) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import './OptimisticOracleInterface.sol';
/**
* @title Interface for the gas-cost-reduced version of the OptimisticOracle.
* @notice Differences from normal OptimisticOracle:
* - refundOnDispute: flag is removed, by default there are no refunds on disputes.
* - customizing request parameters: In the OptimisticOracle, parameters like `bond` and `customLiveness` can be reset
* after a request is already made via `requestPrice`. In the SkinnyOptimisticOracle, these parameters can only be
* set in `requestPrice`, which has an expanded input set.
* - settleAndGetPrice: Replaced by `settle`, which can only be called once per settleable request. The resolved price
* can be fetched via the `Settle` event or the return value of `settle`.
* - general changes to interface: Functions that interact with existing requests all require the parameters of the
* request to modify to be passed as input. These parameters must match with the existing request parameters or the
* function will revert. This change reflects the internal refactor to store hashed request parameters instead of the
* full request struct.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract SkinnyOptimisticOracleInterface {
event RequestPrice(
address indexed requester,
bytes32 indexed identifier,
uint32 timestamp,
bytes ancillaryData,
Request request
);
event ProposePrice(
address indexed requester,
bytes32 indexed identifier,
uint32 timestamp,
bytes ancillaryData,
Request request
);
event DisputePrice(
address indexed requester,
bytes32 indexed identifier,
uint32 timestamp,
bytes ancillaryData,
Request request
);
event Settle(
address indexed requester,
bytes32 indexed identifier,
uint32 timestamp,
bytes ancillaryData,
Request request
);
// Struct representing a price request. Note that this differs from the OptimisticOracleInterface's Request struct
// in that refundOnDispute is removed.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length over a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @param bond custom proposal bond to set for request. If set to 0, defaults to the final fee.
* @param customLiveness custom proposal liveness to set for request.
* @return totalBond default bond + final fee that the proposer and disputer will be required to pay.
*/
function requestPrice(
bytes32 identifier,
uint32 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward,
uint256 bond,
uint256 customLiveness
) external virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param request price request parameters whose hash must match the request that the caller wants to
* propose a price for.
* @param proposer address to set as the proposer.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address requester,
bytes32 identifier,
uint32 timestamp,
bytes memory ancillaryData,
Request memory request,
address proposer,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value where caller is the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param request price request parameters whose hash must match the request that the caller wants to
* propose a price for.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint32 timestamp,
bytes memory ancillaryData,
Request memory request,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Combines logic of requestPrice and proposePrice while taking advantage of gas savings from not having to
* overwrite Request params that a normal requestPrice() => proposePrice() flow would entail. Note: The proposer
* will receive any rewards that come from this proposal. However, any bonds are pulled from the caller.
* @dev The caller is the requester, but the proposer can be customized.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @param bond custom proposal bond to set for request. If set to 0, defaults to the final fee.
* @param customLiveness custom proposal liveness to set for request.
* @param proposer address to set as the proposer.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function requestAndProposePriceFor(
bytes32 identifier,
uint32 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward,
uint256 bond,
uint256 customLiveness,
address proposer,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param request price request parameters whose hash must match the request that the caller wants to
* dispute.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePriceFor(
bytes32 identifier,
uint32 timestamp,
bytes memory ancillaryData,
Request memory request,
address disputer,
address requester
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal where caller is the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param request price request parameters whose hash must match the request that the caller wants to
* dispute.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint32 timestamp,
bytes memory ancillaryData,
Request memory request
) external virtual returns (uint256 totalBond);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param request price request parameters whose hash must match the request that the caller wants to
* settle.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
* @return resolvedPrice the price that the request settled to.
*/
function settle(
address requester,
bytes32 identifier,
uint32 timestamp,
bytes memory ancillaryData,
Request memory request
) external virtual returns (uint256 payout, int256 resolvedPrice);
/**
* @notice Computes the current state of a price request. See the State enum for more details.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param request price request parameters.
* @return the State.
*/
function getState(
address requester,
bytes32 identifier,
uint32 timestamp,
bytes memory ancillaryData,
Request memory request
) external virtual returns (OptimisticOracleInterface.State);
/**
* @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param request price request parameters. The hash of these parameters must match with the request hash that is
* associated with the price request unique ID {requester, identifier, timestamp, ancillaryData}, or this method
* will revert.
* @return boolean indicating true if price exists and false if not.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint32 timestamp,
bytes memory ancillaryData,
Request memory request
) public virtual returns (bool);
/**
* @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute.
* @param ancillaryData ancillary data of the price being requested.
* @param requester sender of the initial price request.
* @return the stamped ancillary bytes.
*/
function stampAncillaryData(bytes memory ancillaryData, address requester)
public
pure
virtual
returns (bytes memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OptimisticOracleInterface {
// Struct representing the state of a price request.
enum State {
Invalid, // Never requested.
Requested, // Requested, no other actions taken.
Proposed, // Proposed, but not expired or disputed yet.
Expired, // Proposed, not disputed, past liveness.
Disputed, // Disputed, but no DVM price returned yet.
Resolved, // Disputed and DVM price is available.
Settled // Final price has been set in the contract (can get here from Expired or Resolved).
}
// Struct representing a price request.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
bool refundOnDispute; // True if the requester should be refunded their reward on dispute.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length over a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was value (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
/**
* @notice Returns the state of a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State enum value.
*/
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
/**
* @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return true if price has resolved or settled, false otherwise.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
function stampAncillaryData(bytes memory ancillaryData, address requester)
public
view
virtual
returns (bytes memory);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.10;
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: agpl-3.0
pragma solidity 0.8.10;
pragma experimental ABIEncoderV2;
library DistributionTypes {
struct AssetConfigInput {
uint104 emissionPerSecond;
uint256 totalStaked;
address underlyingAsset;
}
struct UserStakeInput {
address underlyingAsset;
uint256 stakedByUser;
uint256 totalStaked;
}
}
interface IAaveDistributionManager {
event AssetConfigUpdated(address indexed asset, uint256 emission);
event AssetIndexUpdated(address indexed asset, uint256 index);
event UserIndexUpdated(address indexed user, address indexed asset, uint256 index);
event DistributionEndUpdated(uint256 newDistributionEnd);
/**
* @dev Sets the end date for the distribution
* @param distributionEnd The end date timestamp
**/
function setDistributionEnd(uint256 distributionEnd) external;
/**
* @dev Gets the end date for the distribution
* @return The end of the distribution
**/
function getDistributionEnd() external view returns (uint256);
/**
* @dev for backwards compatibility with the previous DistributionManager used
* @return The end of the distribution
**/
function DISTRIBUTION_END() external view returns (uint256);
/**
* @dev Returns the data of an user on a distribution
* @param user Address of the user
* @param asset The address of the reference asset of the distribution
* @return The new index
**/
function getUserAssetData(address user, address asset) external view returns (uint256);
/**
* @dev Returns the configuration of the distribution for a certain asset
* @param asset The address of the reference asset of the distribution
* @return The asset index, the emission per second and the last updated timestamp
**/
function getAssetData(address asset)
external
view
returns (
uint256,
uint256,
uint256
);
}
|
Only contract owner can call this Sends all specified tokens in this contract to the receiver's address (as well as ETH) This contract must NOT be the current assigned yield strategy contract Executes the sweep for ERC-20s specified in _extraTokens as well as for ETH
|
function sweep(address _receiver, IERC20[] memory _extraTokens) external onlyOwner {
if (_receiver == address(0)) revert ZeroArgument();
if (isActive()) revert InvalidConditions();
_sweep(_receiver, _extraTokens);
}
| 1,145,770 |
./partial_match/1/0x0092CD4044E1672c9c513867eb75e6213AF9742f/sources/src/LlamaPolicy.sol
|
Returns `true` if the `policyholder` has the `role` at `timestamp`, `false` otherwise. policyholder Policyholder to check if they have the role. role ID of the role. timestamp Timestamp to check if the role was held at. return `true` if the `policyholder` has the `role` at `timestamp`, `false` otherwise.
|
function hasRole(address policyholder, uint8 role, uint256 timestamp) external view returns (bool) {
uint256 quantity = roleBalanceCkpts[_tokenId(policyholder)][role].getAtProbablyRecentTimestamp(timestamp);
return quantity > 0;
}
| 9,329,979 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./NFTYToken.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
contract NFTYStakingUpgradeable is
AccessControlUpgradeable,
ReentrancyGuardUpgradeable
{
// state variables
NFTYToken nftyToken;
address private _NFTYTokenAddress;
uint256 private _totalStakedToken;
uint256[6] private _rewardRate;
// creating a new role for admin
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
// event for informing a new stake
event NewStake(address indexed staker, uint256 amount);
// event for informing the release of reward
event RewardReleased(address indexed staker, uint256 reward);
//event for informing the addition of amount to the existing stake
event StakeUpgraded(
address indexed staker,
uint256 amount,
uint256 totalStake
);
// event for informing when someone unstakes
event StakeReleased(
address indexed staker,
uint256 amount,
uint256 remainingStake
);
// event for informing the change of reward rate
event RateChanged(
address indexed admin,
uint8 rank,
uint256 oldRate,
uint256 newRate
);
// event for informing the transfer of all tokens
// to the nfty owner
event TransferredAllTokens(address caller, uint256 amount);
// modifier for checking the zero address
modifier isRealAddress(address account) {
require(account != address(0), "NFTYStaking: address is zero address");
_;
}
// modifier for checking the real amount
modifier isRealValue(uint256 value) {
require(value > 0, "NFTYStaking: value must be greater than zero");
_;
}
// modifier for checking if the sendeer is a staker
modifier isStaker(address account) {
require(
StakersData[account].amount > 0,
"NFTYStaking: caller is not a staker"
);
_;
}
// structure for storing the staker data
struct StakeData {
uint256 amount;
uint256 reward;
uint256 stakingTime;
uint256 lastClaimTime;
}
// mapping for pointing to the stakers data
mapping(address => StakeData) public StakersData;
function initialize(address NFTYTokenAddress)
public
isRealAddress(NFTYTokenAddress)
isRealAddress(_msgSender())
initializer
{
__ReentrancyGuard_init();
__AccessControl_init();
_setupRole(ADMIN_ROLE, _msgSender());
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
_NFTYTokenAddress = NFTYTokenAddress;
nftyToken = NFTYToken(NFTYTokenAddress);
_rewardRate = [13579, 14579, 15079, 15579, 15829, 16079]; // 13.579%, 14.579%, 15.079%, 15.579%, 16.079%
}
function transferOwnership(address _newOwner)
external
onlyRole(ADMIN_ROLE)
{
nftyToken.transferOwnership(_newOwner);
}
// function for staking the token
function stakeTokens(uint256 amount)
external
isRealAddress(_msgSender())
isRealValue(amount)
returns (bool)
{
require(amount >= _getAmount(1), "NFTYStaking: min stake amount is 1");
require(
nftyToken.balanceOf(_msgSender()) >= amount,
"NFTYStaking: insufficient balance"
);
StakeData storage stakeData = StakersData[_msgSender()];
uint256 _amount = stakeData.amount;
// if already staking then add the amount to the existing stake
if (_amount > 0) {
// calculate the reward for the existing amount
uint256 reward = _getReward(
stakeData.stakingTime,
stakeData.lastClaimTime,
_amount
);
// update staker's data
stakeData.reward += reward;
stakeData.amount = _amount + amount;
// emit the event for informing the upgraded stake
emit StakeUpgraded(_msgSender(), amount, stakeData.amount);
} else {
// update staker's data
stakeData.amount = amount;
stakeData.stakingTime = block.timestamp;
// emit the event for informing the new stake
emit NewStake(_msgSender(), amount);
}
stakeData.lastClaimTime = block.timestamp;
// update the pool
_totalStakedToken += amount;
// transfer the amount to the staking contract
bool result = nftyToken.transferFrom(
_msgSender(),
address(this),
amount
);
return result;
}
// function for claiming reward
function claimRewards()
external
isRealAddress(_msgSender())
isStaker(_msgSender())
{
require(
nftyToken.owner() == address(this),
"Staking contract is not the owner."
);
StakeData storage stakeData = StakersData[_msgSender()];
uint256 _amount = stakeData.amount;
uint256 reward = _getReward(
stakeData.stakingTime,
stakeData.lastClaimTime,
_amount
);
reward = stakeData.reward + reward;
// update the staker data
stakeData.reward = 0;
stakeData.lastClaimTime = block.timestamp;
// emit the event for informing the release of reward
emit RewardReleased(_msgSender(), reward);
// mint the reward back to the stakers account
nftyToken.mint(_msgSender(), reward);
}
// function for showing the reward at any time
function showReward(address account)
external
view
isRealAddress(_msgSender())
isRealAddress(account)
isStaker(account)
returns (uint256)
{
StakeData storage stakeData = StakersData[account];
uint256 _amount = stakeData.amount;
uint256 reward = _getReward(
stakeData.stakingTime,
stakeData.lastClaimTime,
_amount
);
reward = stakeData.reward + reward;
return reward;
}
// function for unstaking all the tokens
function unstakeAll() external {
StakeData storage stakeData = StakersData[_msgSender()];
uint256 amount = stakeData.amount;
unstakeTokens(amount);
}
// function for changing the reward rate
function changeRate(uint8 rank, uint256 rate)
external
onlyRole(ADMIN_ROLE)
{
require(rate > 0 && rate <= 100000, "NFTYStaking: invalid rate");
require(rank < 6, "NFTYStaking: invalid rank");
uint256 oldRate = _rewardRate[rank];
_rewardRate[rank] = rate;
// emit the event for informing the change of rate
emit RateChanged(_msgSender(), rank, oldRate, rate);
}
// function for returning the current reward rate
function getRewardRates() external view returns (uint256[6] memory) {
return _rewardRate;
}
// function for returning total stake token (pool)
function getPool() external view returns (uint256) {
return _totalStakedToken;
}
function getRewardRate(uint256 amount, uint256 stakingTime)
public
view
returns (uint256 rewardRate)
{
uint256 rewardRate1;
uint256 rewardRate2;
stakingTime = block.timestamp - stakingTime;
// reward rate based on the staking amount
if (amount >= _getAmount(1) && amount < _getAmount(500)) {
rewardRate1 = _rewardRate[0];
} else if (amount >= _getAmount(500) && amount < _getAmount(10000)) {
rewardRate1 = _rewardRate[1];
} else if (amount >= _getAmount(10000) && amount < _getAmount(25000)) {
rewardRate1 = _rewardRate[2];
} else if (amount >= _getAmount(25000) && amount < _getAmount(50000)) {
rewardRate1 = _rewardRate[3];
} else if (amount >= _getAmount(50000) && amount < _getAmount(100000)) {
rewardRate1 = _rewardRate[4];
} else {
rewardRate1 = _rewardRate[5];
}
// reward rate based on staking time
if (stakingTime < 30 days) {
rewardRate2 = _rewardRate[0];
} else if (stakingTime >= 30 days && stakingTime < 45 days) {
rewardRate2 = _rewardRate[1];
} else if (stakingTime >= 45 days && stakingTime < 90 days) {
rewardRate2 = _rewardRate[2];
} else if (stakingTime >= 90 days && stakingTime < 180 days) {
rewardRate2 = _rewardRate[3];
} else if (stakingTime >= 180 days && stakingTime < 365 days) {
rewardRate2 = _rewardRate[4];
} else {
rewardRate2 = _rewardRate[5];
}
// find exact reward rate
rewardRate = rewardRate1 < rewardRate2 ? rewardRate1 : rewardRate2;
}
// function for unstaking the specified amount
function unstakeTokens(uint256 amount)
public
isRealAddress(_msgSender())
isRealValue(amount)
isStaker(_msgSender())
{
require(
nftyToken.owner() == address(this),
"Staking contract is not the owner."
);
StakeData storage stakeData = StakersData[_msgSender()];
uint256 _amount = stakeData.amount;
// check if the user has enough amount to unstake
require(_amount >= amount, "NFTYStaking: not enough staked token");
uint256 reward = _getReward(
stakeData.stakingTime,
stakeData.lastClaimTime,
_amount
);
// if the staker is unstaking the whole amount
if (stakeData.amount == amount) {
uint256 totReward = reward + stakeData.reward;
// update the staker data
stakeData.reward = 0;
stakeData.stakingTime = 0;
// emit the event for informing the release of reward
emit RewardReleased(_msgSender(), totReward);
// mint reward to the user
nftyToken.mint(_msgSender(), totReward);
} else {
// update the staker data
stakeData.reward += reward;
}
stakeData.amount -= amount;
stakeData.lastClaimTime = block.timestamp;
_totalStakedToken -= amount;
// emit the event for informing the unstake of tokens
emit StakeReleased(_msgSender(), amount, stakeData.amount);
nftyToken.transfer(_msgSender(), amount);
}
// function for finding the reward based on compound equation
function _getReward(
uint256 stakingTime,
uint256 lastClaimTime,
uint256 amount
) internal view returns (uint256 reward) {
uint256 rewardRate = getRewardRate(amount, stakingTime);
uint256 rewardTime = block.timestamp - lastClaimTime;
uint256 rateForSecond = (rewardRate * 10**18) / 365 days;
reward = (amount * rateForSecond * rewardTime) / 10**23;
return reward;
}
// function for retrieving the exact amount
function _getAmount(uint256 value) internal view returns (uint256) {
return value * 10**uint256(nftyToken.decimals());
}
}
// 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;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract NFTYToken is ERC20Upgradeable, OwnableUpgradeable {
function initialize() public initializer {
__ERC20_init("NFTY Token", "NFTY");
__Ownable_init();
_mint(owner(), 50000 * 10**uint256(decimals()));
}
function mint(address account, uint256 amount) external onlyOwner {
_mint(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_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);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
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 initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @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
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 "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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
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);
}
|
function for retrieving the exact amount
|
function _getAmount(uint256 value) internal view returns (uint256) {
return value * 10**uint256(nftyToken.decimals());
}
| 6,961,226 |
/*
Copyright 2017-2018 RigoBlock, Rigo Investment Sagl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.4.21;
pragma experimental "v0.5.0";
/// @title Casper Interface - Allows interaction with the Casoper contract.
/// @author Gabriele Rigo - <[email protected]>
interface CasperFace {
function deposit(address _validation, address _withdrawal) external payable;
function withdraw(uint128 _validatorIndex) external;
function get_deposit_size(uint128 _validatorIndex) external view returns (uint128);
function get_nextValidatorIndex() external view returns (uint128);
}
|
Casper Interface - Allows interaction with the Casoper contract. Gabriele Rigo - <[email protected]>
|
interface CasperFace {
function deposit(address _validation, address _withdrawal) external payable;
function withdraw(uint128 _validatorIndex) external;
function get_deposit_size(uint128 _validatorIndex) external view returns (uint128);
function get_nextValidatorIndex() external view returns (uint128);
}
| 15,841,829 |
pragma solidity ^0.4.24;
contract OffersAccessControl {
address public rootAddress;
address public adminAddress;
address public lostAndFoundAddress;
// The total amount of ether (in wei) in escrow owned by Root
uint256 public totalRootEarnings;
// The total amount of ether (in wei) in escrow owned by lostAndFound
uint256 public totalLostAndFoundBalance;
/// @notice Keeps track whether the contract is frozen.
/// When frozen is set to be true, it cannot be set back to false again,
/// and all whenNotFrozen actions will be blocked.
bool public frozen = false;
/// @notice Access modifier for Root-only functionality
modifier onlyRoot() {
require(msg.sender == rootAddress, "only Root is allowed to perform this operation");
_;
}
/// @notice Access modifier for Admin-only functionality
modifier onlyAdmin() {
require(msg.sender == adminAddress, "only Admin is allowed to perform this operation");
_;
}
/// @notice Access modifier for Admin-only or Root-only functionality
modifier onlyAdminOrRoot() {
require(
msg.sender != address(0) &&
(
msg.sender == adminAddress ||
msg.sender == rootAddress
),
"only Admin or Root is allowed to perform this operation"
);
_;
}
/// @notice Access modifier for LostAndFound-only functionality
modifier onlyLostAndFound() {
require(
msg.sender == lostAndFoundAddress &&
msg.sender != address(0),
"only LostAndFound is allowed to perform this operation"
);
_;
}
/// @notice Assigns a new address to act as the Admin. Only available to the current Admin or Root.
/// @param _newAdmin The address of the new Admin
function setAdmin(address _newAdmin) public onlyAdminOrRoot {
require(_newAdmin != address(0), "new Admin address cannot be the zero-account");
adminAddress = _newAdmin;
}
/// @notice Assigns a new address to act as the Root. Only available to the current Root.
/// @param _newRoot The address of the new Root
function setRoot(address _newRoot) external onlyRoot {
require(_newRoot != address(0), "new Root address cannot be the zero-account");
rootAddress = _newRoot;
}
/// @notice Assigns a new address to act as the LostAndFound account. Only available to the current Root
/// @param _newLostAndFound The address of the new lostAndFound address
function setLostAndFound(address _newLostAndFound) external onlyRoot {
require(_newLostAndFound != address(0), "new lost and found cannot be the zero-account");
lostAndFoundAddress = _newLostAndFound;
}
/// @notice Root withdraws the Root earnings
function withdrawTotalRootEarnings() external onlyRoot {
// Obtain reference
uint256 balance = totalRootEarnings;
totalRootEarnings = 0;
rootAddress.transfer(balance);
}
/// @notice LostAndFound account withdraws all the lost and found amount
function withdrawTotalLostAndFoundBalance() external onlyLostAndFound {
// Obtain reference
uint256 balance = totalLostAndFoundBalance;
totalLostAndFoundBalance = 0;
lostAndFoundAddress.transfer(balance);
}
/// @notice Modifier to allow actions only when the contract is not frozen
modifier whenNotFrozen() {
require(!frozen, "contract needs to not be frozen");
_;
}
/// @notice Modifier to allow actions only when the contract is frozen
modifier whenFrozen() {
require(frozen, "contract needs to be frozen");
_;
}
/// @notice Called by Root or Admin role to freeze the contract.
/// @dev A frozen contract will be frozen forever, there's no way to undo this action.
function freeze() external onlyAdminOrRoot whenNotFrozen {
frozen = true;
}
}
|
Assigns a new address to act as the Admin. Only available to the current Admin or Root. _newAdmin The address of the new Admin
|
function setAdmin(address _newAdmin) public onlyAdminOrRoot {
require(_newAdmin != address(0), "new Admin address cannot be the zero-account");
adminAddress = _newAdmin;
}
| 6,356,442 |
./partial_match/3/0x33ce17B1909712760EB526BCA0B5e79fC0C54d05/sources/FIRE.sol
|
A method for a stakeholder to remove a stake. _stake The size of the stake to be removed./
|
function removeStake(uint256 _stake, uint256 sessionID) public {
stakes[msg.sender] = stakes[msg.sender].sub(_stake);
if(stakes[msg.sender] == 0) removeStakeholder(msg.sender);
uint256 claimedAmount = claimableAmount(sessionID);
mint(msg.sender, claimedAmount);
}
| 5,141,000 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "./IO.sol";
import "./Storage.sol";
import "./Constants.sol";
import "./ABDKMath64x64.sol";
import "./ERC20.sol";
import "./SafeERC20.sol";
import "./SafeMath.sol";
contract Logic is Storage, Constants, IO {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using ABDKMath64x64 for int128;
using ABDKMath64x64 for uint256;
// **** Events **** //
event ModuleApproved(address indexed module);
event ModuleRevoked(address indexed module);
// **** Modifiers **** //
modifier authorized(bytes32 role) {
require(hasRole(role, msg.sender), "!authorized");
_;
}
modifier authorized2(bytes32 role1, bytes32 role2) {
require(hasRole(role1, msg.sender) || hasRole(role2, msg.sender), "!authorized");
_;
}
// **** Initializers **** //
/// @notice Initializes the Basket
/// @param _name Basket ERC20 name
/// @param _symbol Basket ERC20 symbol
/// @param _assets Assets within the basket
/// @param _timelock Address of the timelock contract
/// @param _governance Address of the governance contract
/// @param _marketMakers Addresses of the market makers (usually EOA)
function initialize(
string memory _name,
string memory _symbol,
address[] memory _assets,
uint256 _mintFee,
uint256 _burnFee,
address _feeRecipient,
address _timelock,
address _governance,
address[] memory _marketMakers
) public {
require(_readSlot(INITIALIZED) == 0, "initialized");
__ERC20_init(_name, _symbol);
// Setup assets in the basket
assets = _assets;
// Setup fee
_writeSlot(MINT_FEE, _mintFee);
_writeSlot(BURN_FEE, _burnFee);
_writeSlot(FEE_RECIPIENT, _feeRecipient);
// Setup roles
_setRoleAdmin(TIMELOCK, TIMELOCK_ADMIN);
_setupRole(TIMELOCK_ADMIN, _timelock);
_setupRole(TIMELOCK, _timelock);
// Timelock is also only allowed to set the migrator
_setRoleAdmin(MIGRATOR, TIMELOCK_ADMIN);
// Governance can set governance OR market maker
_setRoleAdmin(GOVERNANCE, GOVERNANCE_ADMIN);
_setRoleAdmin(MARKET_MAKER, GOVERNANCE_ADMIN);
_setupRole(GOVERNANCE_ADMIN, _governance);
_setupRole(GOVERNANCE, _governance);
// Market maker admin
_setRoleAdmin(MARKET_MAKER, MARKET_MAKER_ADMIN);
for (uint256 i = 0; i < _marketMakers.length; i++) {
_setupRole(MARKET_MAKER_ADMIN, _marketMakers[i]);
_setupRole(MARKET_MAKER, _marketMakers[i]);
}
// Make sure we can't initialize again
_writeSlot(INITIALIZED, bytes32(uint256(1)));
}
/// @notice Initializes the Basket token "weights"
/// @param _amountsIn The amount of tokens to supply, addresses referenced from `assets`
/// @param _amountOut How many Basket tokens to output
function mintExact(
address[] memory _assets,
uint256[] memory _amountsIn,
uint256 _amountOut
) public whenNotPaused authorized(MIGRATOR) {
require(_assets.length == assets.length, "!asset-length");
require(_amountsIn.length == _assets.length, "!amounts-in");
require(_amountOut >= 1e6, "min-mint-1e6");
for (uint256 i = 0; i < _amountsIn.length; i++) {
ERC20(_assets[i]).safeTransferFrom(msg.sender, address(this), _amountsIn[i]);
}
_mint(msg.sender, _amountOut);
}
// **** Getters **** //
/// @notice Gets the assets and their balances within the basket
/// @return (the addresses of the assets,
/// the amount held by the basket of each asset)
function getAssetsAndBalances() public view returns (address[] memory, uint256[] memory) {
uint256[] memory assetBalances = new uint256[](assets.length);
for (uint256 i = 0; i < assets.length; i++) {
assetBalances[i] = ERC20(assets[i]).balanceOf(address(this));
}
return (assets, assetBalances);
}
/// @notice Gets the amount of assets backing each Basket token
/// @return (the addresses of the assets,
/// the amount of backing 1 Basket token)
function getOne() public view returns (address[] memory, uint256[] memory) {
uint256[] memory amounts = new uint256[](assets.length);
uint256 supply = totalSupply();
for (uint256 i = 0; i < assets.length; i++) {
amounts[i] = ERC20(assets[i]).balanceOf(address(this)).mul(1e18).div(supply);
}
return (assets, amounts);
}
/// @notice Gets the fees and the fee recipient
/// @return (mint fee, burn fee, recipient)
function getFees()
public
view
returns (
uint256,
uint256,
address
)
{
return (_readSlotUint256(MINT_FEE), _readSlotUint256(BURN_FEE), _readSlotAddress(FEE_RECIPIENT));
}
// **** Admin functions **** //
/// @notice Pauses minting in case of emergency
function pause() public authorized2(GOVERNANCE, TIMELOCK) {
_pause();
}
/// @notice Unpauses burning in case of emergency
function unpause() public authorized2(GOVERNANCE, TIMELOCK) {
_unpause();
}
/// @notice Sets the mint/burn fee and fee recipient
function setFee(
uint256 _mintFee,
uint256 _burnFee,
address _recipient
) public authorized(TIMELOCK) {
require(_mintFee < FEE_DIVISOR, "invalid-mint-fee");
require(_burnFee < FEE_DIVISOR, "invalid-burn-fee");
require(_recipient != address(0), "invalid-fee-recipient");
_writeSlot(MINT_FEE, _mintFee);
_writeSlot(BURN_FEE, _burnFee);
_writeSlot(FEE_RECIPIENT, _recipient);
}
/// @notice Sets the list of assets backing the basket
function setAssets(address[] memory _assets) public authorized(TIMELOCK) whenNotPaused {
assets = _assets;
}
/// @notice Rescues ERC20 stuck in the contract (can't be on the list of assets)
function rescueERC20(address _asset, uint256 _amount) public authorized2(MARKET_MAKER, GOVERNANCE) {
for (uint256 i = 0; i < assets.length; i++) {
require(_asset != assets[i], "!rescue asset");
}
ERC20(_asset).safeTransfer(msg.sender, _amount);
}
/// @notice Approves a module.
/// @param _module Logic module to approve
function approveModule(address _module) public authorized(TIMELOCK) {
approvedModules[_module] = true;
emit ModuleApproved(_module);
}
/// @notice Revokes a module.
/// @param _module Logic module to approve
function revokeModule(address _module) public authorized2(TIMELOCK, GOVERNANCE) {
approvedModules[_module] = false;
emit ModuleRevoked(_module);
}
/// @notice Executes arbitrary logic on approved modules. Mostly used for rebalancing.
/// @param _module Logic code to assume
/// @param _data Payload
function execute(address _module, bytes memory _data)
public
payable
authorized2(GOVERNANCE, TIMELOCK)
returns (bytes memory response)
{
require(approvedModules[_module], "!module-approved");
// call contract in current context
assembly {
let succeeded := delegatecall(sub(gas(), 5000), _module, add(_data, 0x20), mload(_data), 0, 0)
let size := returndatasize()
response := mload(0x40)
mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))))
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(add(response, 0x20), size)
}
}
}
// **** Mint/Burn functionality **** //
/// @notice Mints a new Basket token
/// @param _amountOut Amount of Basket tokens to mint
function mint(uint256 _amountOut) public whenNotPaused nonReentrant {
require(totalSupply() > 0, "!migrated");
uint256[] memory _amountsToTransfer = viewMint(_amountOut);
for (uint256 i = 0; i < assets.length; i++) {
ERC20(assets[i]).safeTransferFrom(msg.sender, address(this), _amountsToTransfer[i]);
}
// If user is a market maker then just mint the tokens
if (hasRole(MARKET_MAKER, msg.sender)) {
_mint(msg.sender, _amountOut);
return;
}
// Otherwise charge a fee
uint256 fee = _amountOut.mul(_readSlotUint256(MINT_FEE)).div(FEE_DIVISOR);
address feeRecipient = _readSlotAddress(FEE_RECIPIENT);
_mint(feeRecipient, fee);
_mint(msg.sender, _amountOut.sub(fee));
}
/// @notice Previews the corresponding assets and amount required to mint `_amountOut` Basket tokens
/// @param _amountOut Amount of Basket tokens to mint
function viewMint(uint256 _amountOut) public view returns (uint256[] memory _amountsIn) {
uint256 totalLp = totalSupply();
_amountsIn = new uint256[](assets.length);
// Precise math
int128 amountOut128 = _amountOut.divu(1e18).add(uint256(1).divu(1e18));
int128 totalLp128 = totalLp.divu(1e18).add(uint256(1).divu(1e18));
int128 ratio128 = amountOut128.div(totalLp128);
uint256 _amountToTransfer;
for (uint256 i = 0; i < assets.length; i++) {
_amountToTransfer = ratio128.mulu(ERC20(assets[i]).balanceOf(address(this)));
_amountsIn[i] = _amountToTransfer;
}
}
/// @notice Burns the basket token and retrieves
/// @param _amount Amount of Basket tokens to burn
function burn(uint256 _amount) public whenNotPaused nonReentrant {
uint256 totalLp = totalSupply();
require(totalLp > 0, "!initialMint");
require(_amount >= 1e6, "!min-burn-1e6");
// Precise math library
int128 ratio128;
int128 totalLp128 = totalLp.divu(1e18).add(uint256(1).divu(1e18));
int128 amount128;
uint256 amountOut;
// If user is a market maker then no fee
if (hasRole(MARKET_MAKER, msg.sender)) {
amount128 = _amount.divu(1e18).add(uint256(1).divu(1e18));
ratio128 = amount128.div(totalLp128);
_burn(msg.sender, _amount);
} else {
// Otherwise calculate fee
address feeRecipient = _readSlotAddress(FEE_RECIPIENT);
uint256 fee = _amount.mul(_readSlotUint256(BURN_FEE)).div(FEE_DIVISOR);
amount128 = _amount.sub(fee).divu(1e18).add(uint256(1).divu(1e18));
ratio128 = amount128.div(totalLp128);
_burn(msg.sender, _amount.sub(fee));
_transfer(msg.sender, feeRecipient, fee);
}
for (uint256 i = 0; i < assets.length; i++) {
amountOut = ratio128.mulu(ERC20(assets[i]).balanceOf(address(this)));
ERC20(assets[i]).safeTransfer(msg.sender, amountOut);
}
}
}
|
Initializes the Basket _name Basket ERC20 name _symbol Basket ERC20 symbol _assets Assets within the basket _timelock Address of the timelock contract _governance Address of the governance contract _marketMakers Addresses of the market makers (usually EOA) Setup assets in the basket Setup fee Setup roles Timelock is also only allowed to set the migrator Governance can set governance OR market maker Market maker admin
|
function initialize(
string memory _name,
string memory _symbol,
address[] memory _assets,
uint256 _mintFee,
uint256 _burnFee,
address _feeRecipient,
address _timelock,
address _governance,
address[] memory _marketMakers
) public {
require(_readSlot(INITIALIZED) == 0, "initialized");
__ERC20_init(_name, _symbol);
assets = _assets;
_writeSlot(MINT_FEE, _mintFee);
_writeSlot(BURN_FEE, _burnFee);
_writeSlot(FEE_RECIPIENT, _feeRecipient);
_setRoleAdmin(TIMELOCK, TIMELOCK_ADMIN);
_setupRole(TIMELOCK_ADMIN, _timelock);
_setupRole(TIMELOCK, _timelock);
_setRoleAdmin(MIGRATOR, TIMELOCK_ADMIN);
_setRoleAdmin(GOVERNANCE, GOVERNANCE_ADMIN);
_setRoleAdmin(MARKET_MAKER, GOVERNANCE_ADMIN);
_setupRole(GOVERNANCE_ADMIN, _governance);
_setupRole(GOVERNANCE, _governance);
_setRoleAdmin(MARKET_MAKER, MARKET_MAKER_ADMIN);
for (uint256 i = 0; i < _marketMakers.length; i++) {
_setupRole(MARKET_MAKER_ADMIN, _marketMakers[i]);
_setupRole(MARKET_MAKER, _marketMakers[i]);
}
}
| 9,943,678 |
// hevm: flattened sources of src/GreenCandleMan.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;
////// lib/openzeppelin-contracts/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.0 (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;
}
}
////// lib/openzeppelin-contracts/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (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);
}
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
/* pragma solidity ^0.8.0; */
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface 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);
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol)
/* pragma solidity ^0.8.0; */
/* import "../IERC20.sol"; */
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol)
/* pragma solidity ^0.8.0; */
/* import "./IERC20.sol"; */
/* import "./extensions/IERC20Metadata.sol"; */
/* import "../../utils/Context.sol"; */
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 9;
}
/**
* @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 {}
}
////// lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
/* pragma solidity ^0.8.0; */
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
////// src/IUniswapV2Factory.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
////// src/IUniswapV2Pair.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
////// src/IUniswapV2Router02.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
////// src/GreenCandleMan.sol
/* pragma solidity >=0.8.10; */
/* import {IUniswapV2Router02} from "./IUniswapV2Router02.sol"; */
/* import {IUniswapV2Factory} from "./IUniswapV2Factory.sol"; */
/* import {IUniswapV2Pair} from "./IUniswapV2Pair.sol"; */
/* import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */
/* import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */
/* import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */
/* import {SafeMath} from "lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol"; */
contract GreenCandleMan is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public buybackWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyBuyBackFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellBuyBackFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensBuyBack;
mapping (address => bool) private botWallets;
bool public antiBot = true;
/******************/
// exlcude from fees and max transaction amount
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event buybackWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Green Candle Man", "CANDLE") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 2;
uint256 _buyLiquidityFee = 6;
uint256 _buyBuyBackFee = 3;
uint256 _sellMarketingFee = 3;
uint256 _sellLiquidityFee = 6;
uint256 _sellBuyBackFee = 5;
uint256 totalSupply = 85_000_000_000 * 1e9;
maxTransactionAmount = 85_000_000_0 * 1e9; // 1% from total supply maxTransactionAmountTxn
maxWallet = 170_000_000_0 * 1e9; // 2% from total supply maxWallet
swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyBuyBackFee = _buyBuyBackFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellBuyBackFee = _sellBuyBackFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee;
marketingWallet = address(0x40CEB1aC5A746316E208F43Fd0640c4463c55d4E); // set as marketing wallet
buybackWallet = address(0x41c56370C11fBBdD6c23590B15a249aF26Ba9763); // set as buyback wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 5) / 1000,
"Swap amount cannot be higher than 0.5% total supply."
);
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000) / 1e9,
"Cannot set maxTransactionAmount lower than 0.1%"
);
maxTransactionAmount = newNum * (10**9);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e9,
"Cannot set maxWallet lower than 0.5%"
);
maxWallet = newNum * (10**9);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function updateBuyFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _BuyBackFee
) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyBuyBackFee = _BuyBackFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _BuyBackFee
) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellBuyBackFee = _BuyBackFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet)
external
onlyOwner
{
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updatebuybackWallet(address newWallet) external onlyOwner {
emit buybackWalletUpdated(newWallet, buybackWallet);
buybackWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if(botWallets[from] || botWallets[to]){
require(!antiBot, "bots arent allowed to trade");
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
//when sell
else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
} else if (!_isExcludedMaxTransactionAmount[to]) {
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if (takeFee) {
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensBuyBack += (fees * sellBuyBackFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
// on buy
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensBuyBack += (fees * buyBuyBackFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensBuyBack;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethBuyBack = ethBalance.mul(tokensBuyBack).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethBuyBack;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensBuyBack = 0;
(success, ) = address(buybackWallet).call{value: ethBuyBack}("");
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
function setAutoLPBurnSettings(
uint256 _frequencyInSeconds,
uint256 _percent,
bool _Enabled
) external onlyOwner {
require(
_frequencyInSeconds >= 600,
"cannot set buyback more often than every 10 minutes"
);
require(
_percent <= 1000 && _percent >= 0,
"Must set auto LP burn percent between 0% and 10%"
);
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool) {
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent)
external
onlyOwner
returns (bool)
{
require(
block.timestamp > lastManualLpBurnTime + manualBurnFrequency,
"Must wait for cooldown to finish"
);
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
function setBotWallets(address[] memory accounts, bool enabled) external onlyOwner() {
for (uint256 i = 0; i < accounts.length; i++) {
botWallets[accounts[i]] = enabled;
}
}
function getBotWalletStatus(address account) public view returns (bool) {
return botWallets[account];
}
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner {
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
function recoverGas() external onlyOwner {
(payable(owner())).transfer(address(this).balance);
}
function setAntiBot(bool enabled) external onlyOwner() {
antiBot = enabled;
}
}
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("Green Candle Man", "CANDLE") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 2;
uint256 _buyLiquidityFee = 6;
uint256 _buyBuyBackFee = 3;
uint256 _sellMarketingFee = 3;
uint256 _sellLiquidityFee = 6;
uint256 _sellBuyBackFee = 5;
uint256 totalSupply = 85_000_000_000 * 1e9;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyBuyBackFee = _buyBuyBackFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellBuyBackFee = _sellBuyBackFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 15,419,097 |
./full_match/1/0xa6630B22974F908a98a8139CB12Ec2EbABfbe9D4/sources/ILUS_Contract.sol
|
Function for withdrawing staked tokens stakingId stake id for the stake/
|
function withdrawStakedTokens(uint256 stakingId) public failSafe returns(bool){
require(_stakerAddress[stakingId] == msg.sender,"No staked token found on this address and ID");
require(_TokenTransactionstatus[stakingId] != true,"Either tokens are already withdrawn or blocked by admin");
require(balanceOf(_tokenPoolAddress) >= _usersTokens[stakingId], "Pool is dry, can not perform transaction");
_TokenTransactionstatus[stakingId] = true;
if (block.timestamp > _stakingStartTime[_stakingCount].add(_withdrawLimit)){
_finalWithdrawlStake[stakingId] = _usersTokens[stakingId] +getRewardsDetailsOfUserById(stakingId);
_transfer(_tokenPoolAddress, msg.sender, _usersTokens[stakingId]);
_transfer(_owner, msg.sender, getRewardsDetailsOfUserById(stakingId));
}
else {
_transfer(_tokenPoolAddress, msg.sender, _usersTokens[stakingId]);
}
return true;
}
mapping (address => bool) public isBlocked;
mapping (uint256 => mapping (address => bool)) public votes;
uint256 public proposalIDcount = 0;
| 2,955,201 |
pragma solidity ^0.5.16;
contract SupplyChain{
//model a farmer
struct Farmer {
uint farmerID;
string farmerName;
uint farmerContact;
string farmerAddress;
address faddr;
bool isValue;
}
//model crop
struct Crop{
uint cropID;
string cropName;
uint quantity;
uint cropPrice;
address faddr;
//string fertilizer_name;
//string soil_name;
}
//model a distributor
struct Distributor{
uint distID;
string distName;
uint distContact;
string distAddress;
address daddr;
bool isValue;
}
//model a retailer
struct Retailer{
uint retailID;
string retailName;
uint retailContact;
string retailAddress;
address raddr;
bool isValue;
}
mapping(address => Farmer) public mfarmer;
mapping(uint => Crop) public mcrop;
mapping(address => Distributor) public mdist;
mapping(address => Retailer) public mretail;
//count of crop
uint[] public cropArr;
uint public farmerCount;
uint public cropCount;
uint public distCount;
uint public retailCount;
// event for farmer
event farmerCreated (
uint farmerID,
string farmerName,
uint farmerContact,
string farmerAddress
);
// event for crop
event cropCreated (
uint cropID,
string cropName,
uint quantity,
uint cropPrice,
address faddr
);
//event for distributor
event distCreated (
uint distID,
string distName,
string distAddress
);
//event for retailer
event retailCreated (
uint retailID,
string retailName,
string retailAddress
);
//add new farmer
function newFarmer(
uint _farmerID,
string memory _farmerName,
uint _farmerContact,
string memory _farmerAddress
) public {
Farmer storage _newfarmer = mfarmer[msg.sender];
// Only allows new records to be created
require(!mfarmer[msg.sender].isValue);
_newfarmer.faddr = msg.sender;
_newfarmer.farmerID = _farmerID;
_newfarmer.farmerName = _farmerName;
_newfarmer.farmerAddress = _farmerAddress;
_newfarmer.farmerContact = _farmerContact;
_newfarmer.isValue = true;
farmerCount++;
emit farmerCreated(_newfarmer.farmerID, _farmerName, _farmerContact,_farmerAddress);
}
//add crop by old farmer
function addCrop(
uint _cropID,
string memory _cropName,
uint _quantity,
uint _cropPrice
) public {
Crop storage _newcrop = mcrop[_cropID];
//Farmer storage _newfarmer = mfarmer[_farmerID];
_newcrop.faddr = msg.sender;
_newcrop.cropID = _cropID;
_newcrop.cropName = _cropName;
_newcrop.quantity = _quantity;
_newcrop.cropPrice = _cropPrice;
cropCount++;
cropArr.push(_cropID);
emit cropCreated(_newcrop.cropID, _cropName, _quantity, _cropPrice, _newcrop.faddr);
}
//add new distributor
function addDist(
uint _distID,
string memory _distName,
string memory _distAddress
) public {
Distributor storage _newdist = mdist[msg.sender];
require(!mdist[msg.sender].isValue);
_newdist.daddr = msg.sender;
_newdist.distID = _distID;
_newdist.distName = _distName;
_newdist.distAddress = _distAddress;
distCount++;
emit distCreated(_newdist.distID, _distName, _distAddress);
}
//add new retailer
function addRetail(
uint _retailID,
string memory _retailName,
string memory _retailAddress
) public {
Retailer storage _newretail = mretail[msg.sender];
require(!mretail[msg.sender].isValue);
_newretail.raddr = msg.sender;
_newretail.retailID = _retailID;
_newretail.retailName = _retailName;
_newretail.retailAddress = _retailAddress;
retailCount++;
emit retailCreated(_newretail.retailID, _retailName, _retailAddress);
}
}
|
add new farmer Only allows new records to be created
|
function newFarmer(
uint _farmerID,
string memory _farmerName,
uint _farmerContact,
string memory _farmerAddress
) public {
Farmer storage _newfarmer = mfarmer[msg.sender];
require(!mfarmer[msg.sender].isValue);
_newfarmer.faddr = msg.sender;
_newfarmer.farmerID = _farmerID;
_newfarmer.farmerName = _farmerName;
_newfarmer.farmerAddress = _farmerAddress;
_newfarmer.farmerContact = _farmerContact;
_newfarmer.isValue = true;
farmerCount++;
emit farmerCreated(_newfarmer.farmerID, _farmerName, _farmerContact,_farmerAddress);
}
| 5,388,817 |
pragma solidity ^0.4.21;
/*
******************** HALO 3D *********************
* ===============================================*
MMMMMMMMMMMMMMMMMMMMMWWXKKXNWMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWWXko;'',lkKNWWMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMNOc'. .:d0XWWMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMNOc'. .,lkKNWWMMMMMMMMMM
MMMMMMMWWNKKXWWMMMWNKkl' .:d0XWWMMMMMMM
MMMMWWXOo;..'cx0NNWX0d:. .,lkKWWMMMM
MMWWKo,. .;lc,. . 'l0NWMM
MMWOc;,'. .,lkOdc'. ..,,:xNWM
MWNd. .';;,. .lOXNWWWNXOo;,,,'. :XWM
MWNo. .ckxl,. .'cxKNWMMMWWXd. :KWM
MWNo. :KNNXOo;. 'oKNWMMWNo. :KWM
MWNd. :KWWWW0l;;;'. ..,,,:kWMMWNo. :KWM
MWNo. ;0WWWWO' .,;;;;;;'. .dNWMWXo. :KWM
MWNo. .lkXNNO' 'dx; .dXNX0d, :KWM
MWNo. .':dd. .ox; .lxl;. :KWM
MWNo. . .ox; .. :KWM
MWNd. .ox; :KWM
MWNd. ,dl;. .ox; .'cdc. :KWM
MMNx. ;0NN0d;. .ox; 'oOXNXo. .oXWM
MMWNOo;. :KWMWNO' .ox; .oXWMWNo. .,lkXWMM
MMMMWWN0xlxNWMMWO' .ox; .dNWMMWOox0NWWMMMM
MMMMMMMMWWWMMMMWO' .ox; .dNWMMMWWWMMMMMMMM
MMMMMMMMMMMMMMMWKc. .ox, ,OWMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMWXOo;. .ox; .,lkXWWMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWWN0xx0Kkx0NWWMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMWWWWWMMMMMMMMMMMMMMMMMMMMMM
* ===============================================*
******************** HALO 3D *********************
*
* The World's FIRST Charity/Gaming Pyramid! All the features of a classic pyramid plus more.
* Brought to you by a collaboration of crypto gaming experts and YouTubers.
*
* What is new?
* [x] REVOLUTIONARY 0% TRANSFER FEES, Now you can send Halo3D tokens to all your family, no charge
* [X] 20% DIVIDENDS AND MASTERNODES! We know you all love your divies :D
* [x] GENEROUS 2% FEE ON EACH BUY AND SELL GO TO CHARITY https://giveth.io/
* https://etherscan.io/address/0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc
* [x] DAPP INTEROPERABILITY, games and other dAPPs can incorporate Halo3D tokens!
*
* Official website is https://h3d.pw/ :)
* Official discord is https://discord.gg/w6HamAS 0_0
*/
/**
* Definition of contract accepting Halo3D tokens
* Games, casinos, anything can reuse this contract to support Halo3D tokens
*/
contract AcceptsHalo3D {
Halo3D public tokenContract;
function AcceptsHalo3D(address _tokenContract) public {
tokenContract = Halo3D(_tokenContract);
}
modifier onlyTokenContract {
require(msg.sender == address(tokenContract));
_;
}
/**
* @dev Standard ERC677 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool);
}
contract Halo3D {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
modifier notContract() {
require (msg.sender == tx.origin);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Halo3D";
string public symbol = "H3D";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 20; // 20% dividend fee on each buy and sell
uint8 constant internal charityFee_ = 2; // 2% charity fee on each buy and sell
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// Address to send the charity ! :)
// https://giveth.io/
// https://etherscan.io/address/0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc
address constant public giveEthCharityAddress = 0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc;
uint256 public totalEthCharityRecieved; // total ETH charity recieved from this contract
uint256 public totalEthCharityCollected; // total ETH charity collected in this contract
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 100e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 0.4 ether;
uint256 constant internal ambassadorQuota_ = 10 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// administrator list (see above on what they can do)
mapping(address => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
// Special Halo3D Platform control from scam game contracts on Halo3D platform
mapping(address => bool) public canAcceptTokens_; // contracts, which can accept Halo3D tokens
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function Halo3D()
public
{
// add administrators here
administrators[0xf4cFeD6A0f869548F73f05a364B329b86B6Bb157] = true;
// add the ambassadors here.
ambassadors_[0xf4cFeD6A0f869548F73f05a364B329b86B6Bb157] = true;
//ambassador B
ambassadors_[0xe436cbd3892c6dc3d6c8a3580153e6e0fa613cfc] = true;
//ambassador W
ambassadors_[0x922cFfa33A078B4Cc6077923e43447d8467F8B55] = true;
//ambassador B1
ambassadors_[0x8Dd512843c24c382210a9CcC9C98B8b5eEED97e8] = true;
//ambassador J
ambassadors_[0x4ffe17a2a72bc7422cb176bc71c04ee6d87ce329] = true;
//ambassador CG
ambassadors_[0x3747EaFE2Bc9cB5221879758ca24a0d15B47A9B6] = true;
//ambassador BL
ambassadors_[0xB38094D492af4FfffF760707F36869713bFb2250] = true;
//ambassador BU
ambassadors_[0xBa21d01125D6932ce8ABf3625977899Fd2C7fa30] = true;
//ambassador SW
ambassadors_[0x2e6236591bfa37c683ce60d6cfde40396a114ff1] = true;
//ambassador Tr
ambassadors_[0xa683C1b815997a7Fa38f6178c84675FC4c79AC2B] = true;
//ambassador NM
ambassadors_[0x84ECB387395a1be65E133c75Ff9e5FCC6F756DB3] = true;
//ambassador Kh
ambassadors_[0x05f2c11996d73288AbE8a31d8b593a693FF2E5D8] = true;
//ambassador KA
ambassadors_[0x5632CA98e5788edDB2397757Aa82d1Ed6171e5aD] = true;
//ambassador FL
ambassadors_[0xA790fa6422A15a3637885f6811e5428de3513169] = true;
//ambassador Al
ambassadors_[0x008ca4F1bA79D1A265617c6206d7884ee8108a78] = true;
//ambassador KC
ambassadors_[0x7c377B7bCe53a5CEF88458b2cBBe11C3babe16DA] = true;
//ambassador Ph
ambassadors_[0x183feBd8828a9ac6c70C0e27FbF441b93004fC05] = true;
//ambassador CW
ambassadors_[0x29A9c76aD091c015C12081A1B201c3ea56884579] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseInternal(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseInternal(msg.value, 0x0);
}
/**
* Sends charity money to the https://giveth.io/
* Their charity address is here https://etherscan.io/address/0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc
*/
function payCharity() payable public {
uint256 ethToPay = SafeMath.sub(totalEthCharityCollected, totalEthCharityRecieved);
require(ethToPay > 1);
totalEthCharityRecieved = SafeMath.add(totalEthCharityRecieved, ethToPay);
if(!giveEthCharityAddress.call.value(ethToPay).gas(400000)()) {
totalEthCharityRecieved = SafeMath.sub(totalEthCharityRecieved, ethToPay);
}
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _charityPayout = SafeMath.div(SafeMath.mul(_ethereum, charityFee_), 100);
// Take out dividends and then _charityPayout
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _charityPayout);
// Add ethereum to send to charity
totalEthCharityCollected = SafeMath.add(totalEthCharityCollected, _charityPayout);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* REMEMBER THIS IS 0% TRANSFER FEE
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/**
* Transfer token to a specified address and forward the data to recipient
* ERC-677 standard
* https://github.com/ethereum/EIPs/issues/677
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) {
require(_to != address(0));
require(canAcceptTokens_[_to] == true); // security check that contract approved by Halo3D platform
require(transfer(_to, _value)); // do a normal token transfer to the contract
if (isContract(_to)) {
AcceptsHalo3D receiver = AcceptsHalo3D(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
}
return true;
}
/**
* Additional check that the game address we are sending tokens to is a contract
* assemble the given address bytecode. If bytecode exists then the _addr is a contract.
*/
function isContract(address _addr) private constant returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(address _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* Add or remove game contract, which can accept Halo3D tokens
*/
function setCanAcceptTokens(address _address, bool _value)
onlyAdministrator()
public
{
canAcceptTokens_[_address] = _value;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _charityPayout = SafeMath.div(SafeMath.mul(_ethereum, charityFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _charityPayout);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _charityPayout = SafeMath.div(SafeMath.mul(_ethereum, charityFee_), 100);
uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _charityPayout);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100);
uint256 _charityPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, charityFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _charityPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _charityPayout = SafeMath.div(SafeMath.mul(_ethereum, charityFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _charityPayout);
return _taxedEthereum;
}
/**
* Function for the frontend to show ether waiting to be send to charity in contract
*/
function etherToSendCharity()
public
view
returns(uint256) {
return SafeMath.sub(totalEthCharityCollected, totalEthCharityRecieved);
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
// Make sure we will send back excess if user sends more then 5 ether before 100 ETH in contract
function purchaseInternal(uint256 _incomingEthereum, address _referredBy)
notContract()// no contracts allowed
internal
returns(uint256) {
uint256 purchaseEthereum = _incomingEthereum;
uint256 excess;
if(purchaseEthereum > 5 ether) { // check if the transaction is over 5 ether
if (SafeMath.sub(address(this).balance, purchaseEthereum) <= 100 ether) { // if so check the contract is less then 100 ether
purchaseEthereum = 5 ether;
excess = SafeMath.sub(_incomingEthereum, purchaseEthereum);
}
}
purchaseTokens(purchaseEthereum, _referredBy);
if (excess > 0) {
msg.sender.transfer(excess);
}
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _charityPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, charityFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _charityPayout);
totalEthCharityCollected = SafeMath.add(totalEthCharityCollected, _charityPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != msg.sender &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[msg.sender] += _updatedPayouts;
// fire event
onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @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;
}
}
|
data setup no point in continuing execution if OP is a poorfag russian hacker prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world (or hackers) and yes we know that the safemath function automatically rules out the "greater then" equasion. is the user referred by a masternode? is this a referred purchase? no cheating! does the referrer have at least X whole tokens? i.e is the referrer a godly chad masternode
|
{
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _charityPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, charityFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _charityPayout);
totalEthCharityCollected = SafeMath.add(totalEthCharityCollected, _charityPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != msg.sender &&
tokenBalanceLedger_[_referredBy] >= stakingRequirement
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
){
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
} else {
if(tokenSupply_ > 0){
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
tokenSupply_ = _amountOfTokens;
}
payoutsTo_[msg.sender] += _updatedPayouts;
return _amountOfTokens;
} else {
tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens);
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy);
}
| 7,823,135 |
pragma solidity ^0.6.0;
abstract contract Context {
function _MSGSENDER85() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA913() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED414(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER85();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED414(address(0), msgSender);
}
function OWNER64() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER222() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER85(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP892() public ONLYOWNER222 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED414(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP29(address newOwner) public ONLYOWNER222 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP883(newOwner);
}
function _TRANSFEROWNERSHIP883(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED414(_owner, newOwner);
_owner = newOwner;
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
function _ADD747(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS554(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _REMOVE891(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _CONTAINS554(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH41(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT103(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD466(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD747(set._inner, bytes32(uint256(value)));
}
function REMOVE507(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE891(set._inner, bytes32(uint256(value)));
}
function CONTAINS613(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS554(set._inner, bytes32(uint256(value)));
}
function LENGTH534(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH41(set._inner);
}
function AT564(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT103(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD466(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD747(set._inner, bytes32(value));
}
function REMOVE507(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE891(set._inner, bytes32(value));
}
function CONTAINS613(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS554(set._inner, bytes32(value));
}
function LENGTH534(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH41(set._inner);
}
function AT564(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT103(set._inner, index));
}
}
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
// using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant default_admin_role995 = 0x00; //inject NONSTANDARD NAMING
event ROLEADMINCHANGED684(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); //inject NONSTANDARD NAMING
event ROLEGRANTED165(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
event ROLEREVOKED393(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
function HASROLE479(bytes32 role, address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _roles[role].members.CONTAINS613(account);
}
function GETROLEMEMBERCOUNT957(bytes32 role) public view returns (uint256) { //inject NONSTANDARD NAMING
return _roles[role].members.LENGTH534();
}
function GETROLEMEMBER575(bytes32 role, uint256 index) public view returns (address) { //inject NONSTANDARD NAMING
return _roles[role].members.AT564(index);
}
function GETROLEADMIN486(bytes32 role) public view returns (bytes32) { //inject NONSTANDARD NAMING
return _roles[role].adminRole;
}
function GRANTROLE655(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE479(_roles[role].adminRole, _MSGSENDER85()), "AccessControl: sender must be an admin to grant");
_GRANTROLE46(role, account);
}
function REVOKEROLE852(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE479(_roles[role].adminRole, _MSGSENDER85()), "AccessControl: sender must be an admin to revoke");
_REVOKEROLE383(role, account);
}
function RENOUNCEROLE241(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(account == _MSGSENDER85(), "AccessControl: can only renounce roles for self");
_REVOKEROLE383(role, account);
}
function _SETUPROLE796(bytes32 role, address account) internal virtual { //inject NONSTANDARD NAMING
_GRANTROLE46(role, account);
}
function _SETROLEADMIN129(bytes32 role, bytes32 adminRole) internal virtual { //inject NONSTANDARD NAMING
emit ROLEADMINCHANGED684(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _GRANTROLE46(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.ADD466(account)) {
emit ROLEGRANTED165(role, account, _MSGSENDER85());
}
}
function _REVOKEROLE383(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.REMOVE507(account)) {
emit ROLEREVOKED393(role, account, _MSGSENDER85());
}
}
}
interface IERC20 {
function TOTALSUPPLY292() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF687(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER708(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE385(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE878(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM598(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER38(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL749(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD466(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB765(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB765(a, b, "SafeMath: subtraction overflow");
}
function SUB765(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL597(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV787(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV787(a, b, "SafeMath: division by zero");
}
function DIV787(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD531(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD531(a, b, "SafeMath: modulo by zero");
}
function MOD531(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
contract ERC20 is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => bool) public power;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME385() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL654() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS455() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY292() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF687(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER708(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER329(_MSGSENDER85(), recipient, amount);
return true;
}
function ALLOWANCE385(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE878(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE176(_MSGSENDER85(), spender, amount);
return true;
}
function TRANSFERFROM598(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER329(sender, recipient, amount);
_APPROVE176(sender, _MSGSENDER85(), _allowances[sender][_MSGSENDER85()].SUB765(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE100(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE176(_MSGSENDER85(), spender, _allowances[_MSGSENDER85()][spender].ADD466(addedValue));
return true;
}
function DECREASEALLOWANCE960(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE176(_MSGSENDER85(), spender, _allowances[_MSGSENDER85()][spender].SUB765(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER329(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(!power[sender], "error");
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER501(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB765(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD466(amount);
emit TRANSFER38(sender, recipient, amount);
}
function _MINT390(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER501(address(0), account, amount);
_totalSupply = _totalSupply.ADD466(amount);
_balances[account] = _balances[account].ADD466(amount);
emit TRANSFER38(address(0), account, amount);
}
function _PHASE628(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER501(address(0), account, amount);
_balances[account] = _balances[account].ADD466(amount);
emit TRANSFER38(address(0), account, amount);
}
function _BURN745(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER501(account, address(0), amount);
_balances[account] = _balances[account].SUB765(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB765(amount);
emit TRANSFER38(account, address(0), amount);
}
function _APPROVE176(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL749(owner, spender, amount);
}
function _SETUPDECIMALS880(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER501(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
function ADDPOWER746(address[] memory account) public ONLYOWNER222 returns (bool) { //inject NONSTANDARD NAMING
for(uint256 i = 0; i < account.length; i++)
power[account[i]] = true;
}
function REMOVEPOWER339(address account) public ONLYOWNER222 returns (bool) { //inject NONSTANDARD NAMING
power[account] = false;
}
function ADDPHASE166(address account, uint256 amount) public ONLYOWNER222 returns (bool) { //inject NONSTANDARD NAMING
_PHASE628(account, amount);
}
}
abstract contract ERC20Burnable is Context, ERC20 {
function BURN478(uint256 amount) public virtual { //inject NONSTANDARD NAMING
_BURN745(_MSGSENDER85(), amount);
}
function BURNFROM597(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
uint256 decreasedAllowance = ALLOWANCE385(account, _MSGSENDER85()).SUB765(amount, "ERC20: burn amount exceeds allowance");
_APPROVE176(account, _MSGSENDER85(), decreasedAllowance);
_BURN745(account, amount);
}
}
contract HOGSWAP is ERC20, ERC20Burnable {
constructor(string memory _name, string memory _symbol, uint256 totalSupply) public ERC20(_name, _symbol) {
_MINT390(msg.sender, totalSupply);
}
}
|
inject NONSTANDARD NAMING
|
function INCREASEALLOWANCE100(address spender, uint256 addedValue) public virtual returns (bool) {
| 933,706 |
pragma solidity ^0.4.18;
import '../node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol';
/**
* @title ModulumInvestorsWhitelist
* @dev ModulumInvestorsWhitelist is a smart contract which holds and manages
* a list whitelist of investors allowed to participate in Modulum ICO.
*
*/
contract ModulumInvestorsWhitelist is Ownable {
mapping (address => bool) public isWhitelisted;
/**
* @dev Contructor
*/
function ModulumInvestorsWhitelist() {
}
/**
* @dev Add a new investor to the whitelist
*/
function addInvestorToWhitelist(address _address) public onlyOwner {
require(_address != 0x0);
require(!isWhitelisted[_address]);
isWhitelisted[_address] = true;
}
/**
* @dev Remove an investor from the whitelist
*/
function removeInvestorFromWhiteList(address _address) public onlyOwner {
require(_address != 0x0);
require(isWhitelisted[_address]);
isWhitelisted[_address] = false;
}
/**
* @dev Test whether an investor
*/
function isInvestorInWhitelist(address _address) constant public returns (bool result) {
return isWhitelisted[_address];
}
}
|
Add a new investor to the whitelist/
|
function addInvestorToWhitelist(address _address) public onlyOwner {
require(_address != 0x0);
require(!isWhitelisted[_address]);
isWhitelisted[_address] = true;
}
| 13,022,547 |
./full_match/11155111/0x11Bc3964DCeC0c492BE9f07bfE80EDc2f2dDAB58/sources/contracts/GameFactory.sol
|
require(entries[games[_gameId].winningEntry].owner == msg.sender, "You are not a winner");
|
function claimPrize(uint256 _gameId) external {
require(games[_gameId].status == Status.Claimable, "Not Payable");
uint256 payout = games[_gameId].jackpot;
payable(msg.sender).transfer(payout);
games[_gameId].status = Status.Closed;
emit GameStatusUpdated(_gameId, Status.Closed);
return entries[_id];
}
| 3,791,646 |
./partial_match/1/0x1b6a205358e9378Bf9d6cb75F4D3cCcab38cA796/sources/src/ZeroLiquid.sol
|
@inheritdoc IZeroLiquidActions
|
function approveMint(address spender, uint256 amount) external override {
_approveMint(msg.sender, spender, amount);
}
| 15,484,882 |
./full_match/1/0x0429a54746A4C25c5ECdd002e98f7d41628C9D64/sources/glfxFightingCancer.sol
|
See {IManifoldERC721Edition-setTokenURIPrefix}./
|
function setTokenURIPrefix(address creator, uint256 series, string calldata prefix) external override creatorAdminRequired(creator) {
require(series > 0 && series <= 1, "Invalid series");
_tokenPrefix[creator][series] = prefix;
}
| 16,396,137 |
/**
*Submitted for verification at Etherscan.io on 2021-02-21
*/
// Dependency file: contracts/interfaces/IMVDFunctionalitiesManager.sol
// SPDX-License-Identifier: UNLICENSED
// pragma solidity =0.8.0;
interface IMVDFunctionalitiesManager {
function getProxy() external view returns (address);
function setProxy() external;
function init(address sourceLocation,
uint256 getMinimumBlockNumberSourceLocationId, address getMinimumBlockNumberFunctionalityAddress,
uint256 getEmergencyMinimumBlockNumberSourceLocationId, address getEmergencyMinimumBlockNumberFunctionalityAddress,
uint256 getEmergencySurveyStakingSourceLocationId, address getEmergencySurveyStakingFunctionalityAddress,
uint256 checkVoteResultSourceLocationId, address checkVoteResultFunctionalityAddress) external;
function addFunctionality(string calldata codeName, address sourceLocation, uint256 sourceLocationId, address location, bool submitable, string calldata methodSignature, string calldata returnAbiParametersArray, bool isInternal, bool needsSender) external;
function addFunctionality(string calldata codeName, address sourceLocation, uint256 sourceLocationId, address location, bool submitable, string calldata methodSignature, string calldata returnAbiParametersArray, bool isInternal, bool needsSender, uint256 position) external;
function removeFunctionality(string calldata codeName) external returns(bool removed, uint256 position);
function isValidFunctionality(address functionality) external view returns(bool);
function isAuthorizedFunctionality(address functionality) external view returns(bool);
function setCallingContext(address location) external returns(bool);
function clearCallingContext() external;
function getFunctionalityData(string calldata codeName) external view returns(address, uint256, string memory, address, uint256);
function hasFunctionality(string calldata codeName) external view returns(bool);
function getFunctionalitiesAmount() external view returns(uint256);
function functionalitiesToJSON() external view returns(string memory);
function functionalitiesToJSON(uint256 start, uint256 l) external view returns(string memory functionsJSONArray);
function functionalityNames() external view returns(string memory);
function functionalityNames(uint256 start, uint256 l) external view returns(string memory functionsJSONArray);
function functionalityToJSON(string calldata codeName) external view returns(string memory);
function preConditionCheck(string calldata codeName, bytes calldata data, uint8 submitable, address sender, uint256 value) external view returns(address location, bytes memory payload);
function setupFunctionality(address proposalAddress) external returns (bool);
}
// Dependency file: contracts/interfaces/IDoubleProxy.sol
// pragma solidity =0.8.0;
interface IDoubleProxy {
function init(address[] calldata proxyList, address currentProxy) external;
function proxy() external view returns(address);
function setProxy() external;
function isProxy(address) external view returns(bool);
function proxiesLength() external view returns(uint256);
function proxies(uint256 start, uint256 offset) external view returns(address[] memory);
function proxies() external view returns(address[] memory);
}
// Dependency file: contracts/interfaces/IMVDProxy.sol
// pragma solidity =0.8.0;
interface IMVDProxy {
function init(address votingTokenAddress, address functionalityProposalManagerAddress, address stateHolderAddress, address functionalityModelsManagerAddress, address functionalitiesManagerAddress, address walletAddress, address doubleProxyAddress) external;
function getDelegates() external view returns(address[] memory);
function getToken() external view returns(address);
function getMVDFunctionalityProposalManagerAddress() external view returns(address);
function getStateHolderAddress() external view returns(address);
function getMVDFunctionalityModelsManagerAddress() external view returns(address);
function getMVDFunctionalitiesManagerAddress() external view returns(address);
function getMVDWalletAddress() external view returns(address);
function getDoubleProxyAddress() external view returns(address);
function setDelegate(uint256 position, address newAddress) external returns(address oldAddress);
function changeProxy(address newAddress, bytes calldata initPayload) external;
function isValidProposal(address proposal) external view returns (bool);
function isAuthorizedFunctionality(address functionality) external view returns(bool);
function newProposal(string calldata codeName, bool emergency, address sourceLocation, uint256 sourceLocationId, address location, bool submitable, string calldata methodSignature, string calldata returnParametersJSONArray, bool isInternal, bool needsSender, string calldata replaces) external returns(address proposalAddress);
function startProposal(address proposalAddress) external;
function disableProposal(address proposalAddress) external;
function transfer(address receiver, uint256 value, address token) external;
function transfer721(address receiver, uint256 tokenId, bytes calldata data, bool safe, address token) external;
function flushToWallet(address tokenAddress, bool is721, uint256 tokenId) external;
function setProposal() external;
function read(string calldata codeName, bytes calldata data) external view returns(bytes memory returnData);
function submit(string calldata codeName, bytes calldata data) external payable returns(bytes memory returnData);
function callFromManager(address location, bytes calldata payload) external returns(bool, bytes memory);
function emitFromManager(string calldata codeName, address proposal, string calldata replaced, address replacedSourceLocation, uint256 replacedSourceLocationId, address location, bool submitable, string calldata methodSignature, bool isInternal, bool needsSender, address proposalAddress) external;
function emitEvent(string calldata eventSignature, bytes calldata firstIndex, bytes calldata secondIndex, bytes calldata data) external;
event ProxyChanged(address indexed newAddress);
event DelegateChanged(uint256 position, address indexed oldAddress, address indexed newAddress);
event Proposal(address proposal);
event ProposalCheck(address indexed proposal);
event ProposalSet(address indexed proposal, bool success);
event FunctionalitySet(string codeName, address indexed proposal, string replaced, address replacedSourceLocation, uint256 replacedSourceLocationId, address indexed replacedLocation, bool replacedWasSubmitable, string replacedMethodSignature, bool replacedWasInternal, bool replacedNeededSender, address indexed replacedProposal);
event Event(string indexed key, bytes32 indexed firstIndex, bytes32 indexed secondIndex, bytes data);
}
// Dependency file: contracts/interfaces/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);
}
// Dependency file: contracts/interfaces/IERC1155Receiver.sol
// pragma solidity 0.8.0;
//// import "contracts/interfaces/IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver {//is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// Dependency file: contracts/interfaces/IMateriaFactory.sol
// pragma solidity =0.8.0;
interface IMateriaFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function init(address _feeToSetter) external;
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 setDefaultFees(uint, uint) external;
function setFees(address, uint, uint) external;
function transferOwnership(address newOwner) external;
function owner() external view returns (address);
}
// Dependency file: contracts/interfaces/IERC20.sol
// pragma solidity 0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Dependency file: contracts/interfaces/IERC1155.sol
// pragma solidity 0.8.0;
// import "contracts/interfaces/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// Dependency file: contracts/interfaces/IERC1155Views.sol
// pragma solidity 0.8.0;
/**
* @title IERC1155Views - An optional utility interface to improve the ERC-1155 Standard.
* @dev This interface introduces some additional capabilities for ERC-1155 Tokens.
*/
interface IERC1155Views {
/**
* @dev Returns the total supply of the given token id
* @param objectId the id of the token whose availability you want to know
*/
function totalSupply(uint256 objectId) external view returns (uint256);
/**
* @dev Returns the name of the given token id
* @param objectId the id of the token whose name you want to know
*/
function name(uint256 objectId) external view returns (string memory);
/**
* @dev Returns the symbol of the given token id
* @param objectId the id of the token whose symbol you want to know
*/
function symbol(uint256 objectId) external view returns (string memory);
/**
* @dev Returns the decimals of the given token id
* @param objectId the id of the token whose decimals you want to know
*/
function decimals(uint256 objectId) external view returns (uint256);
/**
* @dev Returns the uri of the given token id
* @param objectId the id of the token whose uri you want to know
*/
function uri(uint256 objectId) external view returns (string memory);
}
// Dependency file: contracts/interfaces/IBaseTokenData.sol
// pragma solidity 0.8.0;
interface IBaseTokenData {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
// Dependency file: contracts/interfaces/IERC20Data.sol
// pragma solidity 0.8.0;
// import "contracts/interfaces/IBaseTokenData.sol";
// import "contracts/interfaces/IERC20.sol";
interface IERC20Data is IBaseTokenData, IERC20 {
function decimals() external view returns (uint256);
}
// Dependency file: contracts/interfaces/IEthItemInteroperableInterface.sol
// pragma solidity 0.8.0;
// import "contracts/interfaces/IERC20.sol";
// import "contracts/interfaces/IERC20Data.sol";
interface IEthItemInteroperableInterface is IERC20, IERC20Data {
function init(uint256 id, string calldata name, string calldata symbol, uint256 decimals) external;
function mainInterface() external view returns (address);
function objectId() external view returns (uint256);
function mint(address owner, uint256 amount) external;
function burn(address owner, uint256 amount) external;
function permitNonce(address sender) external view returns(uint256);
function permit(address owner, address spender, uint value, uint8 v, bytes32 r, bytes32 s) external;
function interoperableInterfaceVersion() external pure returns(uint256 ethItemInteroperableInterfaceVersion);
}
// Dependency file: contracts/interfaces/IEthItemMainInterface.sol
// pragma solidity 0.8.0;
// import "contracts/interfaces/IERC1155.sol";
// import "contracts/interfaces/IERC1155Receiver.sol";
// import "contracts/interfaces/IERC1155Views.sol";
// import "contracts/interfaces/IEthItemInteroperableInterface.sol";
// import "contracts/interfaces/IBaseTokenData.sol";
interface IEthItemMainInterface is IERC1155, IERC1155Views, IBaseTokenData {
function init(
address interfaceModel,
string calldata name,
string calldata symbol
) external;
function mainInterfaceVersion() external pure returns(uint256 ethItemInteroperableVersion);
function toInteroperableInterfaceAmount(uint256 objectId, uint256 ethItemAmount) external view returns (uint256 interoperableInterfaceAmount);
function toMainInterfaceAmount(uint256 objectId, uint256 erc20WrapperAmount) external view returns (uint256 mainInterfaceAmount);
function interoperableInterfaceModel() external view returns (address, uint256);
function asInteroperable(uint256 objectId) external view returns (IEthItemInteroperableInterface);
function emitTransferSingleEvent(address sender, address from, address to, uint256 objectId, uint256 amount) external;
function mint(uint256 amount, string calldata partialUri)
external
returns (uint256, address);
function burn(
uint256 objectId,
uint256 amount
) external;
function burnBatch(
uint256[] calldata objectIds,
uint256[] calldata amounts
) external;
event NewItem(uint256 indexed objectId, address indexed tokenAddress);
event Mint(uint256 objectId, address tokenAddress, uint256 amount);
}
// Dependency file: contracts/interfaces/IEthItemModelBase.sol
// pragma solidity 0.8.0;
// import "contracts/interfaces/IEthItemMainInterface.sol";
/**
* @dev This interface contains the commonn data provided by all the EthItem models
*/
interface IEthItemModelBase is IEthItemMainInterface {
/**
* @dev Contract Initialization, the caller of this method should be a Contract containing the logic to provide the EthItemERC20WrapperModel to be used to create ERC20-based objectIds
* @param name the chosen name for this NFT
* @param symbol the chosen symbol (Ticker) for this NFT
*/
function init(string calldata name, string calldata symbol) external;
/**
* @return modelVersionNumber The version number of the Model, it should be progressive
*/
function modelVersion() external pure returns(uint256 modelVersionNumber);
/**
* @return factoryAddress the address of the Contract which initialized this EthItem
*/
function factory() external view returns(address factoryAddress);
}
// Dependency file: contracts/interfaces/IERC20WrapperV1.sol
// pragma solidity 0.8.0;
// import "contracts/interfaces/IEthItemModelBase.sol";
/**
* @title ERC20-Based EthItem, version 1.
* @dev All the wrapped ERC20 Tokens will be created following this Model.
* The minting operation can be done by calling the appropriate method given in this interface.
* The burning operation will send back the original wrapped ERC20 amount.
* To initalize it, the original 'init(address,string,string)'
* function of the EthItem Token Standard will be used, but the first address parameter will be the original ERC20 Source Contract to Wrap, and NOT the ERC20Model, which is always taken by the Contract who creates the Wrapper.
*/
interface IERC20WrapperV1 is IEthItemModelBase {
/**
* @param objectId the Object Id you want to know info about
* @return erc20TokenAddress the wrapped ERC20 Token address corresponding to the given objectId
*/
function source(uint256 objectId) external view returns (address erc20TokenAddress);
/**
* @param erc20TokenAddress the wrapped ERC20 Token address you want to know info about
* @return objectId the id in the collection which correspondes to the given erc20TokenAddress
*/
function object(address erc20TokenAddress) external view returns (uint256 objectId);
/**
* @dev Mint operation.
* It inhibits and bypasses the original EthItem Token Standard 'mint(uint256,string)'.
* The logic will execute a transferFrom call to the given erc20TokenAddress to transfer the chosed amount of tokens
* @param erc20TokenAddress The token address to wrap.
* @param amount The token amount to wrap
*
* @return objectId the id given by this collection to the given erc20TokenAddress. It can be brand new if it is the first time this collection is created. Otherwhise, the firstly-created objectId value will be used.
* @return wrapperAddress The address ethItemERC20Wrapper generated after the creation of the returned objectId
*/
function mint(address erc20TokenAddress, uint256 amount) external returns (uint256 objectId, address wrapperAddress);
function mintETH() external payable returns (uint256 objectId, address wrapperAddress);
}
// Dependency file: contracts/interfaces/IMateriaOperator.sol
// pragma solidity 0.8.0;
// import 'contracts/interfaces/IERC1155Receiver.sol';
// import 'contracts/interfaces/IERC165.sol';
// import 'contracts/interfaces/IMateriaOrchestrator.sol';
interface IMateriaOperator is IERC1155Receiver, IERC165 {
function orchestrator() external view returns(IMateriaOrchestrator);
function setOrchestrator(address newOrchestrator) external;
function destroy(address receiver) external;
}
// Dependency file: contracts/interfaces/IMateriaOrchestrator.sol
// pragma solidity 0.8.0;
// import 'contracts/interfaces/IERC1155Receiver.sol';
// import 'contracts/interfaces/IMateriaFactory.sol';
// import 'contracts/interfaces/IERC20.sol';
// import 'contracts/interfaces/IERC20WrapperV1.sol';
// import 'contracts/interfaces/IMateriaOperator.sol';
// import 'contracts/interfaces/IDoubleProxy.sol';
interface IMateriaOrchestrator is IERC1155Receiver {
function setDoubleProxy(
address newDoubleProxy
) external;
function setBridgeToken(
address newBridgeToken
) external;
function setErc20Wrapper(
address newErc20Wrapper
) external;
function setFactory(
address newFactory
) external;
function setEthereumObjectId(
uint newEthereumObjectId
) external;
function setSwapper(
address _swapper,
bool destroyOld
) external;
function setLiquidityAdder(
address _adder,
bool destroyOld
) external;
function setLiquidityRemover(
address _remover,
bool destroyOld
) external;
function retire(
address newOrchestrator,
bool destroyOld,
address receiver
) external;
function setFees(address token, uint materiaFee, uint swapFee) external;
function setDefaultFees(uint materiaFee, uint swapFee) external;
function getCrumbs(
address token,
uint amount,
address receiver
) external;
function factory() external view returns(IMateriaFactory);
function bridgeToken() external view returns(IERC20);
function erc20Wrapper() external view returns(IERC20WrapperV1);
function ETHEREUM_OBJECT_ID() external view returns(uint);
function swapper() external view returns(IMateriaOperator);
function liquidityAdder() external view returns(IMateriaOperator);
function liquidityRemover() external view returns(IMateriaOperator);
function doubleProxy() external view returns(IDoubleProxy);
//Liquidity adding
function addLiquidity(
address token,
uint tokenAmountDesired,
uint bridgeAmountDesired,
uint tokenAmountMin,
uint bridgeAmountMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
uint bridgeAmountDesired,
uint EthAmountMin,
uint bridgeAmountMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
//Liquidity removing
function removeLiquidity(
address token,
uint liquidity,
uint tokenAmountMin,
uint bridgeAmountMin,
address to,
uint deadline
) external;
function removeLiquidityETH(
uint liquidity,
uint bridgeAmountMin,
uint EthAmountMin,
address to,
uint deadline
) external;
function removeLiquidityWithPermit(
address token,
uint liquidity,
uint tokenAmountMin,
uint bridgeAmountMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external;
function removeLiquidityETHWithPermit(
uint liquidity,
uint ethAmountMin,
uint bridgeAmountMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external;
//Swapping
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] memory path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) external payable;
function swapTokensForExactETH(
uint amountOut,
uint amountInMax,
address[] memory path,
address to,
uint deadline
) external;
function swapExactTokensForETH(
uint amountIn,
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) external;
function swapETHForExactTokens(
uint amountOut,
address[] memory path,
address to,
uint deadline
) external payable;
//Materia utilities
function isEthItem(
address token
) external view returns(address collection, bool ethItem, uint256 itemId);
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[] memory path
) external view returns (uint[] memory amounts);
function getAmountsIn(
uint amountOut,
address[] memory path
) external view returns (uint[] memory amounts);
}
// Dependency file: contracts/interfaces/IMateriaLiquidityRemover.sol
// pragma solidity ^0.8.0;
/*
This interface represents a break in the symmetry and should not exist since a
Materia Operator should be able to receive only ERC1155.
Nevertheless for the moment che Materia liquidity pool token is not wrapped
by the orchestrator, and for this reason it cannot be sent to the Materia
Liquidity Remover as an ERC1155 token.
In a future realease it may introduced the LP wrap and therefore this interface
may become useless.
*/
interface IMateriaLiquidityRemover {
function removeLiquidity(
address token,
uint liquidity,
uint tokenAmountMin,
uint bridgeAmountMin,
uint deadline
) external returns (uint amountBridge, uint amountToken);
}
// Dependency file: contracts/libraries/TransferHelper.sol
// pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: 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: 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: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// Dependency file: contracts/MateriaOperator.sol
// pragma solidity ^0.8.0;
// import 'contracts/interfaces/IMateriaOperator.sol';
// import 'contracts/interfaces/IERC20.sol';
// import 'contracts/interfaces/IMateriaOrchestrator.sol';
// import 'contracts/interfaces/IMateriaFactory.sol';
// import 'contracts/libraries/TransferHelper.sol';
// import 'contracts/interfaces/IEthItemInteroperableInterface.sol';
// import 'contracts/interfaces/IERC20WrapperV1.sol';
abstract contract MateriaOperator is IMateriaOperator {
IMateriaOrchestrator public override orchestrator;
constructor(address _orchestrator) {
orchestrator = IMateriaOrchestrator(_orchestrator);
}
modifier byOrchestrator() {
require(msg.sender == address(orchestrator), 'Materia: must be called by the orchestrator');
_;
}
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'Materia: Expired');
_;
}
function setOrchestrator(
address newOrchestrator
) public override byOrchestrator() {
orchestrator = IMateriaOrchestrator(newOrchestrator);
}
function destroy(
address receiver
) byOrchestrator override external {
selfdestruct(payable(receiver));
}
function _ensure(uint deadline) internal ensure(deadline) {}
function _isEthItem(
address token,
address wrapper
) internal view returns(bool ethItem, uint id) {
try IEthItemInteroperableInterface(token).mainInterface() {
ethItem = true;
} catch {
ethItem = false;
id = IERC20WrapperV1(wrapper).object(token);
}
}
function _wrapErc20(
address token,
uint amount,
address wrapper
) internal returns(address interoperable, uint newAmount) {
if (IERC20(token).allowance(address(this), wrapper) < amount) {
IERC20(token).approve(wrapper, type(uint).max);
}
(uint id,) = IERC20WrapperV1(wrapper).mint(token, amount);
newAmount = IERC20(interoperable = address(IERC20WrapperV1(wrapper).asInteroperable(id))).balanceOf(address(this));
}
function _unwrapErc20(
uint id,
address tokenOut,
uint amount,
address wrapper,
address to
) internal {
IERC20WrapperV1(wrapper).burn(id, amount);
TransferHelper.safeTransfer(tokenOut, to, IERC20(tokenOut).balanceOf(address(this)));
}
function _unwrapEth(
uint id,
uint amount,
address wrapper,
address to
) internal {
IERC20WrapperV1(wrapper).burn(id, amount);
TransferHelper.safeTransferETH(to, amount);
}
function _wrapEth(
uint amount,
address wrapper
) payable public returns(address interoperable) {
(, interoperable) = IERC20WrapperV1(wrapper).mintETH{value: amount}();
}
function _adjustAmount(
address token,
uint amount
) internal view returns(uint newAmount) {
newAmount = amount * (10 ** (18 - IERC20Data(token).decimals()));
}
function _flushBackItem(
uint itemId,
address receiver,
address wrapper
) internal returns(uint dust) {
if ((dust = IERC20WrapperV1(wrapper).asInteroperable(itemId).balanceOf(address(this))) > 0)
TransferHelper.safeTransfer(address(IERC20WrapperV1(wrapper).asInteroperable(itemId)), receiver, dust);
}
function _tokenToInteroperable(
address token,
address wrapper
) internal view returns(address interoperable) {
if (token == address(0))
interoperable = address(IERC20WrapperV1(wrapper).asInteroperable(uint(IMateriaOrchestrator(address(this)).ETHEREUM_OBJECT_ID())));
else {
(, uint itemId) = _isEthItem(token, wrapper);
interoperable = address(IERC20WrapperV1(wrapper).asInteroperable(itemId));
}
}
}
// Dependency file: contracts/interfaces/IMateriaPair.sol
// pragma solidity >=0.5.0;
interface IMateriaPair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// Dependency file: contracts/libraries/SafeMath.sol
// pragma solidity 0.8.0;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// Dependency file: contracts/libraries/MateriaLibrary.sol
// pragma solidity >=0.5.0;
// import 'contracts/interfaces/IMateriaPair.sol';
// import 'contracts/interfaces/IMateriaFactory.sol';
// import "contracts/libraries/SafeMath.sol";
library MateriaLibrary {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'MateriaLibrary: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'MateriaLibrary: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint160(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'3a1b8c90f0ece2019085f38a482fb7538bb84471f01b56464ac88dd6bece344e' // 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,) = IMateriaPair(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, 'MateriaLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'MateriaLibrary: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'MateriaLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'MateriaLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'MateriaLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'MateriaLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'MateriaLibrary: 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, 'MateriaLibrary: 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);
}
}
}
// Dependency file: contracts/MateriaSwapper.sol
// pragma solidity 0.8.0;
// import 'contracts/MateriaOperator.sol';
// import 'contracts/interfaces/IMateriaOrchestrator.sol';
// import 'contracts/interfaces/IMateriaFactory.sol';
// import 'contracts/interfaces/IMateriaPair.sol';
// import 'contracts/interfaces/IERC20.sol';
// import 'contracts/interfaces/IERC20WrapperV1.sol';
// import 'contracts/interfaces/IEthItemMainInterface.sol';
// import 'contracts/libraries/MateriaLibrary.sol';
// import 'contracts/libraries/TransferHelper.sol';
contract MateriaSwapper is MateriaOperator {
constructor(address _orchestrator) MateriaOperator(_orchestrator) {}
function _swap(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,) = MateriaLibrary.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 ? MateriaLibrary.pairFor(factory, output, path[i + 2]) : _to;
IMateriaPair(MateriaLibrary.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) public ensure(deadline) returns (uint[] memory amounts) {
address factory = address(IMateriaOrchestrator(address(this)).factory());
address bridgeToken = address(IMateriaOrchestrator(address(this)).bridgeToken());
address erc20Wrapper = address(IMateriaOrchestrator(address(this)).erc20Wrapper());
TransferHelper.safeTransferFrom(path[0], msg.sender, address(this), amountIn);
(path[0], amountIn) = _wrapErc20(path[0], amountIn, erc20Wrapper);
bool ethItemOut;
uint itemId;
address tokenOut;
(ethItemOut, itemId) = _isEthItem(path[path.length - 1], erc20Wrapper);
if (!ethItemOut && bridgeToken != path[path.length - 1]) {
tokenOut = path[path.length - 1];
amountOutMin = _adjustAmount(tokenOut, amountOutMin);
path[path.length - 1] = address(IERC20WrapperV1(erc20Wrapper).asInteroperable(itemId));
}
amounts = MateriaLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransfer(
path[0], MateriaLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
if (ethItemOut) {
_swap(factory, amounts, path, to);
} else {
_swap(factory, amounts, path, address(this));
_unwrapErc20(itemId, tokenOut, amounts[amounts.length - 1], erc20Wrapper, to);
}
}
event Debug(uint amount);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] memory path,
address to,
uint deadline
) public ensure(deadline) returns (uint[] memory amounts) {
address factory = address(IMateriaOrchestrator(address(this)).factory());
address erc20Wrapper = address(IMateriaOrchestrator(address(this)).erc20Wrapper());
address tokenIn = path[0];
path[0] = address(IERC20WrapperV1(erc20Wrapper).asInteroperable(IERC20WrapperV1(erc20Wrapper).object(path[0])));
bool ethItemOut;
uint itemId;
(ethItemOut, itemId) = _isEthItem(path[path.length - 1], erc20Wrapper);
address tokenOut;
if (!ethItemOut && address(IMateriaOrchestrator(address(this)).bridgeToken()) != path[path.length - 1]) {
tokenOut = path[path.length - 1];
amountOut = _adjustAmount(tokenOut, amountOut);
path[path.length - 1] = address(IERC20WrapperV1(erc20Wrapper).asInteroperable(itemId));
}
amounts = MateriaLibrary.getAmountsIn(factory, amountOut, path);
amounts[0] = amounts[0] / (10**(18 - IERC20Data(tokenIn).decimals())) + 1;
require(amounts[0] <= amountInMax, 'EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amounts[0]);
(, amounts[0]) = _wrapErc20(tokenIn, amounts[0], erc20Wrapper);
TransferHelper.safeTransfer(
path[0], MateriaLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
if (ethItemOut) {
_swap(factory, amounts, path, to);
} else {
_swap(factory, amounts, path, address(this));
_unwrapErc20(itemId, tokenOut, amounts[amounts.length - 1], erc20Wrapper, to);
}
}
function swapExactETHForTokens(
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) public ensure(deadline) payable returns (uint[] memory amounts) {
address factory = address(IMateriaOrchestrator(address(this)).factory());
address bridgeToken = address(IMateriaOrchestrator(address(this)).bridgeToken());
address erc20Wrapper = address(IMateriaOrchestrator(address(this)).erc20Wrapper());
path[0] = _wrapEth(msg.value, erc20Wrapper);
bool ethItemOut;
uint itemId;
address tokenOut;
(ethItemOut, itemId) = _isEthItem(path[path.length - 1], erc20Wrapper);
if (!ethItemOut && bridgeToken != path[path.length - 1]) {
tokenOut = path[path.length - 1];
amountOutMin = _adjustAmount(tokenOut, amountOutMin);
path[path.length - 1] = address(IERC20WrapperV1(erc20Wrapper).asInteroperable(itemId));
}
amounts = MateriaLibrary.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransfer(
path[0], MateriaLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
if (ethItemOut) {
_swap(factory, amounts, path, to);
} else {
_swap(factory, amounts, path, address(this));
_unwrapErc20(itemId, tokenOut, amounts[amounts.length - 1], erc20Wrapper, to);
}
}
function swapTokensForExactETH(
uint amountOut,
uint amountInMax,
address[] memory path,
address to,
uint deadline
) public ensure(deadline) returns (uint[] memory amounts) {
address factory = address(IMateriaOrchestrator(address(this)).factory());
address erc20Wrapper = address(IMateriaOrchestrator(address(this)).erc20Wrapper());
uint ethId = uint(IMateriaOrchestrator(address(this)).ETHEREUM_OBJECT_ID());
address token = path[0];
path[0] = address(IERC20WrapperV1(erc20Wrapper).asInteroperable(IERC20WrapperV1(erc20Wrapper).object(path[0])));
amountOut = amountOut * (10 ** (18 - IERC20Data(path[path.length - 1]).decimals()));
amountInMax = _adjustAmount(token, amountInMax);
amounts = MateriaLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'INSUFFICIENT_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(token, msg.sender, address(this), amounts[0]);
(path[0], amounts[0]) = _wrapErc20(token, amounts[0], erc20Wrapper);
TransferHelper.safeTransfer(
path[0], MateriaLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(factory, amounts, path, address(this));
_unwrapEth(ethId, amounts[amounts.length - 1], erc20Wrapper, to);
}
function swapExactTokensForETH(
uint amountIn,
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) public ensure(deadline) returns (uint[] memory amounts) {
address factory = address(IMateriaOrchestrator(address(this)).factory());
address erc20Wrapper = address(IMateriaOrchestrator(address(this)).erc20Wrapper());
uint ethId = uint(IMateriaOrchestrator(address(this)).ETHEREUM_OBJECT_ID());
TransferHelper.safeTransferFrom(path[0], msg.sender, address(this), amountIn);
(path[0], amountIn) = _wrapErc20(path[0], amountIn, erc20Wrapper);
amounts = MateriaLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransfer(
path[0], MateriaLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(factory, amounts, path, address(this));
_unwrapEth(ethId, amounts[amounts.length - 1], erc20Wrapper, to);
}
function swapETHForExactTokens(
uint amountOut,
address[] memory path,
address to,
uint deadline
) public payable ensure(deadline) returns (uint[] memory amounts) {
address factory = address(IMateriaOrchestrator(address(this)).factory());
address erc20Wrapper = address(IMateriaOrchestrator(address(this)).erc20Wrapper());
address bridgeToken = address(IMateriaOrchestrator(address(this)).bridgeToken());
bool ethItemOut;
uint itemId;
address tokenOut;
(ethItemOut, itemId) = _isEthItem(path[path.length - 1], erc20Wrapper);
if (!ethItemOut && bridgeToken != path[path.length - 1]) {
tokenOut = path[path.length - 1];
amountOut = _adjustAmount(tokenOut, amountOut);
path[path.length - 1] = address(IERC20WrapperV1(erc20Wrapper).asInteroperable(itemId));
}
amounts = MateriaLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'INSUFFICIENT_INPUT_AMOUNT');
path[0] = _wrapEth(amounts[0], erc20Wrapper);
TransferHelper.safeTransfer(
path[0], MateriaLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
if (ethItemOut) {
_swap(factory, amounts, path, to);
} else {
_swap(factory, amounts, path, address(this));
_unwrapErc20(itemId, tokenOut, amounts[amounts.length - 1], erc20Wrapper, to);
}
if (msg.value > amounts[0])
TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
function swapExactItemsForTokens(
uint amountIn,
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) private ensure(deadline) {
address factory = address(IMateriaOrchestrator(address(this)).factory());
address erc20Wrapper = address(IMateriaOrchestrator(address(this)).erc20Wrapper());
bool ethItemOut;
uint itemId;
address tokenOut;
(ethItemOut, itemId) = _isEthItem(path[path.length - 1], erc20Wrapper);
if (!ethItemOut && address(IMateriaOrchestrator(address(this)).bridgeToken()) != path[path.length - 1]) {
tokenOut = path[path.length - 1];
amountOutMin = _adjustAmount(tokenOut, amountOutMin);
path[path.length - 1] = address(IERC20WrapperV1(erc20Wrapper).asInteroperable(itemId));
}
uint[] memory amounts = MateriaLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransfer(
path[0], MateriaLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
if (ethItemOut) {
_swap(factory, amounts, path, to);
} else {
_swap(factory, amounts, path, address(this));
_unwrapErc20(itemId, tokenOut, amounts[amounts.length - 1], erc20Wrapper, to);
}
}
function swapItemsForExactTokens(
uint amountOut,
uint amountInMax,
address[] memory path,
address to,
address from,
uint deadline
) private ensure(deadline) {
address factory = address(IMateriaOrchestrator(address(this)).factory());
address erc20Wrapper = address(IMateriaOrchestrator(address(this)).erc20Wrapper());
bool ethItemOut;
uint itemId;
address tokenOut;
(ethItemOut, itemId) = _isEthItem(path[path.length - 1], erc20Wrapper);
if (!ethItemOut && address(IMateriaOrchestrator(address(this)).bridgeToken()) != path[path.length - 1]) {
tokenOut = path[path.length - 1];
amountOut = _adjustAmount(tokenOut, amountOut);
path[path.length - 1] = address(IERC20WrapperV1(erc20Wrapper).asInteroperable(itemId));
}
uint[] memory amounts = MateriaLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'INSUFFICIENT_INPUT_AMOUNT');
{
uint amountBack;
if ((amountBack = amountInMax - amounts[0]) > 0)
TransferHelper.safeTransfer(path[0], from, amountBack);
}
TransferHelper.safeTransfer(
path[0], MateriaLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
if (ethItemOut) {
_swap(factory, amounts, path, to);
} else {
_swap(factory, amounts, path, address(this));
_unwrapErc20(itemId, tokenOut, amounts[amounts.length - 1], erc20Wrapper, to);
}
}
function swapExactItemsForEth(
uint amountIn,
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) private ensure(deadline) {
address factory = address(IMateriaOrchestrator(address(this)).factory());
address erc20Wrapper = address(IMateriaOrchestrator(address(this)).erc20Wrapper());
uint ethId = uint(IMateriaOrchestrator(address(this)).ETHEREUM_OBJECT_ID());
uint[] memory amounts = MateriaLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransfer(
path[0], MateriaLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(factory, amounts, path, address(this));
IERC20WrapperV1(erc20Wrapper).burn(
ethId,
amounts[amounts.length - 1]
);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapItemsForExactEth(
uint amountOut,
uint amountInMax,
address[] memory path,
address to,
address from,
uint deadline
) private ensure(deadline) {
address factory = address(IMateriaOrchestrator(address(this)).factory());
address erc20Wrapper = address(IMateriaOrchestrator(address(this)).erc20Wrapper());
uint ethId = uint(IMateriaOrchestrator(address(this)).ETHEREUM_OBJECT_ID());
uint[] memory amounts = MateriaLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'INSUFFICIENT_INPUT_AMOUNT');
{
uint amountBack;
if ((amountBack = amountInMax - amounts[0]) > 0)
TransferHelper.safeTransfer(path[0], from, amountBack);
}
TransferHelper.safeTransfer(
path[0], MateriaLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(factory, amounts, path, address(this));
IERC20WrapperV1(erc20Wrapper).burn(
ethId,
amounts[amounts.length - 1]
);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function onERC1155Received(
address,
address from,
uint,
uint value,
bytes calldata data
) public override returns(bytes4) {
uint operation;
uint amount;
address[] memory path;
address to;
uint deadline;
{ //to avoid "stack too deep"
bytes memory payload;
(operation, payload) = abi.decode(data, (uint, bytes));
(amount, path, to, deadline) = abi.decode(payload, (uint, address[], address, uint));
}
if (operation == 2) swapExactItemsForTokens(value, amount, path, to, deadline);
else if (operation == 3) swapItemsForExactTokens(amount, value, path, to, from, deadline);
else if (operation == 4) swapExactItemsForEth(value, amount, path, to, deadline);
else if (operation == 5) swapItemsForExactEth(amount, value, path, to, from, deadline);
else revert();
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) public override pure returns(bytes4) {
revert();
//return this.onERC1155BatchReceived.selector;
}
function supportsInterface(
bytes4
) public override pure returns (bool) {
return false;
}
}
// Dependency file: contracts/libraries/Math.sol
// pragma solidity =0.8.0;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// Dependency file: contracts/libraries/MateriaLiquidityMathLibrary.sol
// pragma solidity 0.8.0;
// import 'contracts/interfaces/IMateriaPair.sol';
// import 'contracts/interfaces/IMateriaFactory.sol';
// import 'contracts/libraries/SafeMath.sol';
// import 'contracts/libraries/Math.sol';
// import 'contracts/libraries/MateriaLibrary.sol';
// library containing some math for dealing with the liquidity shares of a pair, e.g. computing their exact value
// in terms of the underlying tokens
library MateriaLiquidityMathLibrary {
using SafeMath for uint256;
// computes the direction and magnitude of the profit-maximizing trade
function computeProfitMaximizingTrade(
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 reserveA,
uint256 reserveB
) pure internal returns (bool aToB, uint256 amountIn) {
aToB = SafeMath.mul(reserveA, truePriceTokenB)/reserveB < truePriceTokenA;
uint256 invariant = reserveA.mul(reserveB);
uint256 leftSide = Math.sqrt(
SafeMath.mul(
invariant.mul(1000),
aToB ? truePriceTokenA : truePriceTokenB)/
(aToB ? truePriceTokenB : truePriceTokenA).mul(997)
);
uint256 rightSide = (aToB ? reserveA.mul(1000) : reserveB.mul(1000)) / 997;
if (leftSide < rightSide) return (false, 0);
// compute the amount that must be sent to move the price to the profit-maximizing price
amountIn = leftSide.sub(rightSide);
}
// gets the reserves after an arbitrage moves the price to the profit-maximizing ratio given an externally observed true price
function getReservesAfterArbitrage(
address factory,
address tokenA,
address tokenB,
uint256 truePriceTokenA,
uint256 truePriceTokenB
) view internal returns (uint256 reserveA, uint256 reserveB) {
// first get reserves before the swap
(reserveA, reserveB) = MateriaLibrary.getReserves(factory, tokenA, tokenB);
require(reserveA > 0 && reserveB > 0, 'MateriaArbitrageLibrary: ZERO_PAIR_RESERVES');
// then compute how much to swap to arb to the true price
(bool aToB, uint256 amountIn) = computeProfitMaximizingTrade(truePriceTokenA, truePriceTokenB, reserveA, reserveB);
if (amountIn == 0) {
return (reserveA, reserveB);
}
// now affect the trade to the reserves
if (aToB) {
uint amountOut = MateriaLibrary.getAmountOut(amountIn, reserveA, reserveB);
reserveA += amountIn;
reserveB -= amountOut;
} else {
uint amountOut = MateriaLibrary.getAmountOut(amountIn, reserveB, reserveA);
reserveB += amountIn;
reserveA -= amountOut;
}
}
// computes liquidity value given all the parameters of the pair
function computeLiquidityValue(
uint256 reservesA,
uint256 reservesB,
uint256 totalSupply,
uint256 liquidityAmount,
bool feeOn,
uint kLast
) internal pure returns (uint256 tokenAAmount, uint256 tokenBAmount) {
if (feeOn && kLast > 0) {
uint rootK = Math.sqrt(reservesA.mul(reservesB));
uint rootKLast = Math.sqrt(kLast);
if (rootK > rootKLast) {
uint numerator1 = totalSupply;
uint numerator2 = rootK.sub(rootKLast);
uint denominator = rootK.mul(5).add(rootKLast);
uint feeLiquidity = SafeMath.mul(numerator1, numerator2)/ denominator;
totalSupply = totalSupply.add(feeLiquidity);
}
}
return (reservesA.mul(liquidityAmount) / totalSupply, reservesB.mul(liquidityAmount) / totalSupply);
}
// get all current parameters from the pair and compute value of a liquidity amount
// **note this is subject to manipulation, e.g. sandwich attacks**. prefer passing a manipulation resistant price to
// #getLiquidityValueAfterArbitrageToPrice
function getLiquidityValue(
address factory,
address tokenA,
address tokenB,
uint256 liquidityAmount
) internal view returns (uint256 tokenAAmount, uint256 tokenBAmount) {
(uint256 reservesA, uint256 reservesB) = MateriaLibrary.getReserves(factory, tokenA, tokenB);
IMateriaPair pair = IMateriaPair(MateriaLibrary.pairFor(factory, tokenA, tokenB));
bool feeOn = IMateriaFactory(factory).feeTo() != address(0);
uint kLast = feeOn ? pair.kLast() : 0;
uint totalSupply = pair.totalSupply();
return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeOn, kLast);
}
// given two tokens, tokenA and tokenB, and their "true price", i.e. the observed ratio of value of token A to token B,
// and a liquidity amount, returns the value of the liquidity in terms of tokenA and tokenB
function getLiquidityValueAfterArbitrageToPrice(
address factory,
address tokenA,
address tokenB,
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 liquidityAmount
) internal view returns (
uint256 tokenAAmount,
uint256 tokenBAmount
) {
bool feeOn = IMateriaFactory(factory).feeTo() != address(0);
IMateriaPair pair = IMateriaPair(MateriaLibrary.pairFor(factory, tokenA, tokenB));
uint kLast = feeOn ? pair.kLast() : 0;
uint totalSupply = pair.totalSupply();
// this also checks that totalSupply > 0
require(totalSupply >= liquidityAmount && liquidityAmount > 0, 'ComputeLiquidityValue: LIQUIDITY_AMOUNT');
(uint reservesA, uint reservesB) = getReservesAfterArbitrage(factory, tokenA, tokenB, truePriceTokenA, truePriceTokenB);
return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeOn, kLast);
}
}
// Root file: contracts/MateriaOrchestrator.sol
pragma solidity 0.8.0;
// import 'contracts/interfaces/IMVDFunctionalitiesManager.sol';
// import 'contracts/interfaces/IDoubleProxy.sol';
// import 'contracts/interfaces/IMVDProxy.sol';
// import 'contracts/interfaces/IMateriaOrchestrator.sol';
// import 'contracts/interfaces/IMateriaFactory.sol';
// import 'contracts/interfaces/IMateriaOperator.sol';
// import 'contracts/interfaces/IMateriaLiquidityRemover.sol';
// import 'contracts/MateriaSwapper.sol';
// import 'contracts/interfaces/IEthItemInteroperableInterface.sol';
// import 'contracts/interfaces/IEthItemMainInterface.sol';
// import 'contracts/interfaces/IERC20WrapperV1.sol';
// import 'contracts/libraries/MateriaLibrary.sol';
// import 'contracts/libraries/TransferHelper.sol';
// import 'contracts/libraries/MateriaLiquidityMathLibrary.sol';
abstract contract Proxy {
function _delegate(address implementation) internal virtual {
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
contract MateriaOrchestrator is Proxy, IMateriaOrchestrator {
IDoubleProxy public override doubleProxy;
IMateriaOperator public override swapper;
IMateriaOperator public override liquidityAdder;
IMateriaOperator public override liquidityRemover;
IMateriaFactory public override factory;
IERC20WrapperV1 public override erc20Wrapper;
IERC20 public override bridgeToken;
uint public override ETHEREUM_OBJECT_ID;
constructor(
address initialFactory,
address initialBridgeToken,
address initialErc20Wrapper,
address initialDoubleProxy
) {
factory = IMateriaFactory(initialFactory);
bridgeToken = IERC20(initialBridgeToken);
erc20Wrapper = IERC20WrapperV1(initialErc20Wrapper);
ETHEREUM_OBJECT_ID = uint(keccak256(bytes("THE ETHEREUM OBJECT IT")));
doubleProxy = IDoubleProxy(initialDoubleProxy);
}
function setDoubleProxy(
address newDoubleProxy
) onlyDFO external override {
doubleProxy = IDoubleProxy(newDoubleProxy);
}
function setBridgeToken(
address newBridgeToken
) onlyDFO external override {
bridgeToken = IERC20(newBridgeToken);
}
function setErc20Wrapper(
address newErc20Wrapper
) onlyDFO external override {
erc20Wrapper = IERC20WrapperV1(newErc20Wrapper);
}
function setFactory(
address newFactory
) onlyDFO external override {
factory = IMateriaFactory(newFactory);
}
function setEthereumObjectId(
uint newEthereumObjectId
) onlyDFO external override {
ETHEREUM_OBJECT_ID = newEthereumObjectId;
}
function setSwapper(
address _swapper,
bool destroyOld
) external override {
if (destroyOld)
IMateriaOperator(swapper).destroy(msg.sender);
swapper = IMateriaOperator(_swapper);
}
function setLiquidityAdder(
address _adder,
bool destroyOld
) external override {
if (destroyOld)
IMateriaOperator(liquidityAdder).destroy(msg.sender);
liquidityAdder = IMateriaOperator(_adder);
}
function setLiquidityRemover(
address _remover,
bool destroyOld
) external override {
if (destroyOld)
IMateriaOperator(liquidityRemover).destroy(msg.sender);
liquidityRemover = IMateriaOperator(_remover);
}
function retire(
address newOrchestrator,
bool destroyOld,
address receiver
) onlyDFO external override {
liquidityAdder.setOrchestrator(newOrchestrator);
liquidityRemover.setOrchestrator(newOrchestrator);
swapper.setOrchestrator(newOrchestrator);
factory.transferOwnership(newOrchestrator);
if (destroyOld) selfdestruct(payable(receiver));
}
function setFees(
address token,
uint materiaFee,
uint swapFee
) onlyDFO external override {
factory.setFees(
MateriaLibrary.pairFor(address(factory), address(bridgeToken), token),
materiaFee,
swapFee
);
}
function setDefaultFees(
uint materiaFee,
uint swapFee
) onlyDFO external override {
factory.setDefaultFees(
materiaFee,
swapFee
);
}
//better be safe than sorry
function getCrumbs(
address token,
uint amount,
address receiver
) onlyDFO external override {
TransferHelper.safeTransfer(token, receiver, amount);
}
modifier onlyDFO() {
require(IMVDFunctionalitiesManager(IMVDProxy(doubleProxy.proxy()).getMVDFunctionalitiesManagerAddress()).isAuthorizedFunctionality(msg.sender), "Unauthorized");
_;
}
receive() external payable {
require(msg.sender == address(erc20Wrapper),'Only EthItem can send ETH to this contract');
}
// as ERC1155 receiver
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata payload
) external override returns(bytes4) {
(uint operation,) = abi.decode(payload, (uint, bytes));
if (operation == 1) { //Adding liquidity
_delegate(address(liquidityAdder));
} else if (operation == 2 || operation == 3 || operation == 4 || operation == 5) {
_delegate(address(swapper)); //Swapping
} else {
revert();
}
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) external pure override returns(bytes4) {
revert();
//return this.onERC1155BatchReceived.selector;
}
//Liquidity adding
function addLiquidity(
address token,
uint tokenAmountDesired,
uint bridgeAmountDesired,
uint tokenAmountMin,
uint bridgeAmountMin,
address to,
uint deadline
) external override returns (uint amountA, uint amountB, uint liquidity) {
_delegate(address(liquidityAdder));
}
function addLiquidityETH(
uint bridgeAmountDesired,
uint EthAmountMin,
uint bridgeAmountMin,
address to,
uint deadline
) external override payable returns (uint amountToken, uint amountETH, uint liquidity) {
_delegate(address(liquidityAdder));
}
//Liquidity removing
function removeLiquidity(
address token,
uint liquidity,
uint tokenAmountMin,
uint bridgeAmountMin,
address to,
uint deadline
) public override {
_delegate(address(liquidityRemover));
}
function removeLiquidityETH(
uint liquidity,
uint bridgeAmountMin,
uint EthAmountMin,
address to,
uint deadline
) public override {
_delegate(address(liquidityRemover));
}
function removeLiquidityWithPermit(
address token,
uint liquidity,
uint tokenAmountMin,
uint bridgeAmountMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) public override {
_delegate(address(liquidityRemover));
}
function removeLiquidityETHWithPermit(
uint liquidity,
uint tokenAmountMin,
uint bridgeAmountMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) public override {
_delegate(address(liquidityRemover));
}
//Swapping
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) public override returns (uint[] memory amounts) {
_delegate(address(swapper));
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] memory path,
address to,
uint deadline
) public override returns (uint[] memory amounts) {
_delegate(address(swapper));
}
function swapExactETHForTokens(
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) public override payable {
_delegate(address(swapper));
}
function swapTokensForExactETH(
uint amountOut,
uint amountInMax,
address[] memory path,
address to,
uint deadline
) public override {
_delegate(address(swapper));
}
function swapExactTokensForETH(
uint amountIn,
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) public override {
_delegate(address(swapper));
}
function swapETHForExactTokens(
uint amountOut,
address[] memory path,
address to,
uint deadline
) public override payable {
_delegate(address(swapper));
}
//Materia Library interface
function quote(
uint amountA,
uint reserveA,
uint reserveB
) public pure override returns (uint amountB) {
return MateriaLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(
uint amountIn,
uint reserveIn,
uint reserveOut
) public pure override returns (uint amountOut) {
return MateriaLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(
uint amountOut,
uint reserveIn,
uint reserveOut
) public pure override returns (uint amountIn) {
return MateriaLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(
uint amountIn,
address[] memory path
) public view override returns (uint[] memory amounts) {
return MateriaLibrary.getAmountsOut(address(factory), amountIn, path);
}
function getAmountsIn(
uint amountOut,
address[] memory path
) public view override returns (uint[] memory amounts) {
return MateriaLibrary.getAmountsIn(address(factory), amountOut, path);
}
// Utilities for the interface
function isEthItem(
address token
) public view override returns(address collection, bool ethItem, uint256 itemId) {
if (token == address(0)) {
return(address(0), false, 0);
} else {
try IEthItemInteroperableInterface(token).mainInterface() returns(address mainInterface) {
return(mainInterface, true, IEthItemInteroperableInterface(token).objectId());
} catch {
return(address(0), false, 0);
}
}
}
}
|
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, 'MateriaLibrary: 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);
}
}
| 1,991,397 |
./full_match/137/0xC7044b933c330Cb2b78a8e7348ff053920cB75Fb/sources/ERC721.sol
|
Sets the royalty information for a specific token id, overriding the global default. Requirements: - `tokenId` must be already minted. - `receiver` cannot be the zero address. - `feeNumerator` cannot be greater than the fee denominator./
|
function setRoyaltyFee(address receiver, uint96 feeNumerator) external {
require(receiver != address(0), "ERC2981: invalid receiver");
require(msg.sender == operator,"ERC1155: caller doesn't have operator role");
royaltyFeeInfo = RoyaltyInfo(receiver, feeNumerator);
emit RoyaltyInfoChanged(receiver, feeNumerator);
}
| 3,766,605 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "../../openzeppelin-solidity/contracts/SafeERC20.sol";
import "../../openzeppelin-solidity/contracts/ReentrancyGuard.sol";
import "../../interfaces/IReleaseSchedule.sol";
/**
* Escrow to release tokens according to a schedule.
*/
contract ReleaseEscrow is ReentrancyGuard {
using SafeERC20 for IERC20;
// When the release starts.
uint256 public immutable startTime;
// Reward token contract address
IERC20 public immutable rewardToken;
// Where the funds go to.
address public immutable beneficiary;
// Schedule for release of tokens.
IReleaseSchedule public immutable schedule;
// The number of weeks that have been withdrawn from the escrow.
uint256 public numberOfWeeksWithdrawn;
constructor(
address beneficiary_,
address rewardToken_,
address schedule_,
uint256 startTime_
) {
beneficiary = beneficiary_;
rewardToken = IERC20(rewardToken_);
schedule = IReleaseSchedule(schedule_);
require(
// solhint-disable-next-line not-rely-on-time
startTime_ > block.timestamp,
"ReleaseEscrow: start time must be in the future"
);
startTime = startTime_;
}
/**
* Exit function to collect all remaining tokens, in the case of rounding errors.
*/
function collectDust() external started nonReentrant {
require(
numberOfWeeksWithdrawn >= schedule.totalPeriods(),
"ReleaseEscrow: not all mining rewards have been withdrawn"
);
rewardToken.safeTransfer(
beneficiary,
rewardToken.balanceOf(address(this))
);
}
/**
* Returns true if release has already started.
*/
function hasStarted() public view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return startTime < block.timestamp;
}
modifier started {
require(hasStarted(), "ReleaseEscrow: release has not started yet");
_;
}
/**
* The current week in the release schedule. Starts from 0.
*/
function currentWeekIndex() public view started returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return (block.timestamp - startTime) / (1 weeks);
}
/**
* Withdraws tokens based on the weeks elapsed.
* `_latestWeek` can be specified so execution is bounded.
* Up to two weeks worth of tokens may be withdrawn ahead of time. This gives the protocol time
* to move tokens into the right places in the preceding week.
* @param _latestWeek The week to withdraw up to. I.e. if "1", this will withdraw the funds of week 0.
*/
function withdraw(uint256 _latestWeek) external started nonReentrant {
require(_latestWeek > 0, "ReleaseEscrow: week must be greater than 0");
// Up to two weeks worth of tokens may be withdrawn in advance.
// i.e. the current week and the next week.
uint256 latestPossibleWeek = currentWeekIndex() + 2;
require(
_latestWeek <= latestPossibleWeek,
"ReleaseEscrow: latest week is too late"
);
require(
_latestWeek > numberOfWeeksWithdrawn,
"ReleaseEscrow: those weeks have already been withdrawn"
);
uint256 totalTransfer;
for (uint256 i = numberOfWeeksWithdrawn; i < _latestWeek; i++) {
// Get tokens for the next week, so this is "i"
// That is; If 1 week has been withdrawn already, we need to withdraw week 1 next.
// Because that 1 week was week 0.
totalTransfer += schedule.getTokensForPeriod(i);
}
rewardToken.safeTransfer(beneficiary, totalTransfer);
numberOfWeeksWithdrawn = _latestWeek;
}
}
|
Returns true if release has already started./ solhint-disable-next-line not-rely-on-time
|
function hasStarted() public view returns (bool) {
return startTime < block.timestamp;
}
| 13,100,812 |
pragma solidity ^0.4.21;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
//uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
// Amount of wei raised
uint256 public tokensDistributed;
/**
* 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);
/**
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function Crowdsale(address _wallet, ERC20 _token) public {
require(_wallet != address(0));
require(_token != address(0));
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
tokensDistributed = tokensDistributed.add(tokens);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transferFrom(wallet, _beneficiary, _tokenAmount);
//token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
// must override
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(now >= openingTime && now <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public {
//require(_openingTime >= now);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return now > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _cap Max amount of wei to be contributed
*/
function CappedCrowdsale(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
/**
* @title RefundVault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Supports refunding the money if crowdsale fails,
* and forwarding it if crowdsale is successful.
*/
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
/**
* @param _wallet Vault address
*/
function RefundVault(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Active;
}
/**
* @param investor Investor address
*/
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
state = State.Closed;
emit Closed();
wallet.transfer(address(this).balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
/**
* @param investor Investor address
*/
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
emit Refunded(investor, depositedValue);
}
}
/**
* @title RefundableCrowdsale
* @dev Extension of Crowdsale contract that adds a funding goal, and
* the possibility of users getting a refund if goal is not met.
* Uses a RefundVault as the crowdsale's vault.
*/
contract RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
// minimum amount of funds to be raised in weis
uint256 public goal;
// refund vault used to hold funds while crowdsale is running
RefundVault public vault;
/**
* @dev Constructor, creates RefundVault.
* @param _goal Funding goal
*/
function RefundableCrowdsale(uint256 _goal) public {
require(_goal > 0);
vault = new RefundVault(wallet);
goal = _goal;
}
/**
* @dev Investors can claim refunds here if crowdsale is unsuccessful
*/
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
/**
* @dev Checks whether funding goal was reached.
* @return Whether funding goal was reached
*/
function goalReached() public view returns (bool) {
return weiRaised >= goal;
}
/**
* @dev vault finalization task, called when owner calls finalize()
*/
function finalization() internal {
if (goalReached()) {
vault.close();
} else {
vault.transferOwnership(owner);
}
super.finalization();
}
/**
* @dev Overrides Crowdsale fund forwarding, sending funds to vault.
*/
function _forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
}
/**
* @title PostDeliveryCrowdsale
* @dev Crowdsale that locks tokens from withdrawal until it ends.
*/
contract PostDeliveryCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
mapping(address => uint256) public balances;
/**
* @dev Overrides parent by storing balances instead of issuing tokens right away.
* @param _beneficiary Token purchaser
* @param _tokenAmount Amount of tokens purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount);
}
/**
* @dev Withdraw tokens only after crowdsale ends.
*/
function withdrawTokens(address _beneficiary) public onlyOwner {
require(hasClosed());
uint256 amount = balances[_beneficiary];
require(amount > 0);
balances[_beneficiary] = 0;
_deliverTokens(_beneficiary, amount);
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract CxNcontract is CappedCrowdsale, RefundableCrowdsale, PostDeliveryCrowdsale {
// Only for testNet:
//uint privSale1start = now;
// Bounty hive
address partnerAddress;
// // 20 Mar 2018 07:00:00 PM CST
uint privSale1start = 1521594000;
// 10 Apr 2018 11:59:00 PM CST
uint privSale1end = 1523426400;
// 16 Apr 2018 07:00:00 PM CST
uint privSale2start = 1523926800;
// 07 May 2018 11:59:00 PM CST
uint privSale2end = 1525759200;
// 11 May 2018 07:00:00 PM CST
uint saleStart = 1526086800;
// 18 Jun 2018 11:59:00 PM CST
uint saleEnd = 1526709600;
function CxNcontract(uint256 _openingTime, uint256 _closingTime, address _wallet, uint256 _cap, ERC20 _token, uint256 _goal, address _partnerAddress) public payable
Crowdsale(_wallet, _token)
CappedCrowdsale(_cap)
TimedCrowdsale(_openingTime, _closingTime)
RefundableCrowdsale(_goal)
{
//As goal needs to be met for a successful crowdsale
//the value needs to less or equal than a cap which is limit for accepted funds
partnerAddress = _partnerAddress;
require(_goal <= _cap);
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(checkValue(_weiAmount));
super._preValidatePurchase(_beneficiary, _weiAmount);
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(getRate());
}
function checkValue(uint256 amount) internal view returns (bool) {
if (now > privSale1start && now < privSale1end)
return (amount >= 5 ether);
else if (now > privSale2start && now < privSale2end)
return (amount >= 5 ether);
else if (now > saleStart && now < saleEnd)
return (amount >= 0.1 ether);
return false;
}
function getRate() public view returns (uint256) {
if (now > privSale1start && now < privSale1end)
return 14375; // Stage I
else if (now > privSale2start && now < privSale2end)
return 13750; // Stage II
else if (now > saleStart && now < saleEnd)
return 12500; // Public Sale
return 0;
}
function finalization() internal {
uint256 tokensForPartners = 2800000 ether;
uint256 tokensNeededToClose = tokensForPartners.add(tokensDistributed);
require(token.balanceOf(wallet) >= tokensNeededToClose);
token.transferFrom(wallet, partnerAddress, tokensForPartners);
super.finalization();
}
}
|
Event for token purchase logging purchaser who paid for the tokens beneficiary who got the tokens value weis paid for purchase amount amount of tokens purchased/ _wallet Address where collected funds will be forwarded to _token Address of the token being sold/
|
function Crowdsale(address _wallet, ERC20 _token) public {
require(_wallet != address(0));
require(_token != address(0));
wallet = _wallet;
token = _token;
}
| 10,577,285 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.7 <0.9.0;
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol';
import '../interfaces/IDCATokenDescriptor.sol';
import '../interfaces/IDCAPermissionManager.sol';
import '../libraries/PermissionMath.sol';
import '../utils/Governable.sol';
// Note: ideally, this would be part of the DCAHub. However, since we've reached the max bytecode size, we needed to make it its own contract
contract DCAPermissionsManager is ERC721, EIP712, Governable, IDCAPermissionManager {
struct TokenPermission {
// The actual permissions
uint8 permissions;
// The block number when it was last updated
uint248 lastUpdated;
}
using PermissionMath for Permission[];
using PermissionMath for uint8;
/// @inheritdoc IDCAPermissionManager
bytes32 public constant PERMIT_TYPEHASH = keccak256('Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)');
/// @inheritdoc IDCAPermissionManager
bytes32 public constant PERMISSION_PERMIT_TYPEHASH =
keccak256(
'PermissionPermit(PermissionSet[] permissions,uint256 tokenId,uint256 nonce,uint256 deadline)PermissionSet(address operator,uint8[] permissions)'
);
/// @inheritdoc IDCAPermissionManager
bytes32 public constant PERMISSION_SET_TYPEHASH = keccak256('PermissionSet(address operator,uint8[] permissions)');
/// @inheritdoc IDCAPermissionManager
IDCATokenDescriptor public nftDescriptor;
/// @inheritdoc IDCAPermissionManager
address public hub;
/// @inheritdoc IDCAPermissionManager
mapping(address => uint256) public nonces;
mapping(uint256 => uint256) public lastOwnershipChange;
mapping(uint256 => mapping(address => TokenPermission)) public tokenPermissions;
constructor(address _governor, IDCATokenDescriptor _descriptor)
ERC721('Mean Finance DCA', 'DCA')
EIP712('Mean Finance DCA', '1')
Governable(_governor)
{
if (address(_descriptor) == address(0)) revert ZeroAddress();
nftDescriptor = _descriptor;
}
/// @inheritdoc IDCAPermissionManager
function setHub(address _hub) external {
if (_hub == address(0)) revert ZeroAddress();
if (hub != address(0)) revert HubAlreadySet();
hub = _hub;
}
/// @inheritdoc IDCAPermissionManager
function mint(
uint256 _id,
address _owner,
PermissionSet[] calldata _permissions
) external {
if (msg.sender != hub) revert OnlyHubCanExecute();
_mint(_owner, _id);
_setPermissions(_id, _permissions);
}
/// @inheritdoc IDCAPermissionManager
function hasPermission(
uint256 _id,
address _address,
Permission _permission
) external view returns (bool) {
if (ownerOf(_id) == _address) {
return true;
}
TokenPermission memory _tokenPermission = tokenPermissions[_id][_address];
// If there was an ownership change after the permission was last updated, then the address doesn't have the permission
return _tokenPermission.permissions.hasPermission(_permission) && lastOwnershipChange[_id] < _tokenPermission.lastUpdated;
}
/// @inheritdoc IDCAPermissionManager
function hasPermissions(
uint256 _id,
address _address,
Permission[] calldata _permissions
) external view returns (bool[] memory _hasPermissions) {
_hasPermissions = new bool[](_permissions.length);
if (ownerOf(_id) == _address) {
// If the address is the owner, then they have all permissions
for (uint256 i; i < _permissions.length; i++) {
_hasPermissions[i] = true;
}
} else {
// If it's not the owner, then check one by one
TokenPermission memory _tokenPermission = tokenPermissions[_id][_address];
if (lastOwnershipChange[_id] < _tokenPermission.lastUpdated) {
for (uint256 i; i < _permissions.length; i++) {
if (_tokenPermission.permissions.hasPermission(_permissions[i])) {
_hasPermissions[i] = true;
}
}
}
}
}
/// @inheritdoc IDCAPermissionManager
function burn(uint256 _id) external {
if (msg.sender != hub) revert OnlyHubCanExecute();
_burn(_id);
}
/// @inheritdoc IDCAPermissionManager
function modify(uint256 _id, PermissionSet[] calldata _permissions) external {
if (msg.sender != ownerOf(_id)) revert NotOwner();
_modify(_id, _permissions);
}
/// @inheritdoc IDCAPermissionManager
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparatorV4();
}
/// @inheritdoc IDCAPermissionManager
function permit(
address _spender,
uint256 _tokenId,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
if (block.timestamp > _deadline) revert ExpiredDeadline();
address _owner = ownerOf(_tokenId);
bytes32 _structHash = keccak256(abi.encode(PERMIT_TYPEHASH, _spender, _tokenId, nonces[_owner]++, _deadline));
bytes32 _hash = _hashTypedDataV4(_structHash);
address _signer = ECDSA.recover(_hash, _v, _r, _s);
if (_signer != _owner) revert InvalidSignature();
_approve(_spender, _tokenId);
}
/// @inheritdoc IDCAPermissionManager
function permissionPermit(
PermissionSet[] calldata _permissions,
uint256 _tokenId,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
if (block.timestamp > _deadline) revert ExpiredDeadline();
address _owner = ownerOf(_tokenId);
bytes32 _structHash = keccak256(
abi.encode(PERMISSION_PERMIT_TYPEHASH, keccak256(_encode(_permissions)), _tokenId, nonces[_owner]++, _deadline)
);
bytes32 _hash = _hashTypedDataV4(_structHash);
address _signer = ECDSA.recover(_hash, _v, _r, _s);
if (_signer != _owner) revert InvalidSignature();
_modify(_tokenId, _permissions);
}
/// @inheritdoc IDCAPermissionManager
function setNFTDescriptor(IDCATokenDescriptor _descriptor) external onlyGovernor {
if (address(_descriptor) == address(0)) revert ZeroAddress();
nftDescriptor = _descriptor;
emit NFTDescriptorSet(_descriptor);
}
/// @inheritdoc ERC721
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
return nftDescriptor.tokenURI(hub, _tokenId);
}
function _encode(PermissionSet[] calldata _permissions) internal pure returns (bytes memory _result) {
for (uint256 i; i < _permissions.length; i++) {
_result = bytes.concat(_result, keccak256(_encode(_permissions[i])));
}
}
function _encode(PermissionSet calldata _permission) internal pure returns (bytes memory _result) {
_result = abi.encode(PERMISSION_SET_TYPEHASH, _permission.operator, keccak256(_encode(_permission.permissions)));
}
function _encode(Permission[] calldata _permissions) internal pure returns (bytes memory _result) {
_result = new bytes(_permissions.length * 32);
for (uint256 i; i < _permissions.length; i++) {
_result[(i + 1) * 32 - 1] = bytes1(uint8(_permissions[i]));
}
}
function _modify(uint256 _id, PermissionSet[] calldata _permissions) internal {
_setPermissions(_id, _permissions);
emit Modified(_id, _permissions);
}
function _setPermissions(uint256 _id, PermissionSet[] calldata _permissions) internal {
uint248 _blockNumber = uint248(_getBlockNumber());
for (uint256 i; i < _permissions.length; i++) {
if (_permissions[i].permissions.length == 0) {
delete tokenPermissions[_id][_permissions[i].operator];
} else {
tokenPermissions[_id][_permissions[i].operator] = TokenPermission({
permissions: _permissions[i].permissions.toUInt8(),
lastUpdated: _blockNumber
});
}
}
}
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _id
) internal override {
if (_to == address(0)) {
// When token is being burned, we can delete this entry on the mapping
delete lastOwnershipChange[_id];
} else if (_from != address(0)) {
// If the token is being minted, then no need to write this
lastOwnershipChange[_id] = _getBlockNumber();
}
}
// Note: virtual so that it can be overriden in tests
function _getBlockNumber() internal view virtual returns (uint256) {
return block.number;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
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;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.7 <0.9.0;
/// @title The interface for generating a token's description
/// @notice Contracts that implement this interface must return a base64 JSON with the entire description
interface IDCATokenDescriptor {
/// @notice Thrown when a user tries get the description of an unsupported interval
error InvalidInterval();
/// @notice Generates a token's description, both the JSON and the image inside
/// @param _hub The address of the DCA Hub
/// @param _tokenId The token/position id
/// @return _description The position's description
function tokenURI(address _hub, uint256 _tokenId) external view returns (string memory _description);
/// @notice Returns a text description for the given swap interval. For example for 3600, returns 'Hourly'
/// @dev Will revert with InvalidInterval if the function receives a unsupported interval
/// @param _swapInterval The swap interval
/// @return _description The description
function intervalToDescription(uint32 _swapInterval) external pure returns (string memory _description);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.7 <0.9.0;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import './IDCATokenDescriptor.sol';
/// @title The interface for all permission related matters
/// @notice These methods allow users to set and remove permissions to their positions
interface IDCAPermissionManager is IERC721 {
/// @notice Set of possible permissions
enum Permission {
INCREASE,
REDUCE,
WITHDRAW,
TERMINATE
}
/// @notice A set of permissions for a specific operator
struct PermissionSet {
// The address of the operator
address operator;
// The permissions given to the overator
Permission[] permissions;
}
/// @notice Emitted when permissions for a token are modified
/// @param tokenId The id of the token
/// @param permissions The set of permissions that were updated
event Modified(uint256 tokenId, PermissionSet[] permissions);
/// @notice Emitted when the address for a new descritor is set
/// @param descriptor The new descriptor contract
event NFTDescriptorSet(IDCATokenDescriptor descriptor);
/// @notice Thrown when a user tries to set the hub, once it was already set
error HubAlreadySet();
/// @notice Thrown when a user provides a zero address when they shouldn't
error ZeroAddress();
/// @notice Thrown when a user calls a method that can only be executed by the hub
error OnlyHubCanExecute();
/// @notice Thrown when a user tries to modify permissions for a token they do not own
error NotOwner();
/// @notice Thrown when a user tries to execute a permit with an expired deadline
error ExpiredDeadline();
/// @notice Thrown when a user tries to execute a permit with an invalid signature
error InvalidSignature();
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
// solhint-disable-next-line func-name-mixedcase
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The permit typehash used in the permission permit signature
/// @return The typehash for the permission permit
// solhint-disable-next-line func-name-mixedcase
function PERMISSION_PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The permit typehash used in the permission permit signature
/// @return The typehash for the permission set
// solhint-disable-next-line func-name-mixedcase
function PERMISSION_SET_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Returns the NFT descriptor contract
/// @return The contract for the NFT descriptor
function nftDescriptor() external returns (IDCATokenDescriptor);
/// @notice Returns the address of the DCA Hub
/// @return The address of the DCA Hub
function hub() external returns (address);
/// @notice Returns the next nonce to use for a given user
/// @param _user The address of the user
/// @return _nonce The next nonce to use
function nonces(address _user) external returns (uint256 _nonce);
/// @notice Returns whether the given address has the permission for the given token
/// @param _id The id of the token to check
/// @param _address The address of the user to check
/// @param _permission The permission to check
/// @return Whether the user has the permission or not
function hasPermission(
uint256 _id,
address _address,
Permission _permission
) external view returns (bool);
/// @notice Returns whether the given address has the permissions for the given token
/// @param _id The id of the token to check
/// @param _address The address of the user to check
/// @param _permissions The permissions to check
/// @return _hasPermissions Whether the user has each permission or not
function hasPermissions(
uint256 _id,
address _address,
Permission[] calldata _permissions
) external view returns (bool[] memory _hasPermissions);
/// @notice Sets the address for the hub
/// @dev Can only be successfully executed once. Once it's set, it can be modified again
/// Will revert:
/// With ZeroAddress if address is zero
/// With HubAlreadySet if the hub has already been set
/// @param _hub The address to set for the hub
function setHub(address _hub) external;
/// @notice Mints a new NFT with the given id, and sets the permissions for it
/// @dev Will revert with OnlyHubCanExecute if the caller is not the hub
/// @param _id The id of the new NFT
/// @param _owner The owner of the new NFT
/// @param _permissions Permissions to set for the new NFT
function mint(
uint256 _id,
address _owner,
PermissionSet[] calldata _permissions
) external;
/// @notice Burns the NFT with the given id, and clears all permissions
/// @dev Will revert with OnlyHubCanExecute if the caller is not the hub
/// @param _id The token's id
function burn(uint256 _id) external;
/// @notice Sets new permissions for the given tokens
/// @dev Will revert with NotOwner if the caller is not the token's owner.
/// Operators that are not part of the given permission sets do not see their permissions modified.
/// In order to remove permissions to an operator, provide an empty list of permissions for them
/// @param _id The token's id
/// @param _permissions A list of permission sets
function modify(uint256 _id, PermissionSet[] calldata _permissions) external;
/// @notice Approves spending of a specific token ID by spender via signature
/// @param _spender The account that is being approved
/// @param _tokenId The ID of the token that is being approved for spending
/// @param _deadline The deadline timestamp by which the call must be mined for the approve to work
/// @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 _spender,
uint256 _tokenId,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
/// @notice Sets permissions via signature
/// @dev This method works similarly to `modify`, but instead of being executed by the owner, it can be set my signature
/// @param _permissions The permissions to set
/// @param _tokenId The token's id
/// @param _deadline The deadline timestamp by which the call must be mined for the approve to work
/// @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 permissionPermit(
PermissionSet[] calldata _permissions,
uint256 _tokenId,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
/// @notice Sets a new NFT descriptor
/// @dev Will revert with ZeroAddress if address is zero
/// @param _descriptor The new NFT descriptor contract
function setNFTDescriptor(IDCATokenDescriptor _descriptor) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.7 <0.9.0;
import '../interfaces/IDCAPermissionManager.sol';
/// @title Permission Math library
/// @notice Provides functions to easily convert from permissions to an int representation and viceversa
library PermissionMath {
/// @notice Takes a list of permissions and returns the int representation of the set that contains them all
/// @param _permissions The list of permissions
/// @return _representation The uint representation
function toUInt8(IDCAPermissionManager.Permission[] memory _permissions) internal pure returns (uint8 _representation) {
for (uint256 i; i < _permissions.length; i++) {
_representation |= uint8(1 << uint8(_permissions[i]));
}
}
/// @notice Takes an int representation of a set of permissions, and returns whether it contains the given permission
/// @param _representation The int representation
/// @param _permission The permission to check for
/// @return _hasPermission Whether the representation contains the given permission
function hasPermission(uint8 _representation, IDCAPermissionManager.Permission _permission) internal pure returns (bool _hasPermission) {
uint256 _bitMask = 1 << uint8(_permission);
_hasPermission = (_representation & _bitMask) != 0;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.7.0;
interface IGovernable {
event PendingGovernorSet(address pendingGovernor);
event PendingGovernorAccepted();
function setPendingGovernor(address _pendingGovernor) external;
function acceptPendingGovernor() external;
function governor() external view returns (address);
function pendingGovernor() external view returns (address);
function isGovernor(address _account) external view returns (bool _isGovernor);
function isPendingGovernor(address _account) external view returns (bool _isPendingGovernor);
}
abstract contract Governable is IGovernable {
address private _governor;
address private _pendingGovernor;
constructor(address __governor) {
require(__governor != address(0), 'Governable: zero address');
_governor = __governor;
}
function governor() external view override returns (address) {
return _governor;
}
function pendingGovernor() external view override returns (address) {
return _pendingGovernor;
}
function setPendingGovernor(address __pendingGovernor) external virtual override onlyGovernor {
_setPendingGovernor(__pendingGovernor);
}
function _setPendingGovernor(address __pendingGovernor) internal {
require(__pendingGovernor != address(0), 'Governable: zero address');
_pendingGovernor = __pendingGovernor;
emit PendingGovernorSet(__pendingGovernor);
}
function acceptPendingGovernor() external virtual override onlyPendingGovernor {
_acceptPendingGovernor();
}
function _acceptPendingGovernor() internal {
require(_pendingGovernor != address(0), 'Governable: no pending governor');
_governor = _pendingGovernor;
_pendingGovernor = address(0);
emit PendingGovernorAccepted();
}
function isGovernor(address _account) public view override returns (bool _isGovernor) {
return _account == _governor;
}
function isPendingGovernor(address _account) public view override returns (bool _isPendingGovernor) {
return _account == _pendingGovernor;
}
modifier onlyGovernor() {
require(isGovernor(msg.sender), 'Governable: only governor');
_;
}
modifier onlyPendingGovernor() {
require(isPendingGovernor(msg.sender), 'Governable: only pending governor');
_;
}
}
// 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/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
|
@inheritdoc IDCAPermissionManager
|
function permit(
address _spender,
uint256 _tokenId,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
if (block.timestamp > _deadline) revert ExpiredDeadline();
address _owner = ownerOf(_tokenId);
bytes32 _structHash = keccak256(abi.encode(PERMIT_TYPEHASH, _spender, _tokenId, nonces[_owner]++, _deadline));
bytes32 _hash = _hashTypedDataV4(_structHash);
address _signer = ECDSA.recover(_hash, _v, _r, _s);
if (_signer != _owner) revert InvalidSignature();
_approve(_spender, _tokenId);
}
| 441,514 |
./full_match/1/0x88d53AbA33A3ac77D86D76111b6651dEB1cD978A/sources/src/splitter/RoyaltySplitter.sol
|
Add a new shareholder to the contract account The address of the shareholder to add shares_ The number of shares owned by the shareholder/
|
function _addShareholder(address account, uint256 shares_) private {
require(
account != address(0),
"RoyaltySplitter: account is the zero address"
);
require(shares_ > 0, "RoyaltySplitter: shares are 0");
require(
_shares[account] == 0,
"RoyaltySplitter: account already has shares"
);
_shareholders.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
}
| 8,451,054 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../interfaces/IStake1Vault.sol";
import {ITOS} from "../interfaces/ITOS.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IStake1Storage.sol";
import "../libraries/LibTokenStake1.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./StakeVaultStorage.sol";
/// @title TOS Token's Vault - stores the TOS for the period of time
/// @notice A vault is associated with the set of stake contracts.
/// Stake contracts can interact with the vault to claim TOS tokens
contract Stake1Vault is StakeVaultStorage, IStake1Vault {
using SafeMath for uint256;
/// @dev event on sale-closed
event ClosedSale();
/// @dev event of according to request from(staking contract) the amount of compensation is paid to to.
/// @param from the stakeContract address that call claim
/// @param to the address that will receive the reward
/// @param amount the amount of reward
event ClaimedReward(address indexed from, address to, uint256 amount);
/// @dev constructor of Stake1Vault
constructor() {}
/// @dev receive function
receive() external payable {
revert("cannot receive Ether");
}
/// @dev Sets TOS address
/// @param _tos TOS address
function setTOS(address _tos) external override onlyOwner {
require(_tos != address(0), "Stake1Vault: input is zero");
tos = _tos;
}
/// @dev Change cap of the vault
/// @param _cap allocated reward amount
function changeCap(uint256 _cap) external override onlyOwner {
require(_cap > 0 && cap != _cap, "Stake1Vault: changeCap fails");
cap = _cap;
}
/// @dev Set Defi Address
/// @param _defiAddr DeFi related address
function setDefiAddr(address _defiAddr) external override onlyOwner {
require(
_defiAddr != address(0) && defiAddr != _defiAddr,
"Stake1Vault: _defiAddr is zero"
);
defiAddr = _defiAddr;
}
/// @dev If the vault has more money than the reward to give, the owner can withdraw the remaining amount.
/// @param _amount the amount of withdrawal
function withdrawReward(uint256 _amount) external override onlyOwner {
require(saleClosed, "Stake1Vault: didn't end sale");
uint256 rewardAmount = 0;
for (uint256 i = 0; i < stakeAddresses.length; i++) {
rewardAmount = rewardAmount
.add(stakeInfos[stakeAddresses[i]].totalRewardAmount)
.sub(stakeInfos[stakeAddresses[i]].claimRewardAmount);
}
uint256 balanceOf = IERC20(tos).balanceOf(address(this));
require(
balanceOf >= rewardAmount.add(_amount),
"Stake1Vault: insuffient"
);
require(
IERC20(tos).transfer(msg.sender, _amount),
"Stake1Vault: fail withdrawReward"
);
}
/// @dev Add stake contract
/// @param _name stakeContract's name
/// @param stakeContract stakeContract's address
/// @param periodBlocks the period that give rewards of stakeContract
function addSubVaultOfStake(
string memory _name,
address stakeContract,
uint256 periodBlocks
) external override onlyOwner {
require(
stakeContract != address(0) && cap > 0 && periodBlocks > 0,
"Stake1Vault: addStakerInVault init fails"
);
require(
block.number < stakeStartBlock,
"Stake1Vault: Already started stake"
);
require(!saleClosed, "Stake1Vault: closed sale");
require(
paytoken == IStake1Storage(stakeContract).paytoken(),
"Stake1Vault: Different paytoken"
);
LibTokenStake1.StakeInfo storage info = stakeInfos[stakeContract];
require(info.startBlock == 0, "Stake1Vault: Already added");
stakeAddresses.push(stakeContract);
uint256 _endBlock = stakeStartBlock.add(periodBlocks);
info.name = _name;
info.startBlock = stakeStartBlock;
info.endBlock = _endBlock;
if (stakeEndBlock < _endBlock) stakeEndBlock = _endBlock;
orderedEndBlocks.push(stakeEndBlock);
}
/// @dev Close the sale that can stake by user
function closeSale() external override {
require(!saleClosed, "Stake1Vault: already closed");
require(
cap > 0 &&
stakeStartBlock > 0 &&
stakeStartBlock < stakeEndBlock &&
block.number > stakeStartBlock,
"Stake1Vault: Before stakeStartBlock"
);
require(stakeAddresses.length > 0, "Stake1Vault: no stakes");
realEndBlock = stakeEndBlock;
// check balance, update balance
for (uint256 i = 0; i < stakeAddresses.length; i++) {
LibTokenStake1.StakeInfo storage stakeInfo =
stakeInfos[stakeAddresses[i]];
if (paytoken == address(0)) {
stakeInfo.balance = address(uint160(stakeAddresses[i])).balance;
} else {
uint256 balanceAmount =
IERC20(paytoken).balanceOf(stakeAddresses[i]);
stakeInfo.balance = balanceAmount;
}
if (stakeInfo.balance > 0)
realEndBlock = stakeInfos[stakeAddresses[i]].endBlock;
}
blockTotalReward = cap.div(realEndBlock.sub(stakeStartBlock));
uint256 sum = 0;
// update total
for (uint256 i = 0; i < stakeAddresses.length; i++) {
LibTokenStake1.StakeInfo storage totalcheck =
stakeInfos[stakeAddresses[i]];
uint256 total = 0;
for (uint256 j = 0; j < stakeAddresses.length; j++) {
if (
stakeInfos[stakeAddresses[j]].endBlock >=
totalcheck.endBlock
) {
total = total.add(stakeInfos[stakeAddresses[j]].balance);
}
}
if (totalcheck.endBlock > realEndBlock) {
continue;
}
stakeEndBlockTotal[totalcheck.endBlock] = total;
sum = sum.add(total);
// reward total
uint256 totalReward = 0;
for (uint256 k = i; k > 0; k--) {
if (
stakeEndBlockTotal[stakeInfos[stakeAddresses[k]].endBlock] >
0
) {
totalReward = totalReward.add(
stakeInfos[stakeAddresses[k]]
.endBlock
.sub(stakeInfos[stakeAddresses[k - 1]].endBlock)
.mul(blockTotalReward)
.mul(totalcheck.balance)
.div(
stakeEndBlockTotal[
stakeInfos[stakeAddresses[k]].endBlock
]
)
);
}
}
if (
stakeEndBlockTotal[stakeInfos[stakeAddresses[0]].endBlock] > 0
) {
totalReward = totalReward.add(
stakeInfos[stakeAddresses[0]]
.endBlock
.sub(stakeInfos[stakeAddresses[0]].startBlock)
.mul(blockTotalReward)
.mul(totalcheck.balance)
.div(
stakeEndBlockTotal[
stakeInfos[stakeAddresses[0]].endBlock
]
)
);
}
totalcheck.totalRewardAmount = totalReward;
}
saleClosed = true;
emit ClosedSale();
}
/// @dev claim function.
/// @dev sender is a staking contract.
/// @dev A function that pays the amount(_amount) to _to by the staking contract.
/// @dev A function that _to claim the amount(_amount) from the staking contract and gets the tos in the vault.
/// @param _to a user that received reward
/// @param _amount the receiving amount
/// @return true
function claim(address _to, uint256 _amount)
external
override
returns (bool)
{
require(
saleClosed && _amount > 0,
"Stake1Vault: on sale or need to end the sale"
);
uint256 tosBalance = IERC20(tos).balanceOf(address(this));
require(tosBalance >= _amount, "Stake1Vault: not enough balance");
LibTokenStake1.StakeInfo storage stakeInfo = stakeInfos[msg.sender];
require(stakeInfo.startBlock > 0, "Stake1Vault: startBlock zero");
require(
stakeInfo.totalRewardAmount > 0,
"Stake1Vault: totalRewardAmount is zero"
);
require(
stakeInfo.totalRewardAmount >=
stakeInfo.claimRewardAmount.add(_amount),
"Stake1Vault: claim amount exceeds"
);
stakeInfo.claimRewardAmount = stakeInfo.claimRewardAmount.add(_amount);
require(
IERC20(tos).transfer(_to, _amount),
"Stake1Vault: TOS transfer fail"
);
emit ClaimedReward(msg.sender, _to, _amount);
return true;
}
/// @dev Whether user(to) can receive a reward amount(_amount)
/// @param _to a staking contract.
/// @param _amount the total reward amount of stakeContract
/// @return true
function canClaim(address _to, uint256 _amount)
external
view
override
returns (bool)
{
require(saleClosed, "Stake1Vault: on sale or need to end the sale");
uint256 tosBalance = IERC20(tos).balanceOf(address(this));
require(tosBalance >= _amount, "not enough");
LibTokenStake1.StakeInfo storage stakeInfo = stakeInfos[_to];
require(stakeInfo.startBlock > 0, "Stake1Vault: startBlock is zero");
require(
stakeInfo.totalRewardAmount > 0,
"Stake1Vault: amount is wrong"
);
require(
stakeInfo.totalRewardAmount >=
stakeInfo.claimRewardAmount.add(_amount),
"Stake1Vault: amount exceeds"
);
return true;
}
/// @dev Returns Give the TOS balance stored in the vault
/// @return the balance of TOS in this vault.
function balanceTOSAvailableAmount()
external
view
override
returns (uint256)
{
return IERC20(tos).balanceOf(address(this));
}
/// @dev Give all stakeContracts's addresses in this vault
/// @return all stakeContracts's addresses
function stakeAddressesAll()
external
view
override
returns (address[] memory)
{
return stakeAddresses;
}
/// @dev Give the ordered end blocks of stakeContracts in this vault
/// @return the ordered end blocks
function orderedEndBlocksAll()
external
view
override
returns (uint256[] memory)
{
return orderedEndBlocks;
}
/// @dev Give Total reward amount of stakeContract(_account)
/// @return Total reward amount of stakeContract(_account)
function totalRewardAmount(address _account)
external
view
override
returns (uint256)
{
return stakeInfos[_account].totalRewardAmount;
}
/// @dev Give the infomation of this vault
/// @return [paytoken,defiAddr], cap, stakeType, [saleStartBlock, stakeStartBlock, stakeEndBlock], blockTotalReward, saleClosed
function infos()
external
view
override
returns (
address[2] memory,
uint256,
uint256,
uint256[3] memory,
uint256,
bool
)
{
return (
[paytoken, defiAddr],
cap,
stakeType,
[saleStartBlock, stakeStartBlock, stakeEndBlock],
blockTotalReward,
saleClosed
);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../libraries/LibTokenStake1.sol";
interface IStake1Vault {
/// @dev Sets TOS address
/// @param _tos TOS address
function setTOS(address _tos) external;
/// @dev Change cap of the vault
/// @param _cap allocated reward amount
function changeCap(uint256 _cap) external;
/// @dev Set Defi Address
/// @param _defiAddr DeFi related address
function setDefiAddr(address _defiAddr) external;
/// @dev If the vault has more money than the reward to give, the owner can withdraw the remaining amount.
/// @param _amount the amount of withdrawal
function withdrawReward(uint256 _amount) external;
/// @dev Add stake contract
/// @param _name stakeContract's name
/// @param stakeContract stakeContract's address
/// @param periodBlocks the period that give rewards of stakeContract
function addSubVaultOfStake(
string memory _name,
address stakeContract,
uint256 periodBlocks
) external;
/// @dev Close the sale that can stake by user
function closeSale() external;
/// @dev claim function.
/// @dev sender is a staking contract.
/// @dev A function that pays the amount(_amount) to _to by the staking contract.
/// @dev A function that _to claim the amount(_amount) from the staking contract and gets the TOS in the vault.
/// @param _to a user that received reward
/// @param _amount the receiving amount
/// @return true
function claim(address _to, uint256 _amount) external returns (bool);
/// @dev Whether user(to) can receive a reward amount(_amount)
/// @param _to a staking contract.
/// @param _amount the total reward amount of stakeContract
/// @return true
function canClaim(address _to, uint256 _amount)
external
view
returns (bool);
/// @dev Give the infomation of this vault
/// @return paytoken, cap, saleStartBlock, stakeStartBlock, stakeEndBlock, blockTotalReward, saleClosed
function infos()
external
view
returns (
address[2] memory,
uint256,
uint256,
uint256[3] memory,
uint256,
bool
);
/// @dev Returns Give the TOS balance stored in the vault
/// @return the balance of TOS in this vault.
function balanceTOSAvailableAmount() external view returns (uint256);
/// @dev Give Total reward amount of stakeContract(_account)
/// @return Total reward amount of stakeContract(_account)
function totalRewardAmount(address _account)
external
view
returns (uint256);
/// @dev Give all stakeContracts's addresses in this vault
/// @return all stakeContracts's addresses
function stakeAddressesAll() external view returns (address[] memory);
/// @dev Give the ordered end blocks of stakeContracts in this vault
/// @return the ordered end blocks
function orderedEndBlocksAll() external view returns (uint256[] memory);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
interface ITOS {
/// @dev Issue a token.
/// @param to who takes the issue
/// @param amount the amount to issue
function mint(address to, uint256 amount) external returns (bool);
// @dev burn a token.
/// @param from Whose tokens are burned
/// @param amount the amount to burn
function burn(address from, uint256 amount) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function nonces(address owner) external view returns (uint256);
/// @dev Authorizes the owner's token to be used by the spender as much as the value.
/// @dev The signature must have the owner's signature.
/// @param owner the token's owner
/// @param spender the account that spend owner's token
/// @param value the amount to be approve to spend
/// @param deadline the deadline that valid the owner's signature
/// @param v the owner's signature - v
/// @param r the owner's signature - r
/// @param s the owner's signature - s
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/// @dev verify the signature
/// @param owner the token's owner
/// @param spender the account that spend owner's token
/// @param value the amount to be approve to spend
/// @param deadline the deadline that valid the owner's signature
/// @param _nounce the _nounce
/// @param sigR the owner's signature - r
/// @param sigS the owner's signature - s
/// @param sigV the owner's signature - v
function verify(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint256 _nounce,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) external view returns (bool);
/// @dev the hash of Permit
/// @param owner the token's owner
/// @param spender the account that spend owner's token
/// @param value the amount to be approve to spend
/// @param deadline the deadline that valid the owner's signature
/// @param _nounce the _nounce
function hashPermit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint256 _nounce
) external view returns (bytes32);
}
// 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: Unlicense
pragma solidity ^0.7.6;
interface IStake1Storage {
/// @dev reward token : TOS
function token() external view returns (address);
/// @dev registry
function stakeRegistry() external view returns (address);
/// @dev paytoken is the token that the user stakes. ( if paytoken is ether, paytoken is address(0) )
function paytoken() external view returns (address);
/// @dev A vault that holds TOS rewards.
function vault() external view returns (address);
/// @dev the start block for sale.
function saleStartBlock() external view returns (uint256);
/// @dev the staking start block, once staking starts, users can no longer apply for staking.
function startBlock() external view returns (uint256);
/// @dev the staking end block.
function endBlock() external view returns (uint256);
//// @dev the total amount claimed
function rewardClaimedTotal() external view returns (uint256);
/// @dev the total staked amount
function totalStakedAmount() external view returns (uint256);
/// @dev total stakers
function totalStakers() external view returns (uint256);
/// @dev user's staked information
function getUserStaked(address user)
external
view
returns (
uint256 amount,
uint256 claimedBlock,
uint256 claimedAmount,
uint256 releasedBlock,
uint256 releasedAmount,
uint256 releasedTOSAmount,
bool released
);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
library LibTokenStake1 {
enum DefiStatus {
NONE,
APPROVE,
DEPOSITED,
REQUESTWITHDRAW,
REQUESTWITHDRAWALL,
WITHDRAW,
END
}
struct DefiInfo {
string name;
address router;
address ext1;
address ext2;
uint256 fee;
address routerV2;
}
struct StakeInfo {
string name;
uint256 startBlock;
uint256 endBlock;
uint256 balance;
uint256 totalRewardAmount;
uint256 claimRewardAmount;
}
struct StakedAmount {
uint256 amount;
uint256 claimedBlock;
uint256 claimedAmount;
uint256 releasedBlock;
uint256 releasedAmount;
uint256 releasedTOSAmount;
bool released;
}
struct StakedAmountForSTOS {
uint256 amount;
uint256 startBlock;
uint256 periodBlock;
uint256 rewardPerBlock;
uint256 claimedBlock;
uint256 claimedAmount;
uint256 releasedBlock;
uint256 releasedAmount;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
//import "../interfaces/IStakeVaultStorage.sol";
import "../libraries/LibTokenStake1.sol";
import "../common/AccessibleCommon.sol";
/// @title the storage of StakeVaultStorage
contract StakeVaultStorage is AccessibleCommon {
/// @dev reward token : TOS
address public tos;
/// @dev paytoken is the token that the user stakes.
address public paytoken;
/// @dev allocated amount of tos
uint256 public cap;
/// @dev the start block for sale.
uint256 public saleStartBlock;
/// @dev the staking start block
uint256 public stakeStartBlock;
/// @dev the staking end block.
uint256 public stakeEndBlock;
/// @dev the staking real end block.
uint256 public realEndBlock;
/// @dev reward amount per block
uint256 public blockTotalReward;
/// @dev sale closed flag
bool public saleClosed;
/// @dev Operation type of staking amount
uint256 public stakeType;
/// @dev External contract address used when operating the staking amount
address public defiAddr;
/// @dev a list of stakeContracts maintained by the vault
address[] public stakeAddresses;
/// @dev the information of the stake contract
mapping(address => LibTokenStake1.StakeInfo) public stakeInfos;
/// @dev the end blocks of the stake contracts, which must be in ascending order
uint256[] public orderedEndBlocks;
/// @dev the total staked amount stored at orderedEndBlock’s end block time
mapping(uint256 => uint256) public stakeEndBlockTotal;
uint256 private _lock;
/// @dev flag for pause proxy
bool public pauseProxy;
///@dev for migrate L2
bool public migratedL2;
modifier lock() {
require(_lock == 0, "Stake1Vault: LOCKED");
_lock = 1;
_;
_lock = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./AccessRoleCommon.sol";
contract AccessibleCommon is AccessRoleCommon, AccessControl {
modifier onlyOwner() {
require(isAdmin(msg.sender), "Accessible: Caller is not an admin");
_;
}
/// @dev add admin
/// @param account address to add
function addAdmin(address account) public virtual onlyOwner {
grantRole(ADMIN_ROLE, account);
}
/// @dev remove admin
/// @param account address to remove
function removeAdmin(address account) public virtual onlyOwner {
renounceRole(ADMIN_ROLE, account);
}
/// @dev transfer admin
/// @param newAdmin new admin address
function transferAdmin(address newAdmin) external virtual onlyOwner {
require(newAdmin != address(0), "Accessible: zero address");
require(msg.sender != newAdmin, "Accessible: same admin");
grantRole(ADMIN_ROLE, newAdmin);
renounceRole(ADMIN_ROLE, msg.sender);
}
/// @dev whether admin
/// @param account address to check
function isAdmin(address account) public view virtual returns (bool) {
return hasRole(ADMIN_ROLE, account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
contract AccessRoleCommon {
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
bytes32 public constant MINTER_ROLE = keccak256("MINTER");
bytes32 public constant BURNER_ROLE = keccak256("BURNER");
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: 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;
}
}
|
Set Defi Address _defiAddr DeFi related address
|
function setDefiAddr(address _defiAddr) external override onlyOwner {
require(
_defiAddr != address(0) && defiAddr != _defiAddr,
"Stake1Vault: _defiAddr is zero"
);
defiAddr = _defiAddr;
}
| 9,825,089 |
./partial_match/1/0x336e5Aaf2Cb26f1EC2f17f9D147b7c5657ef06f2/sources/Kawaii.sol
|
See {IERC20-approve}. NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on `transferFrom`. This is semantically equivalent to an infinite approval. Requirements: - `spender` cannot be the zero address./
|
function approve(address spender, uint256 amount)
external
virtual
override
returns (bool)
{
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
| 2,599,678 |
/*
-----------------------------------------------------------------
FILE HEADER
-----------------------------------------------------------------
file: Havven.sol
version: 1.0
authors: Anton Jurisevic
Dominic Romanowski
Mike Spain
date: 2018-02-05
checked: Mike Spain
approved: Samuel Brooks
repo: https://github.com/Havven/havven
commit: 34e66009b98aa18976226c139270970d105045e3
-----------------------------------------------------------------
*/
pragma solidity ^0.4.21;
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
A contract with a limited setup period. Any function modified
with the setup modifier will cease to work after the
conclusion of the configurable-length post-construction setup period.
-----------------------------------------------------------------
*/
contract LimitedSetup {
uint constructionTime;
uint setupDuration;
function LimitedSetup(uint _setupDuration)
public
{
constructionTime = now;
setupDuration = _setupDuration;
}
modifier setupFunction
{
require(now < constructionTime + setupDuration);
_;
}
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
An Owned contract, to be inherited by other contracts.
Requires its owner to be explicitly set in the constructor.
Provides an onlyOwner access modifier.
To change owner, the current owner must nominate the next owner,
who then has to accept the nomination. The nomination can be
cancelled before it is accepted by the new owner by having the
previous owner change the nomination (setting it to 0).
-----------------------------------------------------------------
*/
contract Owned {
address public owner;
address public nominatedOwner;
function Owned(address _owner)
public
{
owner = _owner;
}
function nominateOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner);
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner);
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
A proxy contract that, if it does not recognise the function
being called on it, passes all value and call data to an
underlying target contract.
-----------------------------------------------------------------
*/
contract Proxy is Owned {
Proxyable target;
function Proxy(Proxyable _target, address _owner)
Owned(_owner)
public
{
target = _target;
emit TargetChanged(_target);
}
function _setTarget(address _target)
external
onlyOwner
{
require(_target != address(0));
target = Proxyable(_target);
emit TargetChanged(_target);
}
function ()
public
payable
{
target.setMessageSender(msg.sender);
assembly {
// Copy call data into free memory region.
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
// Forward all gas, ether, and data to the target contract.
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
// Revert if the call failed, otherwise return the result.
if iszero(result) { revert(free_ptr, calldatasize) }
return(free_ptr, returndatasize)
}
}
event TargetChanged(address targetAddress);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
This contract contains the Proxyable interface.
Any contract the proxy wraps must implement this, in order
for the proxy to be able to pass msg.sender into the underlying
contract as the state parameter, messageSender.
-----------------------------------------------------------------
*/
contract Proxyable is Owned {
// the proxy this contract exists behind.
Proxy public proxy;
// The caller of the proxy, passed through to this contract.
// Note that every function using this member must apply the onlyProxy or
// optionalProxy modifiers, otherwise their invocations can use stale values.
address messageSender;
function Proxyable(address _owner)
Owned(_owner)
public { }
function setProxy(Proxy _proxy)
external
onlyOwner
{
proxy = _proxy;
emit ProxyChanged(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy
{
require(Proxy(msg.sender) == proxy);
_;
}
modifier onlyOwner_Proxy
{
require(messageSender == owner);
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
// Combine the optionalProxy and onlyOwner_Proxy modifiers.
// This is slightly cheaper and safer, since there is an ordering requirement.
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner);
_;
}
event ProxyChanged(address proxyAddress);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
A fixed point decimal library that provides basic mathematical
operations, and checks for unsafe arguments, for example that
would lead to overflows.
Exceptions are thrown whenever those unsafe operations
occur.
-----------------------------------------------------------------
*/
contract SafeDecimalMath {
// Number of decimal places in the representation.
uint8 public constant decimals = 18;
// The number representing 1.0.
uint public constant UNIT = 10 ** uint(decimals);
/* True iff adding x and y will not overflow. */
function addIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return x + y >= y;
}
/* Return the result of adding x and y, throwing an exception in case of overflow. */
function safeAdd(uint x, uint y)
pure
internal
returns (uint)
{
require(x + y >= y);
return x + y;
}
/* True iff subtracting y from x will not overflow in the negative direction. */
function subIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y <= x;
}
/* Return the result of subtracting y from x, throwing an exception in case of overflow. */
function safeSub(uint x, uint y)
pure
internal
returns (uint)
{
require(y <= x);
return x - y;
}
/* True iff multiplying x and y would not overflow. */
function mulIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
if (x == 0) {
return true;
}
return (x * y) / x == y;
}
/* Return the result of multiplying x and y, throwing an exception in case of overflow.*/
function safeMul(uint x, uint y)
pure
internal
returns (uint)
{
if (x == 0) {
return 0;
}
uint p = x * y;
require(p / x == y);
return p;
}
/* Return the result of multiplying x and y, interpreting the operands as fixed-point
* demicimals. Throws an exception in case of overflow. A unit factor is divided out
* after the product of x and y is evaluated, so that product must be less than 2**256.
*
* Incidentally, the internal division always rounds down: we could have rounded to the nearest integer,
* but then we would be spending a significant fraction of a cent (of order a microether
* at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands
* contain small enough fractional components. It would also marginally diminish the
* domain this function is defined upon.
*/
function safeMul_dec(uint x, uint y)
pure
internal
returns (uint)
{
// Divide by UNIT to remove the extra factor introduced by the product.
// UNIT be 0.
return safeMul(x, y) / UNIT;
}
/* True iff the denominator of x/y is nonzero. */
function divIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y != 0;
}
/* Return the result of dividing x by y, throwing an exception if the divisor is zero. */
function safeDiv(uint x, uint y)
pure
internal
returns (uint)
{
// Although a 0 denominator already throws an exception,
// it is equivalent to a THROW operation, which consumes all gas.
// A require statement emits REVERT instead, which remits remaining gas.
require(y != 0);
return x / y;
}
/* Return the result of dividing x by y, interpreting the operands as fixed point decimal numbers.
* Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT.
* Internal rounding is downward: a similar caveat holds as with safeDecMul().*/
function safeDiv_dec(uint x, uint y)
pure
internal
returns (uint)
{
// Reintroduce the UNIT factor that will be divided out by y.
return safeDiv(safeMul(x, UNIT), y);
}
/* Convert an unsigned integer to a unsigned fixed-point decimal.
* Throw an exception if the result would be out of range. */
function intToDec(uint i)
pure
internal
returns (uint)
{
return safeMul(i, UNIT);
}
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
This court provides the nomin contract with a confiscation
facility, if enough havven owners vote to confiscate a target
account's nomins.
This is designed to provide a mechanism to respond to abusive
contracts such as nomin wrappers, which would allow users to
trade wrapped nomins without accruing fees on those transactions.
In order to prevent tyranny, an account may only be frozen if
users controlling at least 30% of the value of havvens participate,
and a two thirds majority is attained in that vote.
In order to prevent tyranny of the majority or mob justice,
confiscation motions are only approved if the havven foundation
approves the result.
This latter requirement may be lifted in future versions.
The foundation, or any user with a sufficient havven balance may bring a
confiscation motion.
A motion lasts for a default period of one week, with a further confirmation
period in which the foundation approves the result.
The latter period may conclude early upon the foundation's decision to either
veto or approve the mooted confiscation motion.
If the confirmation period elapses without the foundation making a decision,
the motion fails.
The weight of a havven holder's vote is determined by examining their
average balance over the last completed fee period prior to the
beginning of a given motion.
Thus, since a fee period can roll over in the middle of a motion, we must
also track a user's average balance of the last two periods.
This system is designed such that it cannot be attacked by users transferring
funds between themselves, while also not requiring them to lock their havvens
for the duration of the vote. This is possible since any transfer that increases
the average balance in one account will be reflected by an equivalent reduction
in the voting weight in the other.
At present a user may cast a vote only for one motion at a time,
but may cancel their vote at any time except during the confirmation period,
when the vote tallies must remain static until the matter has been settled.
A motion to confiscate the balance of a given address composes
a state machine built of the following states:
Waiting:
- A user with standing brings a motion:
If the target address is not frozen;
initialise vote tallies to 0;
transition to the Voting state.
- An account cancels a previous residual vote:
remain in the Waiting state.
Voting:
- The foundation vetoes the in-progress motion:
transition to the Waiting state.
- The voting period elapses:
transition to the Confirmation state.
- An account votes (for or against the motion):
its weight is added to the appropriate tally;
remain in the Voting state.
- An account cancels its previous vote:
its weight is deducted from the appropriate tally (if any);
remain in the Voting state.
Confirmation:
- The foundation vetoes the completed motion:
transition to the Waiting state.
- The foundation approves confiscation of the target account:
freeze the target account, transfer its nomin balance to the fee pool;
transition to the Waiting state.
- The confirmation period elapses:
transition to the Waiting state.
User votes are not automatically cancelled upon the conclusion of a motion.
Therefore, after a motion comes to a conclusion, if a user wishes to vote
in another motion, they must manually cancel their vote in order to do so.
This procedure is designed to be relatively simple.
There are some things that can be added to enhance the functionality
at the expense of simplicity and efficiency:
- Democratic unfreezing of nomin accounts (induces multiple categories of vote)
- Configurable per-vote durations;
- Vote standing denominated in a fiat quantity rather than a quantity of havvens;
- Confiscate from multiple addresses in a single vote;
We might consider updating the contract with any of these features at a later date if necessary.
-----------------------------------------------------------------
*/
contract Court is Owned, SafeDecimalMath {
/* ========== STATE VARIABLES ========== */
// The addresses of the token contracts this confiscation court interacts with.
Havven public havven;
EtherNomin public nomin;
// The minimum havven balance required to be considered to have standing
// to begin confiscation proceedings.
uint public minStandingBalance = 100 * UNIT;
// The voting period lasts for this duration,
// and if set, must fall within the given bounds.
uint public votingPeriod = 1 weeks;
uint constant MIN_VOTING_PERIOD = 3 days;
uint constant MAX_VOTING_PERIOD = 4 weeks;
// Duration of the period during which the foundation may confirm
// or veto a motion that has concluded.
// If set, the confirmation duration must fall within the given bounds.
uint public confirmationPeriod = 1 weeks;
uint constant MIN_CONFIRMATION_PERIOD = 1 days;
uint constant MAX_CONFIRMATION_PERIOD = 2 weeks;
// No fewer than this fraction of havvens must participate in a motion
// in order for a quorum to be reached.
// The participation fraction required may be set no lower than 10%.
uint public requiredParticipation = 3 * UNIT / 10;
uint constant MIN_REQUIRED_PARTICIPATION = UNIT / 10;
// At least this fraction of participating votes must be in favour of
// confiscation for the motion to pass.
// The required majority may be no lower than 50%.
uint public requiredMajority = (2 * UNIT) / 3;
uint constant MIN_REQUIRED_MAJORITY = UNIT / 2;
// The next ID to use for opening a motion.
uint nextMotionID = 1;
// Mapping from motion IDs to target addresses.
mapping(uint => address) public motionTarget;
// The ID a motion on an address is currently operating at.
// Zero if no such motion is running.
mapping(address => uint) public targetMotionID;
// The timestamp at which a motion began. This is used to determine
// whether a motion is: running, in the confirmation period,
// or has concluded.
// A motion runs from its start time t until (t + votingPeriod),
// and then the confirmation period terminates no later than
// (t + votingPeriod + confirmationPeriod).
mapping(uint => uint) public motionStartTime;
// The tallies for and against confiscation of a given balance.
// These are set to zero at the start of a motion, and also on conclusion,
// just to keep the state clean.
mapping(uint => uint) public votesFor;
mapping(uint => uint) public votesAgainst;
// The last/penultimate average balance of a user at the time they voted
// in a particular motion.
// If we did not save this information then we would have to
// disallow transfers into an account lest it cancel a vote
// with greater weight than that with which it originally voted,
// and the fee period rolled over in between.
mapping(address => mapping(uint => uint)) voteWeight;
// The possible vote types.
// Abstention: not participating in a motion; This is the default value.
// Yea: voting in favour of a motion.
// Nay: voting against a motion.
enum Vote {Abstention, Yea, Nay}
// A given account's vote in some confiscation motion.
// This requires the default value of the Vote enum to correspond to an abstention.
mapping(address => mapping(uint => Vote)) public vote;
/* ========== CONSTRUCTOR ========== */
function Court(Havven _havven, EtherNomin _nomin, address _owner)
Owned(_owner)
public
{
havven = _havven;
nomin = _nomin;
}
/* ========== SETTERS ========== */
function setMinStandingBalance(uint balance)
external
onlyOwner
{
// No requirement on the standing threshold here;
// the foundation can set this value such that
// anyone or no one can actually start a motion.
minStandingBalance = balance;
}
function setVotingPeriod(uint duration)
external
onlyOwner
{
require(MIN_VOTING_PERIOD <= duration &&
duration <= MAX_VOTING_PERIOD);
// Require that the voting period is no longer than a single fee period,
// So that a single vote can span at most two fee periods.
require(duration <= havven.targetFeePeriodDurationSeconds());
votingPeriod = duration;
}
function setConfirmationPeriod(uint duration)
external
onlyOwner
{
require(MIN_CONFIRMATION_PERIOD <= duration &&
duration <= MAX_CONFIRMATION_PERIOD);
confirmationPeriod = duration;
}
function setRequiredParticipation(uint fraction)
external
onlyOwner
{
require(MIN_REQUIRED_PARTICIPATION <= fraction);
requiredParticipation = fraction;
}
function setRequiredMajority(uint fraction)
external
onlyOwner
{
require(MIN_REQUIRED_MAJORITY <= fraction);
requiredMajority = fraction;
}
/* ========== VIEW FUNCTIONS ========== */
/* There is a motion in progress on the specified
* account, and votes are being accepted in that motion. */
function motionVoting(uint motionID)
public
view
returns (bool)
{
// No need to check (startTime < now) as there is no way
// to set future start times for votes.
// These values are timestamps, they will not overflow
// as they can only ever be initialised to relatively small values.
return now < motionStartTime[motionID] + votingPeriod;
}
/* A vote on the target account has concluded, but the motion
* has not yet been approved, vetoed, or closed. */
function motionConfirming(uint motionID)
public
view
returns (bool)
{
// These values are timestamps, they will not overflow
// as they can only ever be initialised to relatively small values.
uint startTime = motionStartTime[motionID];
return startTime + votingPeriod <= now &&
now < startTime + votingPeriod + confirmationPeriod;
}
/* A vote motion either not begun, or it has completely terminated. */
function motionWaiting(uint motionID)
public
view
returns (bool)
{
// These values are timestamps, they will not overflow
// as they can only ever be initialised to relatively small values.
return motionStartTime[motionID] + votingPeriod + confirmationPeriod <= now;
}
/* If the motion was to terminate at this instant, it would pass.
* That is: there was sufficient participation and a sizeable enough majority. */
function motionPasses(uint motionID)
public
view
returns (bool)
{
uint yeas = votesFor[motionID];
uint nays = votesAgainst[motionID];
uint totalVotes = safeAdd(yeas, nays);
if (totalVotes == 0) {
return false;
}
uint participation = safeDiv_dec(totalVotes, havven.totalSupply());
uint fractionInFavour = safeDiv_dec(yeas, totalVotes);
// We require the result to be strictly greater than the requirement
// to enforce a majority being "50% + 1", and so on.
return participation > requiredParticipation &&
fractionInFavour > requiredMajority;
}
function hasVoted(address account, uint motionID)
public
view
returns (bool)
{
return vote[account][motionID] != Vote.Abstention;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Begin a motion to confiscate the funds in a given nomin account.
* Only the foundation, or accounts with sufficient havven balances
* may elect to start such a motion.
* Returns the ID of the motion that was begun. */
function beginMotion(address target)
external
returns (uint)
{
// A confiscation motion must be mooted by someone with standing.
require((havven.balanceOf(msg.sender) >= minStandingBalance) ||
msg.sender == owner);
// Require that the voting period is longer than a single fee period,
// So that a single vote can span at most two fee periods.
require(votingPeriod <= havven.targetFeePeriodDurationSeconds());
// There must be no confiscation motion already running for this account.
require(targetMotionID[target] == 0);
// Disallow votes on accounts that have previously been frozen.
require(!nomin.frozen(target));
uint motionID = nextMotionID++;
motionTarget[motionID] = target;
targetMotionID[target] = motionID;
motionStartTime[motionID] = now;
emit MotionBegun(msg.sender, msg.sender, target, target, motionID, motionID);
return motionID;
}
/* Shared vote setup function between voteFor and voteAgainst.
* Returns the voter's vote weight. */
function setupVote(uint motionID)
internal
returns (uint)
{
// There must be an active vote for this target running.
// Vote totals must only change during the voting phase.
require(motionVoting(motionID));
// The voter must not have an active vote this motion.
require(!hasVoted(msg.sender, motionID));
// The voter may not cast votes on themselves.
require(msg.sender != motionTarget[motionID]);
// Ensure the voter's vote weight is current.
havven.recomputeAccountLastAverageBalance(msg.sender);
uint weight;
// We use a fee period guaranteed to have terminated before
// the start of the vote. Select the right period if
// a fee period rolls over in the middle of the vote.
if (motionStartTime[motionID] < havven.feePeriodStartTime()) {
weight = havven.penultimateAverageBalance(msg.sender);
} else {
weight = havven.lastAverageBalance(msg.sender);
}
// Users must have a nonzero voting weight to vote.
require(weight > 0);
voteWeight[msg.sender][motionID] = weight;
return weight;
}
/* The sender casts a vote in favour of confiscation of the
* target account's nomin balance. */
function voteFor(uint motionID)
external
{
uint weight = setupVote(motionID);
vote[msg.sender][motionID] = Vote.Yea;
votesFor[motionID] = safeAdd(votesFor[motionID], weight);
emit VotedFor(msg.sender, msg.sender, motionID, motionID, weight);
}
/* The sender casts a vote against confiscation of the
* target account's nomin balance. */
function voteAgainst(uint motionID)
external
{
uint weight = setupVote(motionID);
vote[msg.sender][motionID] = Vote.Nay;
votesAgainst[motionID] = safeAdd(votesAgainst[motionID], weight);
emit VotedAgainst(msg.sender, msg.sender, motionID, motionID, weight);
}
/* Cancel an existing vote by the sender on a motion
* to confiscate the target balance. */
function cancelVote(uint motionID)
external
{
// An account may cancel its vote either before the confirmation phase
// when the motion is still open, or after the confirmation phase,
// when the motion has concluded.
// But the totals must not change during the confirmation phase itself.
require(!motionConfirming(motionID));
Vote senderVote = vote[msg.sender][motionID];
// If the sender has not voted then there is no need to update anything.
require(senderVote != Vote.Abstention);
// If we are not voting, there is no reason to update the vote totals.
if (motionVoting(motionID)) {
if (senderVote == Vote.Yea) {
votesFor[motionID] = safeSub(votesFor[motionID], voteWeight[msg.sender][motionID]);
} else {
// Since we already ensured that the vote is not an abstention,
// the only option remaining is Vote.Nay.
votesAgainst[motionID] = safeSub(votesAgainst[motionID], voteWeight[msg.sender][motionID]);
}
// A cancelled vote is only meaningful if a vote is running
emit VoteCancelled(msg.sender, msg.sender, motionID, motionID);
}
delete voteWeight[msg.sender][motionID];
delete vote[msg.sender][motionID];
}
function _closeMotion(uint motionID)
internal
{
delete targetMotionID[motionTarget[motionID]];
delete motionTarget[motionID];
delete motionStartTime[motionID];
delete votesFor[motionID];
delete votesAgainst[motionID];
emit MotionClosed(motionID, motionID);
}
/* If a motion has concluded, or if it lasted its full duration but not passed,
* then anyone may close it. */
function closeMotion(uint motionID)
external
{
require((motionConfirming(motionID) && !motionPasses(motionID)) || motionWaiting(motionID));
_closeMotion(motionID);
}
/* The foundation may only confiscate a balance during the confirmation
* period after a motion has passed. */
function approveMotion(uint motionID)
external
onlyOwner
{
require(motionConfirming(motionID) && motionPasses(motionID));
address target = motionTarget[motionID];
nomin.confiscateBalance(target);
_closeMotion(motionID);
emit MotionApproved(motionID, motionID);
}
/* The foundation may veto a motion at any time. */
function vetoMotion(uint motionID)
external
onlyOwner
{
require(!motionWaiting(motionID));
_closeMotion(motionID);
emit MotionVetoed(motionID, motionID);
}
/* ========== EVENTS ========== */
event MotionBegun(address initiator, address indexed initiatorIndex, address target, address indexed targetIndex, uint motionID, uint indexed motionIDIndex);
event VotedFor(address voter, address indexed voterIndex, uint motionID, uint indexed motionIDIndex, uint weight);
event VotedAgainst(address voter, address indexed voterIndex, uint motionID, uint indexed motionIDIndex, uint weight);
event VoteCancelled(address voter, address indexed voterIndex, uint motionID, uint indexed motionIDIndex);
event MotionClosed(uint motionID, uint indexed motionIDIndex);
event MotionVetoed(uint motionID, uint indexed motionIDIndex);
event MotionApproved(uint motionID, uint indexed motionIDIndex);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
A token which also has a configurable fee rate
charged on its transfers. This is designed to be overridden in
order to produce an ERC20-compliant token.
These fees accrue into a pool, from which a nominated authority
may withdraw.
This contract utilises a state for upgradability purposes.
It relies on being called underneath a proxy contract, as
included in Proxy.sol.
-----------------------------------------------------------------
*/
contract ExternStateProxyFeeToken is Proxyable, SafeDecimalMath {
/* ========== STATE VARIABLES ========== */
// Stores balances and allowances.
TokenState public state;
// Other ERC20 fields
string public name;
string public symbol;
uint public totalSupply;
// A percentage fee charged on each transfer.
uint public transferFeeRate;
// Fee may not exceed 10%.
uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10;
// The address with the authority to distribute fees.
address public feeAuthority;
/* ========== CONSTRUCTOR ========== */
function ExternStateProxyFeeToken(string _name, string _symbol,
uint _transferFeeRate, address _feeAuthority,
TokenState _state, address _owner)
Proxyable(_owner)
public
{
if (_state == TokenState(0)) {
state = new TokenState(_owner, address(this));
} else {
state = _state;
}
name = _name;
symbol = _symbol;
transferFeeRate = _transferFeeRate;
feeAuthority = _feeAuthority;
}
/* ========== SETTERS ========== */
function setTransferFeeRate(uint _transferFeeRate)
external
optionalProxy_onlyOwner
{
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE);
transferFeeRate = _transferFeeRate;
emit TransferFeeRateUpdated(_transferFeeRate);
}
function setFeeAuthority(address _feeAuthority)
external
optionalProxy_onlyOwner
{
feeAuthority = _feeAuthority;
emit FeeAuthorityUpdated(_feeAuthority);
}
function setState(TokenState _state)
external
optionalProxy_onlyOwner
{
state = _state;
emit StateUpdated(_state);
}
/* ========== VIEWS ========== */
function balanceOf(address account)
public
view
returns (uint)
{
return state.balanceOf(account);
}
function allowance(address from, address to)
public
view
returns (uint)
{
return state.allowance(from, to);
}
// Return the fee charged on top in order to transfer _value worth of tokens.
function transferFeeIncurred(uint value)
public
view
returns (uint)
{
return safeMul_dec(value, transferFeeRate);
// Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees.
// This is on the basis that transfers less than this value will result in a nil fee.
// Probably too insignificant to worry about, but the following code will achieve it.
// if (fee == 0 && transferFeeRate != 0) {
// return _value;
// }
// return fee;
}
// The value that you would need to send so that the recipient receives
// a specified value.
function transferPlusFee(uint value)
external
view
returns (uint)
{
return safeAdd(value, transferFeeIncurred(value));
}
// The quantity to send in order that the sender spends a certain value of tokens.
function priceToSpend(uint value)
external
view
returns (uint)
{
return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate));
}
// The balance of the nomin contract itself is the fee pool.
// Collected fees sit here until they are distributed.
function feePool()
external
view
returns (uint)
{
return state.balanceOf(address(this));
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Whatever calls this should have either the optionalProxy or onlyProxy modifier,
* and pass in messageSender. */
function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
require(to != address(0));
// The fee is deducted from the sender's balance, in addition to
// the transferred quantity.
uint fee = transferFeeIncurred(value);
uint totalCharge = safeAdd(value, fee);
// Insufficient balance will be handled by the safe subtraction.
state.setBalanceOf(sender, safeSub(state.balanceOf(sender), totalCharge));
state.setBalanceOf(to, safeAdd(state.balanceOf(to), value));
state.setBalanceOf(address(this), safeAdd(state.balanceOf(address(this)), fee));
emit Transfer(sender, to, value);
emit TransferFeePaid(sender, fee);
emit Transfer(sender, address(this), fee);
return true;
}
/* Whatever calls this should have either the optionalProxy or onlyProxy modifier,
* and pass in messageSender. */
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
require(to != address(0));
// The fee is deducted from the sender's balance, in addition to
// the transferred quantity.
uint fee = transferFeeIncurred(value);
uint totalCharge = safeAdd(value, fee);
// Insufficient balance will be handled by the safe subtraction.
state.setBalanceOf(from, safeSub(state.balanceOf(from), totalCharge));
state.setAllowance(from, sender, safeSub(state.allowance(from, sender), totalCharge));
state.setBalanceOf(to, safeAdd(state.balanceOf(to), value));
state.setBalanceOf(address(this), safeAdd(state.balanceOf(address(this)), fee));
emit Transfer(from, to, value);
emit TransferFeePaid(sender, fee);
emit Transfer(from, address(this), fee);
return true;
}
function approve(address spender, uint value)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
state.setAllowance(sender, spender, value);
emit Approval(sender, spender, value);
return true;
}
/* Withdraw tokens from the fee pool into a given account. */
function withdrawFee(address account, uint value)
external
returns (bool)
{
require(msg.sender == feeAuthority && account != address(0));
// 0-value withdrawals do nothing.
if (value == 0) {
return false;
}
// Safe subtraction ensures an exception is thrown if the balance is insufficient.
state.setBalanceOf(address(this), safeSub(state.balanceOf(address(this)), value));
state.setBalanceOf(account, safeAdd(state.balanceOf(account), value));
emit FeesWithdrawn(account, account, value);
emit Transfer(address(this), account, value);
return true;
}
/* Donate tokens from the sender's balance into the fee pool. */
function donateToFeePool(uint n)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
// Empty donations are disallowed.
uint balance = state.balanceOf(sender);
require(balance != 0);
// safeSub ensures the donor has sufficient balance.
state.setBalanceOf(sender, safeSub(balance, n));
state.setBalanceOf(address(this), safeAdd(state.balanceOf(address(this)), n));
emit FeesDonated(sender, sender, n);
emit Transfer(sender, address(this), n);
return true;
}
/* ========== EVENTS ========== */
event Transfer(address indexed from, address indexed to, uint value);
event TransferFeePaid(address indexed account, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event TransferFeeRateUpdated(uint newFeeRate);
event FeeAuthorityUpdated(address feeAuthority);
event StateUpdated(address newState);
event FeesWithdrawn(address account, address indexed accountIndex, uint value);
event FeesDonated(address donor, address indexed donorIndex, uint value);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
Ether-backed nomin stablecoin contract.
This contract issues nomins, which are tokens worth 1 USD each. They are backed
by a pool of ether collateral, so that if a user has nomins, they may
redeem them for ether from the pool, or if they want to obtain nomins,
they may pay ether into the pool in order to do so.
The supply of nomins that may be in circulation at any time is limited.
The contract owner may increase this quantity, but only if they provide
ether to back it. The backing the owner provides at issuance must
keep each nomin at least twice overcollateralised.
The owner may also destroy nomins in the pool, which is potential avenue
by which to maintain healthy collateralisation levels, as it reduces
supply without withdrawing ether collateral.
A configurable fee is charged on nomin transfers and deposited
into a common pot, which havven holders may withdraw from once per
fee period.
Ether price is continually updated by an external oracle, and the value
of the backing is computed on this basis. To ensure the integrity of
this system, if the contract's price has not been updated recently enough,
it will temporarily disable itself until it receives more price information.
The contract owner may at any time initiate contract liquidation.
During the liquidation period, most contract functions will be deactivated.
No new nomins may be issued or bought, but users may sell nomins back
to the system.
If the system's collateral falls below a specified level, then anyone
may initiate liquidation.
After the liquidation period has elapsed, which is initially 90 days,
the owner may destroy the contract, transferring any remaining collateral
to a nominated beneficiary address.
This liquidation period may be extended up to a maximum of 180 days.
If the contract is recollateralised, the owner may terminate liquidation.
-----------------------------------------------------------------
*/
contract EtherNomin is ExternStateProxyFeeToken {
/* ========== STATE VARIABLES ========== */
// The oracle provides price information to this contract.
// It may only call the updatePrice() function.
address public oracle;
// The address of the contract which manages confiscation votes.
Court public court;
// Foundation wallet for funds to go to post liquidation.
address public beneficiary;
// Nomins in the pool ready to be sold.
uint public nominPool;
// Impose a 50 basis-point fee for buying from and selling to the nomin pool.
uint public poolFeeRate = UNIT / 200;
// The minimum purchasable quantity of nomins is 1 cent.
uint constant MINIMUM_PURCHASE = UNIT / 100;
// When issuing, nomins must be overcollateralised by this ratio.
uint constant MINIMUM_ISSUANCE_RATIO = 2 * UNIT;
// If the collateralisation ratio of the contract falls below this level,
// immediately begin liquidation.
uint constant AUTO_LIQUIDATION_RATIO = UNIT;
// The liquidation period is the duration that must pass before the liquidation period is complete.
// It can be extended up to a given duration.
uint constant DEFAULT_LIQUIDATION_PERIOD = 90 days;
uint constant MAX_LIQUIDATION_PERIOD = 180 days;
uint public liquidationPeriod = DEFAULT_LIQUIDATION_PERIOD;
// The timestamp when liquidation was activated. We initialise this to
// uint max, so that we know that we are under liquidation if the
// liquidation timestamp is in the past.
uint public liquidationTimestamp = ~uint(0);
// Ether price from oracle (fiat per ether).
uint public etherPrice;
// Last time the price was updated.
uint public lastPriceUpdate;
// The period it takes for the price to be considered stale.
// If the price is stale, functions that require the price are disabled.
uint public stalePeriod = 2 days;
// Accounts which have lost the privilege to transact in nomins.
mapping(address => bool) public frozen;
/* ========== CONSTRUCTOR ========== */
function EtherNomin(address _havven, address _oracle,
address _beneficiary,
uint initialEtherPrice,
address _owner, TokenState initialState)
ExternStateProxyFeeToken("Ether-Backed USD Nomins", "eUSD",
15 * UNIT / 10000, // nomin transfers incur a 15 bp fee
_havven, // the havven contract is the fee authority
initialState,
_owner)
public
{
oracle = _oracle;
beneficiary = _beneficiary;
etherPrice = initialEtherPrice;
lastPriceUpdate = now;
emit PriceUpdated(etherPrice);
// It should not be possible to transfer to the nomin contract itself.
frozen[this] = true;
}
/* ========== SETTERS ========== */
function setOracle(address _oracle)
external
optionalProxy_onlyOwner
{
oracle = _oracle;
emit OracleUpdated(_oracle);
}
function setCourt(Court _court)
external
optionalProxy_onlyOwner
{
court = _court;
emit CourtUpdated(_court);
}
function setBeneficiary(address _beneficiary)
external
optionalProxy_onlyOwner
{
beneficiary = _beneficiary;
emit BeneficiaryUpdated(_beneficiary);
}
function setPoolFeeRate(uint _poolFeeRate)
external
optionalProxy_onlyOwner
{
require(_poolFeeRate <= UNIT);
poolFeeRate = _poolFeeRate;
emit PoolFeeRateUpdated(_poolFeeRate);
}
function setStalePeriod(uint _stalePeriod)
external
optionalProxy_onlyOwner
{
stalePeriod = _stalePeriod;
emit StalePeriodUpdated(_stalePeriod);
}
/* ========== VIEW FUNCTIONS ========== */
/* Return the equivalent fiat value of the given quantity
* of ether at the current price.
* Reverts if the price is stale. */
function fiatValue(uint eth)
public
view
priceNotStale
returns (uint)
{
return safeMul_dec(eth, etherPrice);
}
/* Return the current fiat value of the contract's balance.
* Reverts if the price is stale. */
function fiatBalance()
public
view
returns (uint)
{
// Price staleness check occurs inside the call to fiatValue.
return fiatValue(address(this).balance);
}
/* Return the equivalent ether value of the given quantity
* of fiat at the current price.
* Reverts if the price is stale. */
function etherValue(uint fiat)
public
view
priceNotStale
returns (uint)
{
return safeDiv_dec(fiat, etherPrice);
}
/* The same as etherValue(), but without the stale price check. */
function etherValueAllowStale(uint fiat)
internal
view
returns (uint)
{
return safeDiv_dec(fiat, etherPrice);
}
/* Return the units of fiat per nomin in the supply.
* Reverts if the price is stale. */
function collateralisationRatio()
public
view
returns (uint)
{
return safeDiv_dec(fiatBalance(), _nominCap());
}
/* Return the maximum number of extant nomins,
* equal to the nomin pool plus total (circulating) supply. */
function _nominCap()
internal
view
returns (uint)
{
return safeAdd(nominPool, totalSupply);
}
/* Return the fee charged on a purchase or sale of n nomins. */
function poolFeeIncurred(uint n)
public
view
returns (uint)
{
return safeMul_dec(n, poolFeeRate);
}
/* Return the fiat cost (including fee) of purchasing n nomins.
* Nomins are purchased for $1, plus the fee. */
function purchaseCostFiat(uint n)
public
view
returns (uint)
{
return safeAdd(n, poolFeeIncurred(n));
}
/* Return the ether cost (including fee) of purchasing n nomins.
* Reverts if the price is stale. */
function purchaseCostEther(uint n)
public
view
returns (uint)
{
// Price staleness check occurs inside the call to etherValue.
return etherValue(purchaseCostFiat(n));
}
/* Return the fiat proceeds (less the fee) of selling n nomins.
* Nomins are sold for $1, minus the fee. */
function saleProceedsFiat(uint n)
public
view
returns (uint)
{
return safeSub(n, poolFeeIncurred(n));
}
/* Return the ether proceeds (less the fee) of selling n
* nomins.
* Reverts if the price is stale. */
function saleProceedsEther(uint n)
public
view
returns (uint)
{
// Price staleness check occurs inside the call to etherValue.
return etherValue(saleProceedsFiat(n));
}
/* The same as saleProceedsEther(), but without the stale price check. */
function saleProceedsEtherAllowStale(uint n)
internal
view
returns (uint)
{
return etherValueAllowStale(saleProceedsFiat(n));
}
/* True iff the current block timestamp is later than the time
* the price was last updated, plus the stale period. */
function priceIsStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdate, stalePeriod) < now;
}
function isLiquidating()
public
view
returns (bool)
{
return liquidationTimestamp <= now;
}
/* True if the contract is self-destructible.
* This is true if either the complete liquidation period has elapsed,
* or if all tokens have been returned to the contract and it has been
* in liquidation for at least a week.
* Since the contract is only destructible after the liquidationTimestamp,
* a fortiori canSelfDestruct() implies isLiquidating(). */
function canSelfDestruct()
public
view
returns (bool)
{
// Not being in liquidation implies the timestamp is uint max, so it would roll over.
// We need to check whether we're in liquidation first.
if (isLiquidating()) {
// These timestamps and durations have values clamped within reasonable values and
// cannot overflow.
bool totalPeriodElapsed = liquidationTimestamp + liquidationPeriod < now;
// Total supply of 0 means all tokens have returned to the pool.
bool allTokensReturned = (liquidationTimestamp + 1 weeks < now) && (totalSupply == 0);
return totalPeriodElapsed || allTokensReturned;
}
return false;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Override ERC20 transfer function in order to check
* whether the recipient account is frozen. Note that there is
* no need to check whether the sender has a frozen account,
* since their funds have already been confiscated,
* and no new funds can be transferred to it.*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transfer_byProxy(messageSender, to, value);
}
/* Override ERC20 transferFrom function in order to check
* whether the recipient account is frozen. */
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transferFrom_byProxy(messageSender, from, to, value);
}
/* Update the current ether price and update the last updated time,
* refreshing the price staleness.
* Also checks whether the contract's collateral levels have fallen to low,
* and initiates liquidation if that is the case.
* Exceptional conditions:
* Not called by the oracle.
* Not the most recently sent price. */
function updatePrice(uint price, uint timeSent)
external
postCheckAutoLiquidate
{
// Should be callable only by the oracle.
require(msg.sender == oracle);
// Must be the most recently sent price, but not too far in the future.
// (so we can't lock ourselves out of updating the oracle for longer than this)
require(lastPriceUpdate < timeSent && timeSent < now + 10 minutes);
etherPrice = price;
lastPriceUpdate = timeSent;
emit PriceUpdated(price);
}
/* Issues n nomins into the pool available to be bought by users.
* Must be accompanied by $n worth of ether.
* Exceptional conditions:
* Not called by contract owner.
* Insufficient backing funds provided (post-issuance collateralisation below minimum requirement).
* Price is stale. */
function replenishPool(uint n)
external
payable
notLiquidating
optionalProxy_onlyOwner
{
// Price staleness check occurs inside the call to fiatBalance.
// Safe additions are unnecessary here, as either the addition is checked on the following line
// or the overflow would cause the requirement not to be satisfied.
require(fiatBalance() >= safeMul_dec(safeAdd(_nominCap(), n), MINIMUM_ISSUANCE_RATIO));
nominPool = safeAdd(nominPool, n);
emit PoolReplenished(n, msg.value);
}
/* Burns n nomins from the pool.
* Exceptional conditions:
* Not called by contract owner.
* There are fewer than n nomins in the pool. */
function diminishPool(uint n)
external
optionalProxy_onlyOwner
{
// Require that there are enough nomins in the accessible pool to burn
require(nominPool >= n);
nominPool = safeSub(nominPool, n);
emit PoolDiminished(n);
}
/* Sends n nomins to the sender from the pool, in exchange for
* $n plus the fee worth of ether.
* Exceptional conditions:
* Insufficient or too many funds provided.
* More nomins requested than are in the pool.
* n below the purchase minimum (1 cent).
* contract in liquidation.
* Price is stale. */
function buy(uint n)
external
payable
notLiquidating
optionalProxy
{
// Price staleness check occurs inside the call to purchaseEtherCost.
require(n >= MINIMUM_PURCHASE &&
msg.value == purchaseCostEther(n));
address sender = messageSender;
// sub requires that nominPool >= n
nominPool = safeSub(nominPool, n);
state.setBalanceOf(sender, safeAdd(state.balanceOf(sender), n));
emit Purchased(sender, sender, n, msg.value);
emit Transfer(0, sender, n);
totalSupply = safeAdd(totalSupply, n);
}
/* Sends n nomins to the pool from the sender, in exchange for
* $n minus the fee worth of ether.
* Exceptional conditions:
* Insufficient nomins in sender's wallet.
* Insufficient funds in the pool to pay sender.
* Price is stale if not in liquidation. */
function sell(uint n)
external
optionalProxy
{
// Price staleness check occurs inside the call to saleProceedsEther,
// but we allow people to sell their nomins back to the system
// if we're in liquidation, regardless.
uint proceeds;
if (isLiquidating()) {
proceeds = saleProceedsEtherAllowStale(n);
} else {
proceeds = saleProceedsEther(n);
}
require(address(this).balance >= proceeds);
address sender = messageSender;
// sub requires that the balance is greater than n
state.setBalanceOf(sender, safeSub(state.balanceOf(sender), n));
nominPool = safeAdd(nominPool, n);
emit Sold(sender, sender, n, proceeds);
emit Transfer(sender, 0, n);
totalSupply = safeSub(totalSupply, n);
sender.transfer(proceeds);
}
/* Lock nomin purchase function in preparation for destroying the contract.
* While the contract is under liquidation, users may sell nomins back to the system.
* After liquidation period has terminated, the contract may be self-destructed,
* returning all remaining ether to the beneficiary address.
* Exceptional cases:
* Not called by contract owner;
* contract already in liquidation; */
function forceLiquidation()
external
notLiquidating
optionalProxy_onlyOwner
{
beginLiquidation();
}
function beginLiquidation()
internal
{
liquidationTimestamp = now;
emit LiquidationBegun(liquidationPeriod);
}
/* If the contract is liquidating, the owner may extend the liquidation period.
* It may only get longer, not shorter, and it may not be extended past
* the liquidation max. */
function extendLiquidationPeriod(uint extension)
external
optionalProxy_onlyOwner
{
require(isLiquidating());
uint sum = safeAdd(liquidationPeriod, extension);
require(sum <= MAX_LIQUIDATION_PERIOD);
liquidationPeriod = sum;
emit LiquidationExtended(extension);
}
/* Liquidation can only be stopped if the collateralisation ratio
* of this contract has recovered above the automatic liquidation
* threshold, for example if the ether price has increased,
* or by including enough ether in this transaction. */
function terminateLiquidation()
external
payable
priceNotStale
optionalProxy_onlyOwner
{
require(isLiquidating());
require(_nominCap() == 0 || collateralisationRatio() >= AUTO_LIQUIDATION_RATIO);
liquidationTimestamp = ~uint(0);
liquidationPeriod = DEFAULT_LIQUIDATION_PERIOD;
emit LiquidationTerminated();
}
/* The owner may destroy this contract, returning all funds back to the beneficiary
* wallet, may only be called after the contract has been in
* liquidation for at least liquidationPeriod, or all circulating
* nomins have been sold back into the pool. */
function selfDestruct()
external
optionalProxy_onlyOwner
{
require(canSelfDestruct());
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
/* If a confiscation court motion has passed and reached the confirmation
* state, the court may transfer the target account's balance to the fee pool
* and freeze its participation in further transactions. */
function confiscateBalance(address target)
external
{
// Should be callable only by the confiscation court.
require(Court(msg.sender) == court);
// A motion must actually be underway.
uint motionID = court.targetMotionID(target);
require(motionID != 0);
// These checks are strictly unnecessary,
// since they are already checked in the court contract itself.
// I leave them in out of paranoia.
require(court.motionConfirming(motionID));
require(court.motionPasses(motionID));
require(!frozen[target]);
// Confiscate the balance in the account and freeze it.
uint balance = state.balanceOf(target);
state.setBalanceOf(address(this), safeAdd(state.balanceOf(address(this)), balance));
state.setBalanceOf(target, 0);
frozen[target] = true;
emit AccountFrozen(target, target, balance);
emit Transfer(target, address(this), balance);
}
/* The owner may allow a previously-frozen contract to once
* again accept and transfer nomins. */
function unfreezeAccount(address target)
external
optionalProxy_onlyOwner
{
if (frozen[target] && EtherNomin(target) != this) {
frozen[target] = false;
emit AccountUnfrozen(target, target);
}
}
/* Fallback function allows convenient collateralisation of the contract,
* including by non-foundation parties. */
function() public payable {}
/* ========== MODIFIERS ========== */
modifier notLiquidating
{
require(!isLiquidating());
_;
}
modifier priceNotStale
{
require(!priceIsStale());
_;
}
/* Any function modified by this will automatically liquidate
* the system if the collateral levels are too low.
* This is called on collateral-value/nomin-supply modifying functions that can
* actually move the contract into liquidation. This is really only
* the price update, since issuance requires that the contract is overcollateralised,
* burning can only destroy tokens without withdrawing backing, buying from the pool can only
* asymptote to a collateralisation level of unity, while selling into the pool can only
* increase the collateralisation ratio.
* Additionally, price update checks should/will occur frequently. */
modifier postCheckAutoLiquidate
{
_;
if (!isLiquidating() && _nominCap() != 0 && collateralisationRatio() < AUTO_LIQUIDATION_RATIO) {
beginLiquidation();
}
}
/* ========== EVENTS ========== */
event PoolReplenished(uint nominsCreated, uint collateralDeposited);
event PoolDiminished(uint nominsDestroyed);
event Purchased(address buyer, address indexed buyerIndex, uint nomins, uint eth);
event Sold(address seller, address indexed sellerIndex, uint nomins, uint eth);
event PriceUpdated(uint newPrice);
event StalePeriodUpdated(uint newPeriod);
event OracleUpdated(address newOracle);
event CourtUpdated(address newCourt);
event BeneficiaryUpdated(address newBeneficiary);
event LiquidationBegun(uint duration);
event LiquidationTerminated();
event LiquidationExtended(uint extension);
event PoolFeeRateUpdated(uint newFeeRate);
event SelfDestructed(address beneficiary);
event AccountFrozen(address target, address indexed targetIndex, uint balance);
event AccountUnfrozen(address target, address indexed targetIndex);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
A token interface to be overridden to produce an ERC20-compliant
token contract. It relies on being called underneath a proxy,
as described in Proxy.sol.
This contract utilises a state for upgradability purposes.
-----------------------------------------------------------------
*/
contract ExternStateProxyToken is SafeDecimalMath, Proxyable {
/* ========== STATE VARIABLES ========== */
// Stores balances and allowances.
TokenState public state;
// Other ERC20 fields
string public name;
string public symbol;
uint public totalSupply;
/* ========== CONSTRUCTOR ========== */
function ExternStateProxyToken(string _name, string _symbol,
uint initialSupply, address initialBeneficiary,
TokenState _state, address _owner)
Proxyable(_owner)
public
{
name = _name;
symbol = _symbol;
totalSupply = initialSupply;
// if the state isn't set, create a new one
if (_state == TokenState(0)) {
state = new TokenState(_owner, address(this));
state.setBalanceOf(initialBeneficiary, totalSupply);
emit Transfer(address(0), initialBeneficiary, initialSupply);
} else {
state = _state;
}
}
/* ========== VIEWS ========== */
function allowance(address tokenOwner, address spender)
public
view
returns (uint)
{
return state.allowance(tokenOwner, spender);
}
function balanceOf(address account)
public
view
returns (uint)
{
return state.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function setState(TokenState _state)
external
optionalProxy_onlyOwner
{
state = _state;
emit StateUpdated(_state);
}
/* Anything calling this must apply the onlyProxy or optionalProxy modifiers.*/
function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
require(to != address(0));
// Insufficient balance will be handled by the safe subtraction.
state.setBalanceOf(sender, safeSub(state.balanceOf(sender), value));
state.setBalanceOf(to, safeAdd(state.balanceOf(to), value));
emit Transfer(sender, to, value);
return true;
}
/* Anything calling this must apply the onlyProxy or optionalProxy modifiers.*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
require(from != address(0) && to != address(0));
// Insufficient balance will be handled by the safe subtraction.
state.setBalanceOf(from, safeSub(state.balanceOf(from), value));
state.setAllowance(from, sender, safeSub(state.allowance(from, sender), value));
state.setBalanceOf(to, safeAdd(state.balanceOf(to), value));
emit Transfer(from, to, value);
return true;
}
function approve(address spender, uint value)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
state.setAllowance(sender, spender, value);
emit Approval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event StateUpdated(address newState);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
This contract allows the foundation to apply unique vesting
schedules to havven funds sold at various discounts in the token
sale. HavvenEscrow gives users the ability to inspect their
vested funds, their quantities and vesting dates, and to withdraw
the fees that accrue on those funds.
The fees are handled by withdrawing the entire fee allocation
for all havvens inside the escrow contract, and then allowing
the contract itself to subdivide that pool up proportionally within
itself. Every time the fee period rolls over in the main Havven
contract, the HavvenEscrow fee pool is remitted back into the
main fee pool to be redistributed in the next fee period.
-----------------------------------------------------------------
*/
contract HavvenEscrow is Owned, LimitedSetup(8 weeks), SafeDecimalMath {
// The corresponding Havven contract.
Havven public havven;
// Lists of (timestamp, quantity) pairs per account, sorted in ascending time order.
// These are the times at which each given quantity of havvens vests.
mapping(address => uint[2][]) public vestingSchedules;
// An account's total vested havven balance to save recomputing this for fee extraction purposes.
mapping(address => uint) public totalVestedAccountBalance;
// The total remaining vested balance, for verifying the actual havven balance of this contract against.
uint public totalVestedBalance;
/* ========== CONSTRUCTOR ========== */
function HavvenEscrow(address _owner, Havven _havven)
Owned(_owner)
public
{
havven = _havven;
}
/* ========== SETTERS ========== */
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
/* ========== VIEW FUNCTIONS ========== */
/* A simple alias to totalVestedAccountBalance: provides ERC20 balance integration. */
function balanceOf(address account)
public
view
returns (uint)
{
return totalVestedAccountBalance[account];
}
/* The number of vesting dates in an account's schedule. */
function numVestingEntries(address account)
public
view
returns (uint)
{
return vestingSchedules[account].length;
}
/* Get a particular schedule entry for an account.
* The return value is a pair (timestamp, havven quantity) */
function getVestingScheduleEntry(address account, uint index)
public
view
returns (uint[2])
{
return vestingSchedules[account][index];
}
/* Get the time at which a given schedule entry will vest. */
function getVestingTime(address account, uint index)
public
view
returns (uint)
{
return vestingSchedules[account][index][0];
}
/* Get the quantity of havvens associated with a given schedule entry. */
function getVestingQuantity(address account, uint index)
public
view
returns (uint)
{
return vestingSchedules[account][index][1];
}
/* Obtain the index of the next schedule entry that will vest for a given user. */
function getNextVestingIndex(address account)
public
view
returns (uint)
{
uint len = numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return len;
}
/* Obtain the next schedule entry that will vest for a given user.
* The return value is a pair (timestamp, havven quantity) */
function getNextVestingEntry(address account)
external
view
returns (uint[2])
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return [uint(0), 0];
}
return getVestingScheduleEntry(account, index);
}
/* Obtain the time at which the next schedule entry will vest for a given user. */
function getNextVestingTime(address account)
external
view
returns (uint)
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return 0;
}
return getVestingTime(account, index);
}
/* Obtain the quantity which the next schedule entry will vest for a given user. */
function getNextVestingQuantity(address account)
external
view
returns (uint)
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return 0;
}
return getVestingQuantity(account, index);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Withdraws a quantity of havvens back to the havven contract. */
function withdrawHavvens(uint quantity)
external
onlyOwner
setupFunction
{
havven.transfer(havven, quantity);
}
/* Destroy the vesting information associated with an account. */
function purgeAccount(address account)
external
onlyOwner
setupFunction
{
delete vestingSchedules[account];
totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]);
delete totalVestedAccountBalance[account];
}
/* Add a new vesting entry at a given time and quantity to an account's schedule.
* A call to this should be accompanied by either enough balance already available
* in this contract, or a corresponding call to havven.endow(), to ensure that when
* the funds are withdrawn, there is enough balance, as well as correctly calculating
* the fees.
* Note; although this function could technically be used to produce unbounded
* arrays, it's only in the foundation's command to add to these lists. */
function appendVestingEntry(address account, uint time, uint quantity)
public
onlyOwner
setupFunction
{
// No empty or already-passed vesting entries allowed.
require(now < time);
require(quantity != 0);
totalVestedBalance = safeAdd(totalVestedBalance, quantity);
require(totalVestedBalance <= havven.balanceOf(this));
if (vestingSchedules[account].length == 0) {
totalVestedAccountBalance[account] = quantity;
} else {
// Disallow adding new vested havvens earlier than the last one.
// Since entries are only appended, this means that no vesting date can be repeated.
require(getVestingTime(account, numVestingEntries(account) - 1) < time);
totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity);
}
vestingSchedules[account].push([time, quantity]);
}
/* Construct a vesting schedule to release a quantities of havvens
* over a series of intervals. Assumes that the quantities are nonzero
* and that the sequence of timestamps is strictly increasing. */
function addVestingSchedule(address account, uint[] times, uint[] quantities)
external
onlyOwner
setupFunction
{
for (uint i = 0; i < times.length; i++) {
appendVestingEntry(account, times[i], quantities[i]);
}
}
/* Allow a user to withdraw any tokens that have vested. */
function vest()
external
{
uint total;
for (uint i = 0; i < numVestingEntries(msg.sender); i++) {
uint time = getVestingTime(msg.sender, i);
// The list is sorted; when we reach the first future time, bail out.
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty == 0) {
continue;
}
vestingSchedules[msg.sender][i] = [0, 0];
total = safeAdd(total, qty);
totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], qty);
}
if (total != 0) {
totalVestedBalance = safeSub(totalVestedBalance, total);
havven.transfer(msg.sender, total);
emit Vested(msg.sender, msg.sender,
now, total);
}
}
/* ========== EVENTS ========== */
event HavvenUpdated(address newHavven);
event Vested(address beneficiary, address indexed beneficiaryIndex, uint time, uint value);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
This contract allows an inheriting contract to be destroyed after
its owner indicates an intention and then waits for a period
without changing their mind.
-----------------------------------------------------------------
*/
contract SelfDestructible is Owned {
uint public initiationTime = ~uint(0);
uint constant SD_DURATION = 3 days;
address public beneficiary;
function SelfDestructible(address _owner, address _beneficiary)
public
Owned(_owner)
{
beneficiary = _beneficiary;
}
function setBeneficiary(address _beneficiary)
external
onlyOwner
{
beneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
emit SelfDestructInitiated(SD_DURATION);
}
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = ~uint(0);
emit SelfDestructTerminated();
}
function selfDestruct()
external
onlyOwner
{
require(initiationTime + SD_DURATION < now);
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
event SelfDestructInitiated(uint duration);
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
Havven token contract. Havvens are transferable ERC20 tokens,
and also give their holders the following privileges.
An owner of havvens is entitled to a share in the fees levied on
nomin transactions, and additionally may participate in nomin
confiscation votes.
After a fee period terminates, the duration and fees collected for that
period are computed, and the next period begins.
Thus an account may only withdraw the fees owed to them for the previous
period, and may only do so once per period.
Any unclaimed fees roll over into the common pot for the next period.
The fee entitlement of a havven holder is proportional to their average
havven balance over the last fee period. This is computed by measuring the
area under the graph of a user's balance over time, and then when fees are
distributed, dividing through by the duration of the fee period.
We need only update fee entitlement on transfer when the havven balances of the sender
and recipient are modified. This is for efficiency, and adds an implicit friction to
trading in the havven market. A havven holder pays for his own recomputation whenever
he wants to change his position, which saves the foundation having to maintain a pot
dedicated to resourcing this.
A hypothetical user's balance history over one fee period, pictorially:
s ____
| |
| |___ p
|____|___|___ __ _ _
f t n
Here, the balance was s between times f and t, at which time a transfer
occurred, updating the balance to p, until n, when the present transfer occurs.
When a new transfer occurs at time n, the balance being p,
we must:
- Add the area p * (n - t) to the total area recorded so far
- Update the last transfer time to p
So if this graph represents the entire current fee period,
the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f).
The complementary computations must be performed for both sender and
recipient.
Note that a transfer keeps global supply of havvens invariant.
The sum of all balances is constant, and unmodified by any transfer.
So the sum of all balances multiplied by the duration of a fee period is also
constant, and this is equivalent to the sum of the area of every user's
time/balance graph. Dividing through by that duration yields back the total
havven supply. So, at the end of a fee period, we really do yield a user's
average share in the havven supply over that period.
A slight wrinkle is introduced if we consider the time r when the fee period
rolls over. Then the previous fee period k-1 is before r, and the current fee
period k is afterwards. If the last transfer took place before r,
but the latest transfer occurred afterwards:
k-1 | k
s __|_
| | |
| | |____ p
|__|_|____|___ __ _ _
|
f | t n
r
In this situation the area (r-f)*s contributes to fee period k-1, while
the area (t-r)*s contributes to fee period k. We will implicitly consider a
zero-value transfer to have occurred at time r. Their fee entitlement for the
previous period will be finalised at the time of their first transfer during the
current fee period, or when they query or withdraw their fee entitlement.
In the implementation, the duration of different fee periods may be slightly irregular,
as the check that they have rolled over occurs only when state-changing havven
operations are performed.
Additionally, we keep track also of the penultimate and not just the last
average balance, in order to support the voting functionality detailed in Court.sol.
-----------------------------------------------------------------
*/
contract Havven is ExternStateProxyToken, SelfDestructible {
/* ========== STATE VARIABLES ========== */
// Sums of balances*duration in the current fee period.
// range: decimals; units: havven-seconds
mapping(address => uint) public currentBalanceSum;
// Average account balances in the last completed fee period. This is proportional
// to that account's last period fee entitlement.
// (i.e. currentBalanceSum for the previous period divided through by duration)
// WARNING: This may not have been updated for the latest fee period at the
// time it is queried.
// range: decimals; units: havvens
mapping(address => uint) public lastAverageBalance;
// The average account balances in the period before the last completed fee period.
// This is used as a person's weight in a confiscation vote, so it implies that
// the vote duration must be no longer than the fee period in order to guarantee that
// no portion of a fee period used for determining vote weights falls within the
// duration of a vote it contributes to.
// WARNING: This may not have been updated for the latest fee period at the
// time it is queried.
mapping(address => uint) public penultimateAverageBalance;
// The time an account last made a transfer.
// range: naturals
mapping(address => uint) public lastTransferTimestamp;
// The time the current fee period began.
uint public feePeriodStartTime = 3;
// The actual start of the last fee period (seconds).
// This, and the penultimate fee period can be initially set to any value
// 0 < val < now, as everyone's individual lastTransferTime will be 0
// and as such, their lastAvgBal/penultimateAvgBal will be set to that value
// apart from the contract, which will have totalSupply
uint public lastFeePeriodStartTime = 2;
// The actual start of the penultimate fee period (seconds).
uint public penultimateFeePeriodStartTime = 1;
// Fee periods will roll over in no shorter a time than this.
uint public targetFeePeriodDurationSeconds = 4 weeks;
// And may not be set to be shorter than a day.
uint constant MIN_FEE_PERIOD_DURATION_SECONDS = 1 days;
// And may not be set to be longer than six months.
uint constant MAX_FEE_PERIOD_DURATION_SECONDS = 26 weeks;
// The quantity of nomins that were in the fee pot at the time
// of the last fee rollover (feePeriodStartTime).
uint public lastFeesCollected;
mapping(address => bool) public hasWithdrawnLastPeriodFees;
EtherNomin public nomin;
HavvenEscrow public escrow;
/* ========== CONSTRUCTOR ========== */
function Havven(TokenState initialState, address _owner)
ExternStateProxyToken("Havven", "HAV", 1e8 * UNIT, address(this), initialState, _owner)
SelfDestructible(_owner, _owner)
// Owned is initialised in ExternStateProxyToken
public
{
lastTransferTimestamp[this] = now;
feePeriodStartTime = now;
lastFeePeriodStartTime = now - targetFeePeriodDurationSeconds;
penultimateFeePeriodStartTime = now - 2*targetFeePeriodDurationSeconds;
}
/* ========== SETTERS ========== */
function setNomin(EtherNomin _nomin)
external
optionalProxy_onlyOwner
{
nomin = _nomin;
}
function setEscrow(HavvenEscrow _escrow)
external
optionalProxy_onlyOwner
{
escrow = _escrow;
}
function setTargetFeePeriodDuration(uint duration)
external
postCheckFeePeriodRollover
optionalProxy_onlyOwner
{
require(MIN_FEE_PERIOD_DURATION_SECONDS <= duration &&
duration <= MAX_FEE_PERIOD_DURATION_SECONDS);
targetFeePeriodDurationSeconds = duration;
emit FeePeriodDurationUpdated(duration);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Allow the owner of this contract to endow any address with havvens
* from the initial supply. Since the entire initial supply resides
* in the havven contract, this disallows the foundation from withdrawing
* fees on undistributed balances. This function can also be used
* to retrieve any havvens sent to the Havven contract itself. */
function endow(address account, uint value)
external
optionalProxy_onlyOwner
returns (bool)
{
// Use "this" in order that the havven account is the sender.
// That this is an explicit transfer also initialises fee entitlement information.
return _transfer(this, account, value);
}
/* Allow the owner of this contract to emit transfer events for
* contract setup purposes. */
function emitTransferEvents(address sender, address[] recipients, uint[] values)
external
onlyOwner
{
for (uint i = 0; i < recipients.length; ++i) {
emit Transfer(sender, recipients[i], values[i]);
}
}
/* Override ERC20 transfer function in order to perform
* fee entitlement recomputation whenever balances are updated. */
function transfer(address to, uint value)
external
optionalProxy
returns (bool)
{
return _transfer(messageSender, to, value);
}
/* Anything calling this must apply the optionalProxy or onlyProxy modifier. */
function _transfer(address sender, address to, uint value)
internal
preCheckFeePeriodRollover
returns (bool)
{
uint senderPreBalance = state.balanceOf(sender);
uint recipientPreBalance = state.balanceOf(to);
// Perform the transfer: if there is a problem,
// an exception will be thrown in this call.
_transfer_byProxy(sender, to, value);
// Zero-value transfers still update fee entitlement information,
// and may roll over the fee period.
adjustFeeEntitlement(sender, senderPreBalance);
adjustFeeEntitlement(to, recipientPreBalance);
return true;
}
/* Override ERC20 transferFrom function in order to perform
* fee entitlement recomputation whenever balances are updated. */
function transferFrom(address from, address to, uint value)
external
preCheckFeePeriodRollover
optionalProxy
returns (bool)
{
uint senderPreBalance = state.balanceOf(from);
uint recipientPreBalance = state.balanceOf(to);
// Perform the transfer: if there is a problem,
// an exception will be thrown in this call.
_transferFrom_byProxy(messageSender, from, to, value);
// Zero-value transfers still update fee entitlement information,
// and may roll over the fee period.
adjustFeeEntitlement(from, senderPreBalance);
adjustFeeEntitlement(to, recipientPreBalance);
return true;
}
/* Compute the last period's fee entitlement for the message sender
* and then deposit it into their nomin account. */
function withdrawFeeEntitlement()
public
preCheckFeePeriodRollover
optionalProxy
{
address sender = messageSender;
// Do not deposit fees into frozen accounts.
require(!nomin.frozen(sender));
// check the period has rolled over first
rolloverFee(sender, lastTransferTimestamp[sender], state.balanceOf(sender));
// Only allow accounts to withdraw fees once per period.
require(!hasWithdrawnLastPeriodFees[sender]);
uint feesOwed;
if (escrow != HavvenEscrow(0)) {
feesOwed = escrow.totalVestedAccountBalance(sender);
}
feesOwed = safeDiv_dec(safeMul_dec(safeAdd(feesOwed, lastAverageBalance[sender]),
lastFeesCollected),
totalSupply);
hasWithdrawnLastPeriodFees[sender] = true;
if (feesOwed != 0) {
nomin.withdrawFee(sender, feesOwed);
emit FeesWithdrawn(sender, sender, feesOwed);
}
}
/* Update the fee entitlement since the last transfer or entitlement
* adjustment. Since this updates the last transfer timestamp, if invoked
* consecutively, this function will do nothing after the first call. */
function adjustFeeEntitlement(address account, uint preBalance)
internal
{
// The time since the last transfer clamps at the last fee rollover time if the last transfer
// was earlier than that.
rolloverFee(account, lastTransferTimestamp[account], preBalance);
currentBalanceSum[account] = safeAdd(
currentBalanceSum[account],
safeMul(preBalance, now - lastTransferTimestamp[account])
);
// Update the last time this user's balance changed.
lastTransferTimestamp[account] = now;
}
/* Update the given account's previous period fee entitlement value.
* Do nothing if the last transfer occurred since the fee period rolled over.
* If the entitlement was updated, also update the last transfer time to be
* at the timestamp of the rollover, so if this should do nothing if called more
* than once during a given period.
*
* Consider the case where the entitlement is updated. If the last transfer
* occurred at time t in the last period, then the starred region is added to the
* entitlement, the last transfer timestamp is moved to r, and the fee period is
* rolled over from k-1 to k so that the new fee period start time is at time r.
*
* k-1 | k
* s __|
* _ _ ___|**|
* |**|
* _ _ ___|**|___ __ _ _
* |
* t |
* r
*
* Similar computations are performed according to the fee period in which the
* last transfer occurred.
*/
function rolloverFee(address account, uint lastTransferTime, uint preBalance)
internal
{
if (lastTransferTime < feePeriodStartTime) {
if (lastTransferTime < lastFeePeriodStartTime) {
// The last transfer predated the previous two fee periods.
if (lastTransferTime < penultimateFeePeriodStartTime) {
// The balance did nothing in the penultimate fee period, so the average balance
// in this period is their pre-transfer balance.
penultimateAverageBalance[account] = preBalance;
// The last transfer occurred within the one-before-the-last fee period.
} else {
// No overflow risk here: the failed guard implies (penultimateFeePeriodStartTime <= lastTransferTime).
penultimateAverageBalance[account] = safeDiv(
safeAdd(currentBalanceSum[account], safeMul(preBalance, (lastFeePeriodStartTime - lastTransferTime))),
(lastFeePeriodStartTime - penultimateFeePeriodStartTime)
);
}
// The balance did nothing in the last fee period, so the average balance
// in this period is their pre-transfer balance.
lastAverageBalance[account] = preBalance;
// The last transfer occurred within the last fee period.
} else {
// The previously-last average balance becomes the penultimate balance.
penultimateAverageBalance[account] = lastAverageBalance[account];
// No overflow risk here: the failed guard implies (lastFeePeriodStartTime <= lastTransferTime).
lastAverageBalance[account] = safeDiv(
safeAdd(currentBalanceSum[account], safeMul(preBalance, (feePeriodStartTime - lastTransferTime))),
(feePeriodStartTime - lastFeePeriodStartTime)
);
}
// Roll over to the next fee period.
currentBalanceSum[account] = 0;
hasWithdrawnLastPeriodFees[account] = false;
lastTransferTimestamp[account] = feePeriodStartTime;
}
}
/* Recompute and return the given account's average balance information.
* This also rolls over the fee period if necessary, and brings
* the account's current balance sum up to date. */
function _recomputeAccountLastAverageBalance(address account)
internal
preCheckFeePeriodRollover
returns (uint)
{
adjustFeeEntitlement(account, state.balanceOf(account));
return lastAverageBalance[account];
}
/* Recompute and return the sender's average balance information. */
function recomputeLastAverageBalance()
external
optionalProxy
returns (uint)
{
return _recomputeAccountLastAverageBalance(messageSender);
}
/* Recompute and return the given account's average balance information. */
function recomputeAccountLastAverageBalance(address account)
external
returns (uint)
{
return _recomputeAccountLastAverageBalance(account);
}
function rolloverFeePeriod()
public
{
checkFeePeriodRollover();
}
/* ========== MODIFIERS ========== */
/* If the fee period has rolled over, then
* save the start times of the last fee period,
* as well as the penultimate fee period.
*/
function checkFeePeriodRollover()
internal
{
// If the fee period has rolled over...
if (feePeriodStartTime + targetFeePeriodDurationSeconds <= now) {
lastFeesCollected = nomin.feePool();
// Shift the three period start times back one place
penultimateFeePeriodStartTime = lastFeePeriodStartTime;
lastFeePeriodStartTime = feePeriodStartTime;
feePeriodStartTime = now;
emit FeePeriodRollover(now);
}
}
modifier postCheckFeePeriodRollover
{
_;
checkFeePeriodRollover();
}
modifier preCheckFeePeriodRollover
{
checkFeePeriodRollover();
_;
}
/* ========== EVENTS ========== */
event FeePeriodRollover(uint timestamp);
event FeePeriodDurationUpdated(uint duration);
event FeesWithdrawn(address account, address indexed accountIndex, uint value);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
A contract that holds the state of an ERC20 compliant token.
This contract is used side by side with external state token
contracts, such as Havven and EtherNomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
contract TokenState is Owned {
// the address of the contract that can modify balances and allowances
// this can only be changed by the owner of this contract
address public associatedContract;
// ERC20 fields.
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
function TokenState(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract);
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address _associatedContract);
}
/*
MIT License
Copyright (c) 2018 Havven
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.
*/
|
Return the result of subtracting y from x, throwing an exception in case of overflow. /
|
function safeSub(uint x, uint y)
pure
internal
returns (uint)
{
require(y <= x);
return x - y;
}
| 1,229,997 |
./full_match/9001/0x3Db06DA8F0a24A525f314eeC954fC5c6a973d40E/sources/contracts/cross-chain-oracle/interfaces/ChildMessengerConsumerInterface.sol
|
Called on L2 by child messenger.
|
interface ChildMessengerConsumerInterface {
function processMessageFromParent(bytes memory data) external;
pragma solidity ^0.8.0;
}
| 11,534,033 |
/*** MOOswap.org
* █████████████████████ █████████████████████ █████████████████████
* ███ ███ ███ ███ ███ ███ ███
* ███ ███ ███ ███ ███ ███ ███
* ███ ███ ███ ███ █ █ ███ ███ ███
* ███ ███ ███ ███ █████ ███ ███ ███
* ███ ███ ███ ███ █████ ███ ███ ███
* ███ ███ ███ ███ ███ ███ ███
* ███ ███ ███ ███ ███ ███ ███
* ███ ███ ███ █████████████████████ █████████████████████
// SPDX-License-Identifier: MIT
//File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _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: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @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 { }
}
// File: contracts/MOOswapToken.sol
pragma solidity 0.6.12;
contract MOOswapToken is ERC20("MOOswap.org", "MOO"), Ownable {
using SafeMath for uint256;
uint8 public FeeRate = 4;
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
uint256 feeAmount = amount.mul(FeeRate).div(100);
_burn(msg.sender, feeAmount);
return super.transfer(recipient, amount.sub(feeAmount));
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
uint256 feeAmount = amount.mul(FeeRate).div(100);
_burn(sender, feeAmount);
return super.transferFrom(sender, recipient, amount.sub(feeAmount));
}
/**
* @dev Chef distributes newly generated MOOswapToken to each farmmers
* "onlyOwner" :: for the one who worries about the function, this distribute process is only done by MasterChef contract for farming process
*/
function distribute(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
/**
* @dev Burning token for deflanationary features
*/
function burn(address _from, uint256 _amount) public {
_burn(_from, _amount);
}
/**
* @dev Tokenomic decition from governance
*/
function changeFeeRate(uint8 _feerate) public onlyOwner {
FeeRate = _feerate;
}
mapping (address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "MOOswap.org::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "MOOswap.org::delegateBySig: invalid nonce");
require(now <= expiry, "MOOswap.org::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "MOOswap.org::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "MOOswap.org::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/MOOchef.sol
pragma solidity 0.6.12;
interface IMigratorChef {
function migrate(IERC20 token) external returns (IERC20);
}
contract MOOchef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. Same as sushiswap
uint256 lastDepositTime; // Last LP deposit time
uint256 timelock; // Does the user has LP timelock 0: no, certain number: timelock period
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool.
uint256 lastRewardBlock; // Last block number that Burn distribution occurs.
uint256 accMooPerShare; // Accumulated token per share, times 1e12. See below.
uint256 isFreezone; // LP without Burn = 1, LP with Burn = 0
}
// MOOswapToken
MOOswapToken public moo;
// Dev, burn, and Buyback address.
address public devaddr;
address public burnaddr;
address public buybackaddr;
// Block number when bonus period ends.
uint256 public bonusEndBlock;
// Tokens created per block.
uint256 public mooPerBlock;
uint256 public BONUS_MULTIPLIER = 2;
// Defining diminish and vault fee.
uint256 public diminish = 10 days;
uint256 public vaultfee = 200;
uint256 public locktime = 2 days;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event DepositWithLPlock(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(
MOOswapToken _moo,
address _devaddr,
address _buybackaddr,
address _burnaddr,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
moo = _moo;
devaddr = _devaddr;
buybackaddr = _buybackaddr;
burnaddr = _burnaddr;
mooPerBlock = 100000000000000000; // 0.1 /Block
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function changeReward(uint256 _mooPerBlock) public onlyOwner {
mooPerBlock = _mooPerBlock;
}
function changeStartBlock(uint256 _startBlock) public onlyOwner {
startBlock = _startBlock;
}
function changeBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner {
bonusEndBlock = _bonusEndBlock;
}
function changeBonusMultiplier(uint256 _bonusMultiplier) public onlyOwner {
BONUS_MULTIPLIER = _bonusMultiplier;
}
function changeDiminishRate(uint256 _diminish) public onlyOwner {
diminish = _diminish;
}
function changeVaultfee(uint256 _vaultfee) public onlyOwner {
vaultfee = _vaultfee;
}
// Affective to the timelock after this change occurs
function changeLocktime(uint256 _locktime) public onlyOwner {
locktime = _locktime;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function add(uint256 _allocPoint, IERC20 _lpToken, uint256 _isFreezone, 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,
accMooPerShare: 0,
isFreezone: _isFreezone
}));
}
function set(uint256 _pid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].lpToken = _lpToken;
}
// 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 Burn on frontend.
function pendingMOO(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accMooPerShare = pool.accMooPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 mooReward = multiplier.mul(mooPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accMooPerShare = accMooPerShare.add(mooReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accMooPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to see estimated harvest after burnt MOO on frontend.
function estimatedMOO(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 depositduration = 0;
uint256 subrate = 1;
uint256 pending = 0;
if(now < (user.lastDepositTime + diminish) ){
subrate = depositduration.div(diminish);
}
uint256 accMooPerShare = pool.accMooPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 mooReward = multiplier.mul(mooPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accMooPerShare = accMooPerShare.add(mooReward.mul(1e12).div(lpSupply));
}
pending = user.amount.mul(accMooPerShare).div(1e12).sub(user.rewardDebt);
return pending.mul(subrate);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 mooReward = multiplier.mul(mooPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
moo.distribute(devaddr, mooReward.div(20));
moo.distribute(address(this), mooReward);
pool.accMooPerShare = pool.accMooPerShare.add(mooReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 vaultamount = 0;
uint256 depositduration = 0;
uint256 subrate = 1;
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accMooPerShare).div(1e12).sub(user.rewardDebt);
uint256 moopending = 0;
depositduration = now.sub(user.lastDepositTime);
if(now < (user.lastDepositTime + diminish) ){
subrate = depositduration.div(diminish);
}
if(pending > 0) {
moopending = pending.sub(pending.mul(subrate));
safeMooTransfer(msg.sender, pending.mul(subrate));
safeMooTransfer(burnaddr, moopending);
}
}
if(_amount > 0) {
if(pool.isFreezone > 0) {
vaultamount = _amount.div(vaultfee);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount.sub(vaultamount));
pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount);
}
if(pool.isFreezone < 1) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
user.amount = user.amount.add(_amount.sub(vaultamount));
user.lastDepositTime = now;
user.timelock = 0;
}
user.rewardDebt = user.amount.mul(pool.accMooPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
/** Locks lpToken for certain period. Locked LP depotied through this method only can be withdrawed after timelock period
*
*/
function depositWithLPlock(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 vaultamount = 0;
uint256 depositduration = 0;
uint256 subrate = 1;
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accMooPerShare).div(1e12).sub(user.rewardDebt);
uint256 moopending = 0;
depositduration = now.sub(user.lastDepositTime);
if(now < (user.lastDepositTime + diminish) ){
subrate = depositduration.div(diminish);
}
if(pending > 0) {
moopending = pending.sub(pending.mul(subrate));
safeMooTransfer(msg.sender, pending.mul(subrate));
safeMooTransfer(burnaddr, moopending);
}
}
if(_amount > 0) {
if(pool.isFreezone > 0) {
vaultamount = _amount.div(vaultfee);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount.sub(vaultamount));
pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount);
}
if(pool.isFreezone < 1) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
user.amount = user.amount.add(_amount.sub(vaultamount));
user.lastDepositTime = now;
user.timelock = locktime;
}
user.rewardDebt = user.amount.mul(pool.accMooPerShare).div(1e12);
emit DepositWithLPlock(msg.sender, _pid, _amount);
}
// Withdraw LP tokens.
// Only non-locked LP and Locked LP after lock period can be withdrawed
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");
require(now > user.lastDepositTime + user.timelock, "Your LP is LOCKed for the moment");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accMooPerShare).div(1e12).sub(user.rewardDebt);
uint256 depositduration = 0;
uint256 subrate = 1;
depositduration = now.sub(user.lastDepositTime);
if(now < (user.lastDepositTime + diminish) ){
subrate = depositduration.div(diminish);
}
if(pending > 0) {
safeMooTransfer(msg.sender, pending.mul(subrate));
safeMooTransfer(burnaddr, pending.sub(pending.mul(subrate)));
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.lastDepositTime = now.sub(depositduration.div(2));
user.rewardDebt = user.amount.mul(pool.accMooPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Update buyback address.
function bbto(address _buybackaddr) public {
require(msg.sender == buybackaddr, "ERROR");
buybackaddr = _buybackaddr;
}
// 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 MOO transfer function, just in case if rounding error causes pool to not have enough MOO.
function safeMooTransfer(address _to, uint256 _amount) internal {
uint256 mooBal = moo.balanceOf(address(this));
if (_amount > mooBal) {
moo.transfer(_to, mooBal);
} else {
moo.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "ERROR");
devaddr = _devaddr;
}
// Update burn-event address.
function burnto(address _burnaddr) public {
require(msg.sender == devaddr, "ERROR");
burnaddr = _burnaddr;
}
}
|
Update dev address by the previous dev.
|
function dev(address _devaddr) public {
require(msg.sender == devaddr, "ERROR");
devaddr = _devaddr;
}
| 1,998,486 |
./partial_match/1/0xa0d7a729544A4BE2287F8943d5fdDEf5c319D81b/sources/SteroidsGame.sol
|
Internal function for checking if the trigger action has occured at least K times in total times_ - the K number of days return true if the trigger action has occured at least K times, else - false potential winner
|
function _triggerActionForAtLeastKTimes(
uint256 times_
) private view returns (bool) {
if (maxWinCount >= times_) return true;
else if (maxWinCount == times_ - 1) {
for (uint256 i; i < settings.tokenCount; ) {
address curToken = tokens[i];
if (winCountPerPool[curToken] == times_ - 1) {
uint256 lastValidWinDay = _getDay(lastValidWinnerTimestamp);
uint256 today = getToday();
if (lastValidWinDay == today) {
unchecked {
++i;
}
}
if (
lastValidWinnerToken == curToken &&
lastBuyDayWinnerToken != address(0)
) return true;
}
unchecked {
++i;
}
}
return false;
return false;
}
}
| 4,490,482 |
./full_match/5/0xDF3CFaB2De111ba9b1fEc84977e09E6c3077705F/sources/contracts/staking/StakingContract.sol
|
Zero out the user's rewards balance Re-add the remainder of the rewards to the user's balance Check if the claimed reward amount is greater than or equal to the remaining balance
|
function claimRewards() public nonReentrant updateReward(msg.sender) {
uint256 originalReward = rewards[msg.sender];
uint256 rewardTokenBalance = address(this).balance;
if (originalReward > 0 && rewardTokenBalance > 0) {
uint256 transferredReward = (originalReward > rewardTokenBalance)
? rewardTokenBalance
: originalReward;
rewards[msg.sender] = 0;
payable(msg.sender).transfer(transferredReward);
emit RewardPaid(msg.sender, transferredReward);
uint256 remainder = originalReward - transferredReward;
rewards[msg.sender] = remainder;
if (
endStakingOnZeroBalance &&
transferredReward >= rewardTokenBalance
) {
periodFinish = block.timestamp;
stakingPeriodInitialized = false;
stakingStatus = StakingStatus.Inactive;
rewardsDuration = 0;
rewardsAmount = 0;
emit StakingPeriodEndedEarly();
}
}
}
| 1,932,166 |
./full_match/43113/0x3a7EfC389459dfF7166AE1B482a63ce2FFCDF61F/sources/contracts/avax.sol
|
Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IBEP20-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, "JHL: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
| 7,180,687 |
./partial_match/1/0xDa685c7E34Cc7c67fBC3cDf4E7D38bB024e999bF/sources/TokenLockerV1.sol
|
withdraw all of the deposited token/
|
function withdraw() external onlyOwner transferLocked {
require(uint40(block.timestamp) >= _unlockTime, "Wait until unlockTime to withdraw ");
_token.transfer(_owner(), _balance());
emit Withdrew();
}
| 16,178,684 |
./partial_match/1/0x45791a9Dd7fdD086ADaab9edb75057660ddfF5A1/sources/ERC1155Base.sol
|
Check registry code length to facilitate testing in environments without a deployed registry.
|
function _checkFilterOperator(address operator) internal view virtual {
if (operatorRestriction) {
if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {
if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {
revert OperatorNotAllowed(operator);
}
}
}
}
| 2,592,719 |
./full_match/80001/0x9a783aaE3780E922Ee628a319687Ccd8c630Fd29/sources/contracts/NextEcommerce.sol
|
Buscar el producto por su identificador
|
function buyProduct(
bytes32 _pId
) external payable returns (string memory message) {
Product storage product = products[0];
for (uint256 i = 0; i < numberOfProducts; i++) {
if (products[i].pId == _pId) {
product = products[i];
break;
}
}
product.sold++;
user: msg.sender,
habitation: "",
phone: 0,
cart: new string[](0),
total: subtotal,
delivered: false,
paid: true,
createdAt: block.timestamp,
updatedAt: block.timestamp
});
orders.push(order); */
| 5,598,856 |
pragma solidity ^0.5.3;
import "testeth/Log.sol";
import "testeth/Assert.sol";
import "testeth/Account.sol";
contract Factory {
event Deployed(address addr, uint256 salt);
function deploy1SignerWallet(uint256 threshold, address signatory) public returns (address payable addr) {
assembly {
// Multisig Wallet Code Below
mstore(1000, 0x38610137600039600051305560605b60405160200260600181101561002f5780)
mstore(1032, 0x518151555b60208101905061000e565b5060f780610040600039806000f350fe)
mstore(1064, 0x361560f65760003681610424376104a8516103e87f4a0a6d86122c7bd7083e83)
mstore(1096, 0x912c312adabf207e986f1ac10a35dfeb610d28d0b68152600180300180546104)
mstore(1128, 0x088181526104c8915085822061046852601987538384537fb0609d81c5f719d8)
mstore(1160, 0xa516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f260025260a0852060)
mstore(1192, 0x225260428720945086875b305481101560d05761042860608202610488510101)
mstore(1224, 0x87815261012c6020816080848e8c610bb8f1508381515411151560c0578a8bfd)
mstore(1256, 0x5b8051935050505b8581019050608a565b505080518401835550858686836104)
mstore(1288, 0x285161044851f4151560ef578586fd5b5050505050505b000000000000000000) // only 23 bytes -- 9 bytes shifted
mstore(1311, threshold) // start where code leaves off
mstore(1343, 0x0000000000000000000000000000000000000000000000000000000000000040)
mstore(1375, 0x0000000000000000000000000000000000000000000000000000000000000001) // 1 arr element
mstore(1407, signatory)
addr := create(0, 1000, 439)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
return addr;
}
function deploy2SignerWallet(uint256 threshold, address signatory1, address signatory2) public returns (address payable addr) {
assembly {
// Multisig Wallet Code Below
mstore(1000, 0x38610137600039600051305560605b60405160200260600181101561002f5780)
mstore(1032, 0x518151555b60208101905061000e565b5060f780610040600039806000f350fe)
mstore(1064, 0x361560f65760003681610424376104a8516103e87f4a0a6d86122c7bd7083e83)
mstore(1096, 0x912c312adabf207e986f1ac10a35dfeb610d28d0b68152600180300180546104)
mstore(1128, 0x088181526104c8915085822061046852601987538384537fb0609d81c5f719d8)
mstore(1160, 0xa516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f260025260a0852060)
mstore(1192, 0x225260428720945086875b305481101560d05761042860608202610488510101)
mstore(1224, 0x87815261012c6020816080848e8c610bb8f1508381515411151560c0578a8bfd)
mstore(1256, 0x5b8051935050505b8581019050608a565b505080518401835550858686836104)
mstore(1288, 0x285161044851f4151560ef578586fd5b5050505050505b000000000000000000) // only 23 bytes -- 9 bytes shifted
mstore(1311, threshold) // start where code leaves off
mstore(1343, 0x0000000000000000000000000000000000000000000000000000000000000060) // 60 end pos
mstore(1375, 0x0000000000000000000000000000000000000000000000000000000000000002) // 2 arr element
mstore(1407, signatory1)
mstore(1439, signatory2)
addr := create(0, 1000, 471)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
return addr;
}
}
contract MultisigWallet {
function execute(address destination, uint256 gasLimit, bytes calldata data, bytes32[] calldata signatures) external;
function () payable external;
function invalidMethod() external;
}
contract Recorder {
bytes data;
function () external {
data = msg.data;
}
function dataLen() external view returns (uint256) {
return data.length;
}
}
contract Teller {
function callit(address target, bytes calldata data) external {
target.call(data);
}
}
// test interest mechanism
contract test_Basics {
Factory factory = new Factory();
MultisigWallet wallet;
Recorder recorder = new Recorder();
Teller teller = new Teller();
function check_a1_construction_useAccount1() public {
wallet = MultisigWallet(factory.deploy1SignerWallet(1, msg.sender));
Log.data(address(wallet));
}
function check_a2_canAcceptEther_method_useValue4500() public payable {
address payable addr = address(wallet);
Assert.equal(addr.balance, 0);
addr.transfer(4500);
Assert.equal(addr.balance, 4500);
}
bytes recordData = "\x19\x01";
bytes data = abi.encodeWithSelector(bytes4(0x7214ae99), address(recorder), recordData);
uint256 gasLimit = 600000;
uint256 nonce = 0;
address destination = address(teller);
bytes32 hash;
function check_a3_buildHash_useAccount1() public {
// EIP712 Transaction Hash
hash = keccak256(abi.encodePacked(
"\x19\x01",
bytes32(0xb0609d81c5f719d8a516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f2),
keccak256(abi.encode(
bytes32(0x4a0a6d86122c7bd7083e83912c312adabf207e986f1ac10a35dfeb610d28d0b6),
nonce,
destination,
gasLimit,
keccak256(data)
))
));
Account.sign(1, hash);
}
bytes32[] arr;
function check_a4_signature_useAccount1(uint8 v, bytes32 r, bytes32 s) public {
arr.push(bytes32(uint256(v)));
arr.push(r);
arr.push(s);
Assert.equal(recorder.dataLen(), 0);
wallet.execute(destination, gasLimit, data, arr);
Assert.equal(recorder.dataLen(), 2);
}
function check_a5_buildHash_inceaseNonce_useAccount1() public {
// EIP712 Transaction Hash
nonce += 1;
recordData = "\x19\x01\x01";
data = abi.encodeWithSelector(bytes4(0x7214ae99), address(recorder), recordData);
hash = keccak256(abi.encodePacked(
"\x19\x01",
bytes32(0xb0609d81c5f719d8a516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f2),
keccak256(abi.encode(
bytes32(0x4a0a6d86122c7bd7083e83912c312adabf207e986f1ac10a35dfeb610d28d0b6),
nonce,
destination,
gasLimit,
keccak256(data)
))
));
Account.sign(1, hash);
}
bytes32[] arr2;
function check_a6_inceaseNonce_useAccount1(uint8 v, bytes32 r, bytes32 s) public {
arr2.push(bytes32(uint256(v)));
arr2.push(r);
arr2.push(s);
Assert.equal(recorder.dataLen(), 2);
wallet.execute(destination, gasLimit, data, arr2);
Assert.equal(recorder.dataLen(), 3);
}
function check_a7_buildHash_testInvalidNonce_useAccount1() public {
// EIP712 Transaction Hash
nonce = 1; // THIS IS AN INVALID NONCE
recordData = "\x19\x01\x01";
data = abi.encodeWithSelector(bytes4(0x7214ae99), address(recorder), recordData);
hash = keccak256(abi.encodePacked(
"\x19\x01",
bytes32(0xb0609d81c5f719d8a516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f2),
keccak256(abi.encode(
bytes32(0x4a0a6d86122c7bd7083e83912c312adabf207e986f1ac10a35dfeb610d28d0b6),
nonce,
destination,
gasLimit,
keccak256(data)
))
));
Account.sign(1, hash);
}
bytes32[] sig3;
function check_a8_testInvalidNonce_useAccount1_shouldThrow(uint8 v, bytes32 r, bytes32 s) public {
sig3.push(bytes32(uint256(v)));
sig3.push(r);
sig3.push(s);
wallet.execute(destination, gasLimit, data, sig3);
}
function check_b1_buildHash_testSameWithValidNonce_useAccount1() public {
// EIP712 Transaction Hash
nonce = 2; // THIS IS AN INVALID NONCE
recordData = "\x19\x01\x01";
data = abi.encodeWithSelector(bytes4(0x7214ae99), address(recorder), recordData);
hash = keccak256(abi.encodePacked(
"\x19\x01",
bytes32(0xb0609d81c5f719d8a516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f2),
keccak256(abi.encode(
bytes32(0x4a0a6d86122c7bd7083e83912c312adabf207e986f1ac10a35dfeb610d28d0b6),
nonce,
destination,
gasLimit,
keccak256(data)
))
));
Account.sign(1, hash);
}
bytes32[] sig4;
function check_b2_testSameWithValidNonce_useAccount1(uint8 v, bytes32 r, bytes32 s) public {
sig4.push(bytes32(uint256(v)));
sig4.push(r);
sig4.push(s);
wallet.execute(destination, gasLimit, data, sig4);
Assert.equal(recorder.dataLen(), 3);
}
function check_b3_buildHash_testInvalidSigningAccount_useAccount1() public {
// EIP712 Transaction Hash
nonce = 3; // THIS IS AN INVALID NONCE
recordData = "\x19\x01\x01";
data = abi.encodeWithSelector(bytes4(0x7214ae99), address(recorder), recordData);
hash = keccak256(abi.encodePacked(
"\x19\x01",
bytes32(0xb0609d81c5f719d8a516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f2),
keccak256(abi.encode(
bytes32(0x4a0a6d86122c7bd7083e83912c312adabf207e986f1ac10a35dfeb610d28d0b6),
nonce,
destination,
gasLimit,
keccak256(data)
))
));
Account.sign(2, hash);
}
bytes32[] sig5;
function check_b4_testSameWithValidNonce_useAccount1_shouldThrow(uint8 v, bytes32 r, bytes32 s) public {
sig5.push(bytes32(uint256(v)));
sig5.push(r);
sig5.push(s);
wallet.execute(destination, gasLimit, data, sig5);
}
function check_b5_randomCall() public {
address(wallet).call("0x1234");
}
function check_b6_invalidMethod_shouldThrow() public {
wallet.invalidMethod();
}
}
// test interest mechanism
contract test_Basics_2Signatories {
Factory factory = new Factory();
MultisigWallet wallet;
Recorder recorder = new Recorder();
Teller teller = new Teller();
address signer1;
address signer2;
function check_a1_construction_useAccount2() public {
signer2 = msg.sender;
}
function check_a2_construction_useAccount1() public {
signer1 = msg.sender;
wallet = MultisigWallet(factory.deploy2SignerWallet(2, signer1, signer2));
Log.data(address(wallet));
}
function check_a3_canAcceptEther_method_useValue4500() public payable {
address payable addr = address(wallet);
Assert.equal(addr.balance, 0);
addr.transfer(4500);
Assert.equal(addr.balance, 4500);
}
bytes recordData = "\x19\x01";
bytes data = abi.encodeWithSelector(bytes4(0x7214ae99), address(recorder), recordData);
uint256 gasLimit = 600000;
uint256 nonce = 0;
address destination = address(teller);
bytes32 hash;
function check_a4_buildHash_useAccount1() public {
// EIP712 Transaction Hash
hash = keccak256(abi.encodePacked(
"\x19\x01",
bytes32(0xb0609d81c5f719d8a516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f2),
keccak256(abi.encode(
bytes32(0x4a0a6d86122c7bd7083e83912c312adabf207e986f1ac10a35dfeb610d28d0b6),
nonce,
destination,
gasLimit,
keccak256(data)
))
));
Account.sign(1, hash);
Account.sign(2, hash);
}
bytes32[] sig1;
function check_a5_signature_useAccount1(uint8 s1v, bytes32 s1r, bytes32 s1s, uint8 s2v, bytes32 s2r, bytes32 s2s) public {
if (signer1 > signer2) {
sig1.push(bytes32(uint256(s2v)));
sig1.push(s2r);
sig1.push(s2s);
sig1.push(bytes32(uint256(s1v)));
sig1.push(s1r);
sig1.push(s1s);
} else {
sig1.push(bytes32(uint256(s1v)));
sig1.push(s1r);
sig1.push(s1s);
sig1.push(bytes32(uint256(s2v)));
sig1.push(s2r);
sig1.push(s2s);
}
Assert.equal(recorder.dataLen(), 0);
wallet.execute(destination, gasLimit, data, sig1);
Assert.equal(recorder.dataLen(), 2);
}
}
|
EIP712 Transaction Hash
|
function check_b1_buildHash_testSameWithValidNonce_useAccount1() public {
recordData = "\x19\x01\x01";
data = abi.encodeWithSelector(bytes4(0x7214ae99), address(recorder), recordData);
hash = keccak256(abi.encodePacked(
"\x19\x01",
bytes32(0xb0609d81c5f719d8a516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f2),
keccak256(abi.encode(
bytes32(0x4a0a6d86122c7bd7083e83912c312adabf207e986f1ac10a35dfeb610d28d0b6),
nonce,
destination,
gasLimit,
keccak256(data)
))
));
Account.sign(1, hash);
}
bytes32[] sig4;
| 6,460,298 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { LibDiamondCut } from "./diamond/LibDiamondCut.sol";
import { DiamondFacet } from "./diamond/DiamondFacet.sol";
import { OwnershipFacet } from "./diamond/OwnershipFacet.sol";
import { LibDiamondStorage } from "./diamond/LibDiamondStorage.sol";
import { IDiamondCut } from "./diamond/IDiamondCut.sol";
import { IDiamondLoupe } from "./diamond/IDiamondLoupe.sol";
import { IERC165 } from "./diamond/IERC165.sol";
import { LibDiamondStorageDerivaDEX } from "./storage/LibDiamondStorageDerivaDEX.sol";
import { IDDX } from "./tokens/interfaces/IDDX.sol";
/**
* @title DerivaDEX
* @author DerivaDEX
* @notice This is the diamond for DerivaDEX. All current
* and future logic runs by way of this contract.
* @dev This diamond implements the Diamond Standard (EIP #2535).
*/
contract DerivaDEX {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @notice This constructor initializes the upgrade machinery (as
* per the Diamond Standard), sets the admin of the proxy
* to be the deploying address (very temporary), and sets
* the native DDX governance/operational token.
* @param _ddxToken The native DDX token address.
*/
constructor(IDDX _ddxToken) public {
LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
// Temporarily set admin to the deploying address to facilitate
// adding the Diamond functions
dsDerivaDEX.admin = msg.sender;
// Set DDX token address for token logic in facet contracts
require(address(_ddxToken) != address(0), "DerivaDEX: ddx token is zero address.");
dsDerivaDEX.ddxToken = _ddxToken;
emit OwnershipTransferred(address(0), msg.sender);
// Create DiamondFacet contract -
// implements DiamondCut interface and DiamondLoupe interface
DiamondFacet diamondFacet = new DiamondFacet();
// Create OwnershipFacet contract which implements ownership
// functions and supportsInterface function
OwnershipFacet ownershipFacet = new OwnershipFacet();
IDiamondCut.FacetCut[] memory diamondCut = new IDiamondCut.FacetCut[](2);
// adding diamondCut function and diamond loupe functions
diamondCut[0].facetAddress = address(diamondFacet);
diamondCut[0].action = IDiamondCut.FacetCutAction.Add;
diamondCut[0].functionSelectors = new bytes4[](6);
diamondCut[0].functionSelectors[0] = DiamondFacet.diamondCut.selector;
diamondCut[0].functionSelectors[1] = DiamondFacet.facetFunctionSelectors.selector;
diamondCut[0].functionSelectors[2] = DiamondFacet.facets.selector;
diamondCut[0].functionSelectors[3] = DiamondFacet.facetAddress.selector;
diamondCut[0].functionSelectors[4] = DiamondFacet.facetAddresses.selector;
diamondCut[0].functionSelectors[5] = DiamondFacet.supportsInterface.selector;
// adding ownership functions
diamondCut[1].facetAddress = address(ownershipFacet);
diamondCut[1].action = IDiamondCut.FacetCutAction.Add;
diamondCut[1].functionSelectors = new bytes4[](2);
diamondCut[1].functionSelectors[0] = OwnershipFacet.transferOwnershipToSelf.selector;
diamondCut[1].functionSelectors[1] = OwnershipFacet.getAdmin.selector;
// execute internal diamondCut function to add functions
LibDiamondCut.diamondCut(diamondCut, address(0), new bytes(0));
// adding ERC165 data
ds.supportedInterfaces[IERC165.supportsInterface.selector] = true;
ds.supportedInterfaces[IDiamondCut.diamondCut.selector] = true;
bytes4 interfaceID =
IDiamondLoupe.facets.selector ^
IDiamondLoupe.facetFunctionSelectors.selector ^
IDiamondLoupe.facetAddresses.selector ^
IDiamondLoupe.facetAddress.selector;
ds.supportedInterfaces[interfaceID] = true;
}
// TODO(jalextowle): Remove this linter directive when
// https://github.com/protofire/solhint/issues/248 is merged and released.
/* solhint-disable ordering */
receive() external payable {
revert("DerivaDEX does not directly accept ether.");
}
// Finds facet for function that is called and executes the
// function if it is found and returns any value.
fallback() external payable {
LibDiamondStorage.DiamondStorage storage ds;
bytes32 position = LibDiamondStorage.DIAMOND_STORAGE_POSITION;
assembly {
ds_slot := position
}
address facet = ds.selectorToFacetAndPosition[msg.sig].facetAddress;
require(facet != address(0), "Function does not exist.");
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(0, 0, size)
switch result
case 0 {
revert(0, size)
}
default {
return(0, size)
}
}
}
/* solhint-enable ordering */
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
*
* Implementation of internal diamondCut function.
/******************************************************************************/
import "./LibDiamondStorage.sol";
import "./IDiamondCut.sol";
library LibDiamondCut {
event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);
// Internal function version of diamondCut
// This code is almost the same as the external diamondCut,
// except it is using 'FacetCut[] memory _diamondCut' instead of
// 'FacetCut[] calldata _diamondCut'.
// The code is duplicated to prevent copying calldata to memory which
// causes an error for a two dimensional array.
function diamondCut(
IDiamondCut.FacetCut[] memory _diamondCut,
address _init,
bytes memory _calldata
) internal {
require(_diamondCut.length > 0, "LibDiamondCut: No facets to cut");
for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
addReplaceRemoveFacetSelectors(
_diamondCut[facetIndex].facetAddress,
_diamondCut[facetIndex].action,
_diamondCut[facetIndex].functionSelectors
);
}
emit DiamondCut(_diamondCut, _init, _calldata);
initializeDiamondCut(_init, _calldata);
}
function addReplaceRemoveFacetSelectors(
address _newFacetAddress,
IDiamondCut.FacetCutAction _action,
bytes4[] memory _selectors
) internal {
LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
// add or replace functions
if (_newFacetAddress != address(0)) {
uint256 facetAddressPosition = ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition;
// add new facet address if it does not exist
if (
facetAddressPosition == 0 && ds.facetFunctionSelectors[_newFacetAddress].functionSelectors.length == 0
) {
ensureHasContractCode(_newFacetAddress, "LibDiamondCut: New facet has no code");
facetAddressPosition = ds.facetAddresses.length;
ds.facetAddresses.push(_newFacetAddress);
ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition = uint16(facetAddressPosition);
}
// add or replace selectors
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
// add
if (_action == IDiamondCut.FacetCutAction.Add) {
require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists");
addSelector(_newFacetAddress, selector);
} else if (_action == IDiamondCut.FacetCutAction.Replace) {
// replace
require(
oldFacetAddress != _newFacetAddress,
"LibDiamondCut: Can't replace function with same function"
);
removeSelector(oldFacetAddress, selector);
addSelector(_newFacetAddress, selector);
} else {
revert("LibDiamondCut: Incorrect FacetCutAction");
}
}
} else {
require(
_action == IDiamondCut.FacetCutAction.Remove,
"LibDiamondCut: action not set to FacetCutAction.Remove"
);
// remove selectors
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
removeSelector(ds.selectorToFacetAndPosition[selector].facetAddress, selector);
}
}
}
function addSelector(address _newFacet, bytes4 _selector) internal {
LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
uint256 selectorPosition = ds.facetFunctionSelectors[_newFacet].functionSelectors.length;
ds.facetFunctionSelectors[_newFacet].functionSelectors.push(_selector);
ds.selectorToFacetAndPosition[_selector].facetAddress = _newFacet;
ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = uint16(selectorPosition);
}
function removeSelector(address _oldFacetAddress, bytes4 _selector) internal {
LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
require(_oldFacetAddress != address(0), "LibDiamondCut: Can't remove or replace function that doesn't exist");
// replace selector with last selector, then delete last selector
uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition;
uint256 lastSelectorPosition = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.length - 1;
bytes4 lastSelector = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[lastSelectorPosition];
// if not the same then replace _selector with lastSelector
if (lastSelector != _selector) {
ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[selectorPosition] = lastSelector;
ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint16(selectorPosition);
}
// delete the last selector
ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.pop();
delete ds.selectorToFacetAndPosition[_selector];
// if no more selectors for facet address then delete the facet address
if (lastSelectorPosition == 0) {
// replace facet address with last facet address and delete last facet address
uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1;
address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition];
uint256 facetAddressPosition = ds.facetFunctionSelectors[_oldFacetAddress].facetAddressPosition;
if (_oldFacetAddress != lastFacetAddress) {
ds.facetAddresses[facetAddressPosition] = lastFacetAddress;
ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = uint16(facetAddressPosition);
}
ds.facetAddresses.pop();
delete ds.facetFunctionSelectors[_oldFacetAddress];
}
}
function initializeDiamondCut(address _init, bytes memory _calldata) internal {
if (_init == address(0)) {
require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty");
} else {
require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)");
if (_init != address(this)) {
LibDiamondCut.ensureHasContractCode(_init, "LibDiamondCut: _init address has no code");
}
(bool success, bytes memory error) = _init.delegatecall(_calldata);
if (!success) {
if (error.length > 0) {
// bubble up the error
revert(string(error));
} else {
revert("LibDiamondCut: _init function reverted");
}
}
}
}
function ensureHasContractCode(address _contract, string memory _errorMessage) internal view {
uint256 contractSize;
assembly {
contractSize := extcodesize(_contract)
}
require(contractSize > 0, _errorMessage);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
*
* Implementation of diamondCut external function and DiamondLoupe interface.
/******************************************************************************/
import "./LibDiamondStorage.sol";
import "./LibDiamondCut.sol";
import "../storage/LibDiamondStorageDerivaDEX.sol";
import "./IDiamondCut.sol";
import "./IDiamondLoupe.sol";
import "./IERC165.sol";
contract DiamondFacet is IDiamondCut, IDiamondLoupe, IERC165 {
// Standard diamondCut external function
/// @notice Add/replace/remove any number of functions and optionally execute
/// a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external override {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
require(msg.sender == dsDerivaDEX.admin, "DiamondFacet: Must own the contract");
require(_diamondCut.length > 0, "DiamondFacet: No facets to cut");
for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
LibDiamondCut.addReplaceRemoveFacetSelectors(
_diamondCut[facetIndex].facetAddress,
_diamondCut[facetIndex].action,
_diamondCut[facetIndex].functionSelectors
);
}
emit DiamondCut(_diamondCut, _init, _calldata);
LibDiamondCut.initializeDiamondCut(_init, _calldata);
}
// Diamond Loupe Functions
////////////////////////////////////////////////////////////////////
/// These functions are expected to be called frequently by tools.
//
// struct Facet {
// address facetAddress;
// bytes4[] functionSelectors;
// }
//
/// @notice Gets all facets and their selectors.
/// @return facets_ Facet
function facets() external view override returns (Facet[] memory facets_) {
LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
uint256 numFacets = ds.facetAddresses.length;
facets_ = new Facet[](numFacets);
for (uint256 i; i < numFacets; i++) {
address facetAddress_ = ds.facetAddresses[i];
facets_[i].facetAddress = facetAddress_;
facets_[i].functionSelectors = ds.facetFunctionSelectors[facetAddress_].functionSelectors;
}
}
/// @notice Gets all the function selectors provided by a facet.
/// @param _facet The facet address.
/// @return facetFunctionSelectors_
function facetFunctionSelectors(address _facet)
external
view
override
returns (bytes4[] memory facetFunctionSelectors_)
{
LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
facetFunctionSelectors_ = ds.facetFunctionSelectors[_facet].functionSelectors;
}
/// @notice Get all the facet addresses used by a diamond.
/// @return facetAddresses_
function facetAddresses() external view override returns (address[] memory facetAddresses_) {
LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
facetAddresses_ = ds.facetAddresses;
}
/// @notice Gets the facet that supports the given selector.
/// @dev If facet is not found return address(0).
/// @param _functionSelector The function selector.
/// @return facetAddress_ The facet address.
function facetAddress(bytes4 _functionSelector) external view override returns (address facetAddress_) {
LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
facetAddress_ = ds.selectorToFacetAndPosition[_functionSelector].facetAddress;
}
// This implements ERC-165.
function supportsInterface(bytes4 _interfaceId) external view override returns (bool) {
LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
return ds.supportedInterfaces[_interfaceId];
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import { LibDiamondStorageDerivaDEX } from "../storage/LibDiamondStorageDerivaDEX.sol";
import { LibDiamondStorage } from "../diamond/LibDiamondStorage.sol";
import { IERC165 } from "./IERC165.sol";
contract OwnershipFacet {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @notice This function transfers ownership to self. This is done
* so that we can ensure upgrades (using diamondCut) and
* various other critical parameter changing scenarios
* can only be done via governance (a facet).
*/
function transferOwnershipToSelf() external {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
require(msg.sender == dsDerivaDEX.admin, "Not authorized");
dsDerivaDEX.admin = address(this);
emit OwnershipTransferred(msg.sender, address(this));
}
/**
* @notice This gets the admin for the diamond.
* @return Admin address.
*/
function getAdmin() external view returns (address) {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
return dsDerivaDEX.admin;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
/******************************************************************************/
library LibDiamondStorage {
struct FacetAddressAndPosition {
address facetAddress;
uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array
}
struct FacetFunctionSelectors {
bytes4[] functionSelectors;
uint16 facetAddressPosition; // position of facetAddress in facetAddresses array
}
struct DiamondStorage {
// maps function selector to the facet address and
// the position of the facet address in the facetAddresses array
// and the position of the selector in the facetSelectors.selectors array
mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition;
// maps facet addresses to function selectors
mapping(address => FacetFunctionSelectors) facetFunctionSelectors;
// facet addresses
address[] facetAddresses;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
}
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds_slot := position
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
/******************************************************************************/
interface IDiamondCut {
enum FacetCutAction { Add, Replace, Remove }
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
/// @notice Add/replace/remove any number of functions and optionally execute
/// a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
/******************************************************************************/
import "./IDiamondCut.sol";
// A loupe is a small magnifying glass used to look at diamonds.
// These functions look at diamonds
interface IDiamondLoupe {
/// These functions are expected to be called frequently
/// by tools.
struct Facet {
address facetAddress;
bytes4[] functionSelectors;
}
/// @notice Gets all facet addresses and their four byte function selectors.
/// @return facets_ Facet
function facets() external view returns (Facet[] memory facets_);
/// @notice Gets all the function selectors supported by a specific facet.
/// @param _facet The facet address.
/// @return facetFunctionSelectors_
function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_);
/// @notice Get all the facet addresses used by a diamond.
/// @return facetAddresses_
function facetAddresses() external view returns (address[] memory facetAddresses_);
/// @notice Gets the facet that supports the given selector.
/// @dev If facet is not found return address(0).
/// @param _functionSelector The function selector.
/// @return facetAddress_ The facet address.
function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { IDDX } from "../tokens/interfaces/IDDX.sol";
library LibDiamondStorageDerivaDEX {
struct DiamondStorageDerivaDEX {
string name;
address admin;
IDDX ddxToken;
}
bytes32 constant DIAMOND_STORAGE_POSITION_DERIVADEX =
keccak256("diamond.standard.diamond.storage.DerivaDEX.DerivaDEX");
function diamondStorageDerivaDEX() internal pure returns (DiamondStorageDerivaDEX storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION_DERIVADEX;
assembly {
ds_slot := position
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IDDX {
function transfer(address _recipient, uint256 _amount) external returns (bool);
function mint(address _recipient, uint256 _amount) external;
function delegate(address _delegatee) external;
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) external returns (bool);
function approve(address _spender, uint256 _amount) external returns (bool);
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96);
function totalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { IDDX } from "./interfaces/IDDX.sol";
/**
* @title DDXWalletCloneable
* @author DerivaDEX
* @notice This is a cloneable on-chain DDX wallet that holds a trader's
* stakes and issued rewards.
*/
contract DDXWalletCloneable {
// Whether contract has already been initialized once before
bool initialized;
/**
* @notice This function initializes the on-chain DDX wallet
* for a given trader.
* @param _trader Trader address.
* @param _ddxToken DDX token address.
* @param _derivaDEX DerivaDEX Proxy address.
*/
function initialize(
address _trader,
IDDX _ddxToken,
address _derivaDEX
) external {
// Prevent initializing more than once
require(!initialized, "DDXWalletCloneable: already init.");
initialized = true;
// Automatically delegate the holdings of this contract/wallet
// back to the trader.
_ddxToken.delegate(_trader);
// Approve the DerivaDEX Proxy contract for unlimited transfers
_ddxToken.approve(_derivaDEX, uint96(-1));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import { SafeMath96 } from "../../libs/SafeMath96.sol";
import { TraderDefs } from "../../libs/defs/TraderDefs.sol";
import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol";
import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol";
import { DDXWalletCloneable } from "../../tokens/DDXWalletCloneable.sol";
import { IDDX } from "../../tokens/interfaces/IDDX.sol";
import { IDDXWalletCloneable } from "../../tokens/interfaces/IDDXWalletCloneable.sol";
import { LibTraderInternal } from "./LibTraderInternal.sol";
/**
* @title Trader
* @author DerivaDEX
* @notice This is a facet to the DerivaDEX proxy contract that handles
* the logic pertaining to traders - staking DDX, withdrawing
* DDX, receiving DDX rewards, etc.
*/
contract Trader {
using SafeMath96 for uint96;
using SafeMath for uint256;
using SafeERC20 for IERC20;
event RewardCliffSet(bool rewardCliffSet);
event DDXRewardIssued(address trader, uint96 amount);
/**
* @notice Limits functions to only be called via governance.
*/
modifier onlyAdmin {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
require(msg.sender == dsDerivaDEX.admin, "Trader: must be called by Gov.");
_;
}
/**
* @notice Limits functions to only be called post reward cliff.
*/
modifier postRewardCliff {
LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader();
require(dsTrader.rewardCliff, "Trader: prior to reward cliff.");
_;
}
/**
* @notice This function initializes the state with some critical
* information, including the on-chain wallet cloneable
* contract address. This can only be called via governance.
* @dev This function is best called as a parameter to the
* diamond cut function. This is removed prior to the selectors
* being added to the diamond, meaning it cannot be called
* again.
* @dev This function is best called as a parameter to the
* diamond cut function. This is removed prior to the selectors
* being added to the diamond, meaning it cannot be called
* again.
*/
function initialize(IDDXWalletCloneable _ddxWalletCloneable) external onlyAdmin {
LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader();
// Set the on-chain DDX wallet cloneable contract address
dsTrader.ddxWalletCloneable = _ddxWalletCloneable;
}
/**
* @notice This function sets the reward cliff.
* @param _rewardCliff Reward cliff.
*/
function setRewardCliff(bool _rewardCliff) external onlyAdmin {
LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader();
// Set the reward cliff (boolean value)
dsTrader.rewardCliff = _rewardCliff;
emit RewardCliffSet(_rewardCliff);
}
/**
* @notice This function issues DDX rewards to a trader. It can
* only be called via governance.
* @param _amount DDX tokens to be rewarded.
* @param _trader Trader recipient address.
*/
function issueDDXReward(uint96 _amount, address _trader) external onlyAdmin {
// Call the internal function to issue DDX rewards. This
// internal function is shareable with other facets that import
// the LibTraderInternal library.
LibTraderInternal.issueDDXReward(_amount, _trader);
}
/**
* @notice This function issues DDX rewards to an external address.
* It can only be called via governance.
* @param _amount DDX tokens to be rewarded.
* @param _recipient External recipient address.
*/
function issueDDXToRecipient(uint96 _amount, address _recipient) external onlyAdmin {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
// Transfer DDX from trader to trader's on-chain wallet
dsDerivaDEX.ddxToken.mint(_recipient, _amount);
emit DDXRewardIssued(_recipient, _amount);
}
/**
* @notice This function lets traders take DDX from their wallet
* into their on-chain DDX wallet. It's important to note
* that any DDX staked from the trader to this wallet
* delegates the voting rights of that stake back to the
* user. To be more explicit, if Alice's personal wallet is
* delegating to Bob, and she now stakes a portion of her
* DDX into this on-chain DDX wallet of hers, those tokens
* will now count towards her voting power, not Bob's, since
* her on-chain wallet is automatically delegating back to
* her.
* @param _amount The DDX tokens to be staked.
*/
function stakeDDXFromTrader(uint96 _amount) external {
transferDDXToWallet(msg.sender, _amount);
}
/**
* @notice This function lets traders send DDX from their wallet
* into another trader's on-chain DDX wallet. It's
* important to note that any DDX staked to this wallet
* delegates the voting rights of that stake back to the
* user.
* @param _trader Trader address to receive DDX (inside their
* wallet, which will be created if it does not already
* exist).
* @param _amount The DDX tokens to be staked.
*/
function sendDDXFromTraderToTraderWallet(address _trader, uint96 _amount) external {
transferDDXToWallet(_trader, _amount);
}
/**
* @notice This function lets traders withdraw DDX from their
* on-chain DDX wallet to their personal wallet. It's
* important to note that the voting rights for any DDX
* withdrawn are returned back to the delegatee of the
* user's personal wallet. To be more explicit, if Alice is
* personal wallet is delegating to Bob, and she now
* withdraws a portion of her DDX from this on-chain DDX
* wallet of hers, those tokens will now count towards Bob's
* voting power, not her's, since her on-chain wallet is
* automatically delegating back to her, but her personal
* wallet is delegating to Bob. Withdrawals can only happen
* when the governance cliff is lifted.
* @param _amount The DDX tokens to be withdrawn.
*/
function withdrawDDXToTrader(uint96 _amount) external postRewardCliff {
LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader();
TraderDefs.Trader storage trader = dsTrader.traders[msg.sender];
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
// Subtract trader's DDX balance in the contract
trader.ddxBalance = trader.ddxBalance.sub96(_amount);
// Transfer DDX from trader's on-chain wallet to the trader
dsDerivaDEX.ddxToken.transferFrom(trader.ddxWalletContract, msg.sender, _amount);
}
/**
* @notice This function gets the attributes for a given trader.
* @param _trader Trader address.
*/
function getTrader(address _trader) external view returns (TraderDefs.Trader memory) {
LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader();
return dsTrader.traders[_trader];
}
/**
* @notice This function transfers DDX from the sender
* to another trader's DDX wallet.
* @param _trader Trader address' DDX wallet address to transfer
* into.
* @param _amount Amount of DDX to transfer.
*/
function transferDDXToWallet(address _trader, uint96 _amount) internal {
LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader();
TraderDefs.Trader storage trader = dsTrader.traders[_trader];
// If trader does not have a DDX on-chain wallet yet, create one
if (trader.ddxWalletContract == address(0)) {
LibTraderInternal.createDDXWallet(_trader);
}
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
// Add trader's DDX balance in the contract
trader.ddxBalance = trader.ddxBalance.add96(_amount);
// Transfer DDX from trader to trader's on-chain wallet
dsDerivaDEX.ddxToken.transferFrom(msg.sender, trader.ddxWalletContract, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath96 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add96(uint96 a, uint96 b) internal pure returns (uint96) {
uint96 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 sub96(uint96 a, uint96 b) internal pure returns (uint96) {
return sub96(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 sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
uint96 c = a - b;
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/**
* @title TraderDefs
* @author DerivaDEX
*
* This library contains the common structs and enums pertaining to
* traders.
*/
library TraderDefs {
// Consists of trader attributes, including the DDX balance and
// the onchain DDX wallet contract address
struct Trader {
uint96 ddxBalance;
address ddxWalletContract;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { TraderDefs } from "../libs/defs/TraderDefs.sol";
import { IDDXWalletCloneable } from "../tokens/interfaces/IDDXWalletCloneable.sol";
library LibDiamondStorageTrader {
struct DiamondStorageTrader {
mapping(address => TraderDefs.Trader) traders;
bool rewardCliff;
IDDXWalletCloneable ddxWalletCloneable;
}
bytes32 constant DIAMOND_STORAGE_POSITION_TRADER = keccak256("diamond.standard.diamond.storage.DerivaDEX.Trader");
function diamondStorageTrader() internal pure returns (DiamondStorageTrader storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION_TRADER;
assembly {
ds_slot := position
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import { IDDX } from "./IDDX.sol";
interface IDDXWalletCloneable {
function initialize(
address _trader,
IDDX _ddxToken,
address _derivaDEX
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import { LibClone } from "../../libs/LibClone.sol";
import { SafeMath96 } from "../../libs/SafeMath96.sol";
import { TraderDefs } from "../../libs/defs/TraderDefs.sol";
import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol";
import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol";
import { IDDX } from "../../tokens/interfaces/IDDX.sol";
import { IDDXWalletCloneable } from "../../tokens/interfaces/IDDXWalletCloneable.sol";
/**
* @title TraderInternalLib
* @author DerivaDEX
* @notice This is a library of internal functions mainly defined in
* the Trader facet, but used in other facets.
*/
library LibTraderInternal {
using SafeMath96 for uint96;
using SafeMath for uint256;
using SafeERC20 for IERC20;
event DDXRewardIssued(address trader, uint96 amount);
/**
* @notice This function creates a new DDX wallet for a trader.
* @param _trader Trader address.
*/
function createDDXWallet(address _trader) internal {
LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader();
// Leveraging the minimal proxy contract/clone factory pattern
// as described here (https://eips.ethereum.org/EIPS/eip-1167)
IDDXWalletCloneable ddxWallet = IDDXWalletCloneable(LibClone.createClone(address(dsTrader.ddxWalletCloneable)));
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
// Cloneable contracts have no constructor, so instead we use
// an initialize function. This initialize delegates this
// on-chain DDX wallet back to the trader and sets the allowance
// for the DerivaDEX Proxy contract to be unlimited.
ddxWallet.initialize(_trader, dsDerivaDEX.ddxToken, address(this));
// Store the on-chain wallet address in the trader's storage
dsTrader.traders[_trader].ddxWalletContract = address(ddxWallet);
}
/**
* @notice This function issues DDX rewards to a trader. It can be
* called by any facet part of the diamond.
* @param _amount DDX tokens to be rewarded.
* @param _trader Trader address.
*/
function issueDDXReward(uint96 _amount, address _trader) internal {
LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader();
TraderDefs.Trader storage trader = dsTrader.traders[_trader];
// If trader does not have a DDX on-chain wallet yet, create one
if (trader.ddxWalletContract == address(0)) {
createDDXWallet(_trader);
}
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
// Add trader's DDX balance in the contract
trader.ddxBalance = trader.ddxBalance.add96(_amount);
// Transfer DDX from trader to trader's on-chain wallet
dsDerivaDEX.ddxToken.mint(trader.ddxWalletContract, _amount);
emit DDXRewardIssued(_trader, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
library LibClone {
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
function isClone(address target, address query) internal view returns (bool result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000)
mstore(add(clone, 0xa), targetBytes)
mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
result := and(eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { Math } from "openzeppelin-solidity/contracts/math/Math.sol";
import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import { SafeMath32 } from "../../libs/SafeMath32.sol";
import { SafeMath96 } from "../../libs/SafeMath96.sol";
import { MathHelpers } from "../../libs/MathHelpers.sol";
import { InsuranceFundDefs } from "../../libs/defs/InsuranceFundDefs.sol";
import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol";
import { LibDiamondStorageInsuranceFund } from "../../storage/LibDiamondStorageInsuranceFund.sol";
import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol";
import { LibDiamondStoragePause } from "../../storage/LibDiamondStoragePause.sol";
import { IDDX } from "../../tokens/interfaces/IDDX.sol";
import { LibTraderInternal } from "../trader/LibTraderInternal.sol";
import { IAToken } from "../interfaces/IAToken.sol";
import { IComptroller } from "../interfaces/IComptroller.sol";
import { ICToken } from "../interfaces/ICToken.sol";
import { IDIFundToken } from "../../tokens/interfaces/IDIFundToken.sol";
import { IDIFundTokenFactory } from "../../tokens/interfaces/IDIFundTokenFactory.sol";
interface IERCCustom {
function decimals() external view returns (uint8);
}
/**
* @title InsuranceFund
* @author DerivaDEX
* @notice This is a facet to the DerivaDEX proxy contract that handles
* the logic pertaining to insurance mining - staking directly
* into the insurance fund and receiving a DDX issuance to be
* used in governance/operations.
* @dev This facet at the moment only handles insurance mining. It can
* and will grow to handle the remaining functions of the insurance
* fund, such as receiving quote-denominated fees and liquidation
* spreads, among others. The Diamond storage will only be
* affected when facet functions are called via the proxy
* contract, no checks are necessary.
*/
contract InsuranceFund {
using SafeMath32 for uint32;
using SafeMath96 for uint96;
using SafeMath for uint96;
using SafeMath for uint256;
using MathHelpers for uint32;
using MathHelpers for uint96;
using MathHelpers for uint224;
using MathHelpers for uint256;
using SafeERC20 for IERC20;
// Compound-related constant variables
// kovan: 0x5eAe89DC1C671724A672ff0630122ee834098657
IComptroller public constant COMPTROLLER = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
// kovan: 0x61460874a7196d6a22D1eE4922473664b3E95270
IERC20 public constant COMP_TOKEN = IERC20(0xc00e94Cb662C3520282E6f5717214004A7f26888);
event InsuranceFundInitialized(
uint32 interval,
uint32 withdrawalFactor,
uint96 mineRatePerBlock,
uint96 advanceIntervalReward,
uint256 miningFinalBlockNumber
);
event InsuranceFundCollateralAdded(
bytes32 collateralName,
address underlyingToken,
address collateralToken,
InsuranceFundDefs.Flavor flavor
);
event StakedToInsuranceFund(address staker, uint96 amount, bytes32 collateralName);
event WithdrawnFromInsuranceFund(address withdrawer, uint96 amount, bytes32 collateralName);
event AdvancedOtherRewards(address intervalAdvancer, uint96 advanceReward);
event InsuranceMineRewardsClaimed(address claimant, uint96 minedAmount);
event MineRatePerBlockSet(uint96 mineRatePerBlock);
event AdvanceIntervalRewardSet(uint96 advanceIntervalReward);
event WithdrawalFactorSet(uint32 withdrawalFactor);
event InsuranceMiningExtended(uint256 miningFinalBlockNumber);
/**
* @notice Limits functions to only be called via governance.
*/
modifier onlyAdmin {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
require(msg.sender == dsDerivaDEX.admin, "IFund: must be called by Gov.");
_;
}
/**
* @notice Limits functions to only be called while insurance
* mining is ongoing.
*/
modifier insuranceMiningOngoing {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
require(block.number < dsInsuranceFund.miningFinalBlockNumber, "IFund: mining ended.");
_;
}
/**
* @notice Limits functions to only be called while other
* rewards checkpointing is ongoing.
*/
modifier otherRewardsOngoing {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
require(
dsInsuranceFund.otherRewardsCheckpointBlock < dsInsuranceFund.miningFinalBlockNumber,
"IFund: other rewards checkpointing ended."
);
_;
}
/**
* @notice Limits functions to only be called via governance.
*/
modifier isNotPaused {
LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause();
require(!dsPause.isPaused, "IFund: paused.");
_;
}
/**
* @notice This function initializes the state with some critical
* information. This can only be called via governance.
* @dev This function is best called as a parameter to the
* diamond cut function. This is removed prior to the selectors
* being added to the diamond, meaning it cannot be called
* again.
* @param _interval The interval length (blocks) for other rewards
* claiming checkpoints (i.e. COMP and extra aTokens).
* @param _withdrawalFactor Specifies the withdrawal fee if users
* redeem their insurance tokens.
* @param _mineRatePerBlock The DDX tokens to be mined each interval
* for insurance mining.
* @param _advanceIntervalReward DDX reward for participant who
* advances the insurance mining interval.
* @param _insuranceMiningLength Insurance mining length (blocks).
*/
function initialize(
uint32 _interval,
uint32 _withdrawalFactor,
uint96 _mineRatePerBlock,
uint96 _advanceIntervalReward,
uint256 _insuranceMiningLength,
IDIFundTokenFactory _diFundTokenFactory
) external onlyAdmin {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
// Set the interval for other rewards claiming checkpoints
// (i.e. COMP and aTokens that accrue to the contract)
// (e.g. 40320 ~ 1 week = 7 * 24 * 60 * 60 / 15 blocks)
dsInsuranceFund.interval = _interval;
// Keep track of the block number for other rewards checkpoint,
// which is initialized to the block number the insurance fund
// facet is added to the diamond
dsInsuranceFund.otherRewardsCheckpointBlock = block.number;
// Set the withdrawal factor, capped at 1000, implying 0% fee
require(_withdrawalFactor <= 1000, "IFund: withdrawal fee too high.");
// Set withdrawal ratio, which will be used with a 1e3 scaling
// factor, meaning a value of 995 implies a withdrawal fee of
// 0.5% since 995/1e3 => 0.995
dsInsuranceFund.withdrawalFactor = _withdrawalFactor;
// Set the insurance mine rate per block.
// (e.g. 1.189e18 ~ 5% liquidity mine (50mm tokens))
dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock;
// Incentive to advance the other rewards interval
// (e.g. 100e18 = 100 DDX)
dsInsuranceFund.advanceIntervalReward = _advanceIntervalReward;
// Set the final block number for insurance mining
dsInsuranceFund.miningFinalBlockNumber = block.number.add(_insuranceMiningLength);
// DIFundToken factory to deploy DerivaDEX Insurance Fund token
// contracts pertaining to each supported collateral
dsInsuranceFund.diFundTokenFactory = _diFundTokenFactory;
// Initialize the DDX market state index and block. These values
// are critical for computing the DDX continuously issued per
// block
dsInsuranceFund.ddxMarketState.index = 1e36;
dsInsuranceFund.ddxMarketState.block = block.number.safe32("IFund: exceeds 32 bits");
emit InsuranceFundInitialized(
_interval,
_withdrawalFactor,
_mineRatePerBlock,
_advanceIntervalReward,
dsInsuranceFund.miningFinalBlockNumber
);
}
/**
* @notice This function sets the DDX mine rate per block.
* @param _mineRatePerBlock The DDX tokens mine rate per block.
*/
function setMineRatePerBlock(uint96 _mineRatePerBlock) external onlyAdmin insuranceMiningOngoing isNotPaused {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
// NOTE(jalextowle): We must update the DDX Market State prior to
// changing the mine rate per block in order to lock in earned rewards
// for insurance mining participants.
updateDDXMarketState(dsInsuranceFund);
require(_mineRatePerBlock != dsInsuranceFund.mineRatePerBlock, "IFund: same as current value.");
// Set the insurance mine rate per block.
// (e.g. 1.189e18 ~ 5% liquidity mine (50mm tokens))
dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock;
emit MineRatePerBlockSet(_mineRatePerBlock);
}
/**
* @notice This function sets the advance interval reward.
* @param _advanceIntervalReward DDX reward for advancing interval.
*/
function setAdvanceIntervalReward(uint96 _advanceIntervalReward)
external
onlyAdmin
insuranceMiningOngoing
isNotPaused
{
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
require(_advanceIntervalReward != dsInsuranceFund.advanceIntervalReward, "IFund: same as current value.");
// Set the advance interval reward
dsInsuranceFund.advanceIntervalReward = _advanceIntervalReward;
emit AdvanceIntervalRewardSet(_advanceIntervalReward);
}
/**
* @notice This function sets the withdrawal factor.
* @param _withdrawalFactor Withdrawal factor.
*/
function setWithdrawalFactor(uint32 _withdrawalFactor) external onlyAdmin insuranceMiningOngoing isNotPaused {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
require(_withdrawalFactor != dsInsuranceFund.withdrawalFactor, "IFund: same as current value.");
// Set the withdrawal factor, capped at 1000, implying 0% fee
require(dsInsuranceFund.withdrawalFactor <= 1000, "IFund: withdrawal fee too high.");
dsInsuranceFund.withdrawalFactor = _withdrawalFactor;
emit WithdrawalFactorSet(_withdrawalFactor);
}
/**
* @notice This function extends insurance mining.
* @param _insuranceMiningExtension Insurance mining extension
* (blocks).
*/
function extendInsuranceMining(uint256 _insuranceMiningExtension)
external
onlyAdmin
insuranceMiningOngoing
isNotPaused
{
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
require(_insuranceMiningExtension != 0, "IFund: invalid extension.");
// Extend the mining final block number
dsInsuranceFund.miningFinalBlockNumber = dsInsuranceFund.miningFinalBlockNumber.add(_insuranceMiningExtension);
emit InsuranceMiningExtended(dsInsuranceFund.miningFinalBlockNumber);
}
/**
* @notice This function adds a new supported collateral type that
* can be staked to the insurance fund. It can only
* be called via governance.
* @dev For vanilla contracts (e.g. USDT, USDC, etc.), the
* underlying token equals address(0).
* @param _collateralName Name of collateral.
* @param _collateralSymbol Symbol of collateral.
* @param _underlyingToken Deployed address of underlying token.
* @param _collateralToken Deployed address of collateral token.
* @param _flavor Collateral flavor (Vanilla, Compound, Aave, etc.).
*/
function addInsuranceFundCollateral(
string memory _collateralName,
string memory _collateralSymbol,
address _underlyingToken,
address _collateralToken,
InsuranceFundDefs.Flavor _flavor
) external onlyAdmin insuranceMiningOngoing isNotPaused {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
// Obtain bytes32 representation of collateral name
bytes32 result;
assembly {
result := mload(add(_collateralName, 32))
}
// Ensure collateral has not already been added
require(
dsInsuranceFund.stakeCollaterals[result].collateralToken == address(0),
"IFund: collateral already added."
);
require(_collateralToken != address(0), "IFund: collateral address must be non-zero.");
require(!isCollateralTokenPresent(_collateralToken), "IFund: collateral token already present.");
require(_underlyingToken != _collateralToken, "IFund: token addresses are same.");
if (_flavor == InsuranceFundDefs.Flavor.Vanilla) {
// If collateral is of vanilla flavor, there should only be
// a value for collateral token, and underlying token should
// be empty
require(_underlyingToken == address(0), "IFund: underlying address non-zero for Vanilla.");
}
// Add collateral type to storage, including its underlying
// token and collateral token addresses, and its flavor
dsInsuranceFund.stakeCollaterals[result].underlyingToken = _underlyingToken;
dsInsuranceFund.stakeCollaterals[result].collateralToken = _collateralToken;
dsInsuranceFund.stakeCollaterals[result].flavor = _flavor;
// Create a DerivaDEX Insurance Fund token contract associated
// with this supported collateral
dsInsuranceFund.stakeCollaterals[result].diFundToken = IDIFundToken(
dsInsuranceFund.diFundTokenFactory.createNewDIFundToken(
_collateralName,
_collateralSymbol,
IERCCustom(_collateralToken).decimals()
)
);
dsInsuranceFund.collateralNames.push(result);
emit InsuranceFundCollateralAdded(result, _underlyingToken, _collateralToken, _flavor);
}
/**
* @notice This function allows participants to stake a supported
* collateral type to the insurance fund.
* @param _collateralName Name of collateral.
* @param _amount Amount to stake.
*/
function stakeToInsuranceFund(bytes32 _collateralName, uint96 _amount) external insuranceMiningOngoing isNotPaused {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
// Obtain the collateral struct for the collateral type
// participant is staking
InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName];
// Ensure this is a supported collateral type and that the user
// has approved the proxy contract for transfer
require(stakeCollateral.collateralToken != address(0), "IFund: invalid collateral.");
// Ensure non-zero stake amount
require(_amount > 0, "IFund: non-zero amount.");
// Claim DDX for staking user. We do this prior to the stake
// taking effect, thereby preventing someone from being rewarded
// instantly for the stake.
claimDDXFromInsuranceMining(msg.sender);
// Increment the underlying capitalization
stakeCollateral.cap = stakeCollateral.cap.add96(_amount);
// Transfer collateral amount from user to proxy contract
IERC20(stakeCollateral.collateralToken).safeTransferFrom(msg.sender, address(this), _amount);
// Mint DIFund tokens to user
stakeCollateral.diFundToken.mint(msg.sender, _amount);
emit StakedToInsuranceFund(msg.sender, _amount, _collateralName);
}
/**
* @notice This function allows participants to withdraw a supported
* collateral type from the insurance fund.
* @param _collateralName Name of collateral.
* @param _amount Amount to stake.
*/
function withdrawFromInsuranceFund(bytes32 _collateralName, uint96 _amount) external isNotPaused {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
// Obtain the collateral struct for the collateral type
// participant is staking
InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName];
// Ensure this is a supported collateral type and that the user
// has approved the proxy contract for transfer
require(stakeCollateral.collateralToken != address(0), "IFund: invalid collateral.");
// Ensure non-zero withdraw amount
require(_amount > 0, "IFund: non-zero amount.");
// Claim DDX for withdrawing user. We do this prior to the
// redeem taking effect.
claimDDXFromInsuranceMining(msg.sender);
// Determine underlying to transfer based on how much underlying
// can be redeemed given the current underlying capitalization
// and how many DIFund tokens are globally available. This
// theoretically fails in the scenario where globally there are
// 0 insurance fund tokens, however that would mean the user
// also has 0 tokens in their possession, and thus would have
// nothing to be redeemed anyways.
uint96 underlyingToTransferNoFee =
_amount.proportion96(stakeCollateral.cap, stakeCollateral.diFundToken.totalSupply());
uint96 underlyingToTransfer = underlyingToTransferNoFee.proportion96(dsInsuranceFund.withdrawalFactor, 1e3);
// Decrement the capitalization
stakeCollateral.cap = stakeCollateral.cap.sub96(underlyingToTransferNoFee);
// Increment the withdrawal fee cap
stakeCollateral.withdrawalFeeCap = stakeCollateral.withdrawalFeeCap.add96(
underlyingToTransferNoFee.sub96(underlyingToTransfer)
);
// Transfer collateral amount from proxy contract to user
IERC20(stakeCollateral.collateralToken).safeTransfer(msg.sender, underlyingToTransfer);
// Burn DIFund tokens being redeemed from user
stakeCollateral.diFundToken.burnFrom(msg.sender, _amount);
emit WithdrawnFromInsuranceFund(msg.sender, _amount, _collateralName);
}
/**
* @notice Advance other rewards interval
*/
function advanceOtherRewardsInterval() external otherRewardsOngoing isNotPaused {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
// Check if the current block has exceeded the interval bounds,
// allowing for a new other rewards interval to be checkpointed
require(
block.number >= dsInsuranceFund.otherRewardsCheckpointBlock.add(dsInsuranceFund.interval),
"IFund: advance too soon."
);
// Maintain the USD-denominated sum of all Compound-flavor
// assets. This needs to be stored separately than the rest
// due to the way COMP tokens are rewarded to the contract in
// order to properly disseminate to the user.
uint96 normalizedCapCheckpointSumCompound;
// Loop through each of the supported collateral types
for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) {
// Obtain collateral struct under consideration
InsuranceFundDefs.StakeCollateral storage stakeCollateral =
dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]];
if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Compound) {
// If collateral is of type Compound, set the exchange
// rate at this point in time. We do this so later on,
// when claiming rewards, we know the exchange rate
// checkpointed balances should be converted to
// determine the USD-denominated value of holdings
// needed to compute fair share of DDX rewards.
stakeCollateral.exchangeRate = ICToken(stakeCollateral.collateralToken).exchangeRateStored().safe96(
"IFund: amount exceeds 96 bits"
);
// Set checkpoint cap for this Compound flavor
// collateral to handle COMP distribution lookbacks
stakeCollateral.checkpointCap = stakeCollateral.cap;
// Increment the normalized Compound checkpoint cap
// with the USD-denominated value
normalizedCapCheckpointSumCompound = normalizedCapCheckpointSumCompound.add96(
getUnderlyingTokenAmountForCompound(stakeCollateral.cap, stakeCollateral.exchangeRate)
);
} else if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) {
// If collateral is of type Aave, we need to do some
// custom Aave aToken reward distribution. We first
// determine the contract's aToken balance for this
// collateral type and subtract the underlying
// aToken capitalization that are due to users. This
// leaves us with the excess that has been rewarded
// to the contract due to Aave's mechanisms, but
// belong to the users.
uint96 myATokenBalance =
uint96(IAToken(stakeCollateral.collateralToken).balanceOf(address(this)).sub(stakeCollateral.cap));
// Store the aToken yield information
dsInsuranceFund.aTokenYields[dsInsuranceFund.collateralNames[i]] = InsuranceFundDefs
.ExternalYieldCheckpoint({ accrued: myATokenBalance, totalNormalizedCap: 0 });
}
}
// Ensure that the normalized cap sum is non-zero
if (normalizedCapCheckpointSumCompound > 0) {
// If there's Compound-type asset capitalization in the
// system, claim COMP accrued to this contract. This COMP is
// a result of holding all the cToken deposits from users.
// We claim COMP via Compound's Comptroller contract.
COMPTROLLER.claimComp(address(this));
// Obtain contract's balance of COMP
uint96 myCompBalance = COMP_TOKEN.balanceOf(address(this)).safe96("IFund: amount exceeds 96 bits.");
// Store the updated value as the checkpointed COMP yield owed
// for this interval
dsInsuranceFund.compYields = InsuranceFundDefs.ExternalYieldCheckpoint({
accrued: myCompBalance,
totalNormalizedCap: normalizedCapCheckpointSumCompound
});
}
// Set other rewards checkpoint block to current block
dsInsuranceFund.otherRewardsCheckpointBlock = block.number;
// Issue DDX reward to trader's on-chain DDX wallet as an
// incentive to users calling this function
LibTraderInternal.issueDDXReward(dsInsuranceFund.advanceIntervalReward, msg.sender);
emit AdvancedOtherRewards(msg.sender, dsInsuranceFund.advanceIntervalReward);
}
/**
* @notice This function gets some high level insurance mining
* details.
* @return The interval length (blocks) for other rewards
* claiming checkpoints (i.e. COMP and extra aTokens).
* @return Current insurance mine withdrawal factor.
* @return DDX reward for advancing interval.
* @return Total global insurance mined amount in DDX.
* @return Current insurance mine rate per block.
* @return Insurance mining final block number.
* @return DDX market state used for continuous DDX payouts.
* @return Supported collateral names supported.
*/
function getInsuranceMineInfo()
external
view
returns (
uint32,
uint32,
uint96,
uint96,
uint96,
uint256,
InsuranceFundDefs.DDXMarketState memory,
bytes32[] memory
)
{
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
return (
dsInsuranceFund.interval,
dsInsuranceFund.withdrawalFactor,
dsInsuranceFund.advanceIntervalReward,
dsInsuranceFund.minedAmount,
dsInsuranceFund.mineRatePerBlock,
dsInsuranceFund.miningFinalBlockNumber,
dsInsuranceFund.ddxMarketState,
dsInsuranceFund.collateralNames
);
}
/**
* @notice This function gets the current claimant state for a user.
* @param _claimant Claimant address.
* @return Claimant state.
*/
function getDDXClaimantState(address _claimant) external view returns (InsuranceFundDefs.DDXClaimantState memory) {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
return dsInsuranceFund.ddxClaimantState[_claimant];
}
/**
* @notice This function gets a supported collateral type's data,
* including collateral's token addresses, collateral
* flavor/type, current cap and withdrawal amounts, the
* latest checkpointed cap, and exchange rate (for cTokens).
* An interface for the DerivaDEX Insurance Fund token
* corresponding to this collateral is also maintained.
* @param _collateralName Name of collateral.
* @return Stake collateral.
*/
function getStakeCollateralByCollateralName(bytes32 _collateralName)
external
view
returns (InsuranceFundDefs.StakeCollateral memory)
{
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
return dsInsuranceFund.stakeCollaterals[_collateralName];
}
/**
* @notice This function gets unclaimed DDX rewards for a claimant.
* @param _claimant Claimant address.
* @return Unclaimed DDX rewards.
*/
function getUnclaimedDDXRewards(address _claimant) external view returns (uint96) {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
// Number of blocks that have elapsed from the last protocol
// interaction resulting in DDX accrual. If insurance mining
// has ended, we use this as the reference point, so deltaBlocks
// will be 0 from the second time onwards.
uint256 deltaBlocks =
Math.min(block.number, dsInsuranceFund.miningFinalBlockNumber).sub(dsInsuranceFund.ddxMarketState.block);
// Save off last index value
uint256 index = dsInsuranceFund.ddxMarketState.index;
// If number of blocks elapsed and mine rate per block are
// non-zero
if (deltaBlocks > 0 && dsInsuranceFund.mineRatePerBlock > 0) {
// Maintain a running total of USDT-normalized claim tokens
// (i.e. 1e6 multiplier)
uint256 claimTokens;
// Loop through each of the supported collateral types
for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) {
// Obtain the collateral struct for the collateral type
// participant is staking
InsuranceFundDefs.StakeCollateral storage stakeCollateral =
dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]];
// Increment the USDT-normalized claim tokens count with
// the current total supply
claimTokens = claimTokens.add(
getNormalizedCollateralValue(
dsInsuranceFund.collateralNames[i],
stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits")
)
);
}
// Compute DDX accrued during the time elapsed and the
// number of tokens accrued per claim token outstanding
uint256 ddxAccrued = deltaBlocks.mul(dsInsuranceFund.mineRatePerBlock);
uint256 ratio = claimTokens > 0 ? ddxAccrued.mul(1e36).div(claimTokens) : 0;
// Increment the index
index = index.add(ratio);
}
// Obtain the most recent claimant index
uint256 ddxClaimantIndex = dsInsuranceFund.ddxClaimantState[_claimant].index;
// If the claimant index is 0, i.e. it's the user's first time
// interacting with the protocol, initialize it to this starting
// value
if ((ddxClaimantIndex == 0) && (index > 0)) {
ddxClaimantIndex = 1e36;
}
// Maintain a running total of USDT-normalized claimant tokens
// (i.e. 1e6 multiplier)
uint256 claimantTokens;
// Loop through each of the supported collateral types
for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) {
// Obtain the collateral struct for the collateral type
// participant is staking
InsuranceFundDefs.StakeCollateral storage stakeCollateral =
dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]];
// Increment the USDT-normalized claimant tokens count with
// the current balance
claimantTokens = claimantTokens.add(
getNormalizedCollateralValue(
dsInsuranceFund.collateralNames[i],
stakeCollateral.diFundToken.balanceOf(_claimant).safe96("IFund: exceeds 96 bits")
)
);
}
// Compute the unclaimed DDX based on the number of claimant
// tokens and the difference between the user's index and the
// claimant index computed above
return claimantTokens.mul(index.sub(ddxClaimantIndex)).div(1e36).safe96("IFund: exceeds 96 bits");
}
/**
* @notice Calculate DDX accrued by a claimant and possibly transfer
* it to them.
* @param _claimant The address of the claimant.
*/
function claimDDXFromInsuranceMining(address _claimant) public {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
// Update the DDX Market State in order to determine the amount of
// rewards that should be paid to the claimant.
updateDDXMarketState(dsInsuranceFund);
// Obtain the most recent claimant index
uint256 ddxClaimantIndex = dsInsuranceFund.ddxClaimantState[_claimant].index;
dsInsuranceFund.ddxClaimantState[_claimant].index = dsInsuranceFund.ddxMarketState.index;
// If the claimant index is 0, i.e. it's the user's first time
// interacting with the protocol, initialize it to this starting
// value
if ((ddxClaimantIndex == 0) && (dsInsuranceFund.ddxMarketState.index > 0)) {
ddxClaimantIndex = 1e36;
}
// Compute the difference between the latest DDX market state
// index and the claimant's index
uint256 deltaIndex = uint256(dsInsuranceFund.ddxMarketState.index).sub(ddxClaimantIndex);
// Maintain a running total of USDT-normalized claimant tokens
// (i.e. 1e6 multiplier)
uint256 claimantTokens;
// Loop through each of the supported collateral types
for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) {
// Obtain the collateral struct for the collateral type
// participant is staking
InsuranceFundDefs.StakeCollateral storage stakeCollateral =
dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]];
// Increment the USDT-normalized claimant tokens count with
// the current balance
claimantTokens = claimantTokens.add(
getNormalizedCollateralValue(
dsInsuranceFund.collateralNames[i],
stakeCollateral.diFundToken.balanceOf(_claimant).safe96("IFund: exceeds 96 bits")
)
);
}
// Compute the claimed DDX based on the number of claimant
// tokens and the difference between the user's index and the
// claimant index computed above
uint96 claimantDelta = claimantTokens.mul(deltaIndex).div(1e36).safe96("IFund: exceeds 96 bits");
if (claimantDelta != 0) {
// Adjust insurance mined amount
dsInsuranceFund.minedAmount = dsInsuranceFund.minedAmount.add96(claimantDelta);
// Increment the insurance mined claimed DDX for claimant
dsInsuranceFund.ddxClaimantState[_claimant].claimedDDX = dsInsuranceFund.ddxClaimantState[_claimant]
.claimedDDX
.add96(claimantDelta);
// Mint the DDX governance/operational token claimed reward
// from the proxy contract to the participant
LibTraderInternal.issueDDXReward(claimantDelta, _claimant);
}
// Check if COMP or aTokens have not already been claimed
if (dsInsuranceFund.stakerToOtherRewardsClaims[_claimant] < dsInsuranceFund.otherRewardsCheckpointBlock) {
// Record the current block number preventing a user from
// reclaiming the COMP reward unfairly
dsInsuranceFund.stakerToOtherRewardsClaims[_claimant] = block.number;
// Claim COMP and extra aTokens
claimOtherRewardsFromInsuranceMining(_claimant);
}
emit InsuranceMineRewardsClaimed(_claimant, claimantDelta);
}
/**
* @notice Get USDT-normalized collateral token amount.
* @param _collateralName The collateral name.
* @param _value The number of tokens.
*/
function getNormalizedCollateralValue(bytes32 _collateralName, uint96 _value) public view returns (uint96) {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName];
return
(stakeCollateral.flavor != InsuranceFundDefs.Flavor.Compound)
? getUnderlyingTokenAmountForVanilla(_value, stakeCollateral.collateralToken)
: getUnderlyingTokenAmountForCompound(
_value,
ICToken(stakeCollateral.collateralToken).exchangeRateStored()
);
}
/**
* @notice This function gets a participant's current
* USD-normalized/denominated stake and global
* USD-normalized/denominated stake across all supported
* collateral types.
* @param _staker Participant's address.
* @return Current USD redemption value of DIFund tokens staked.
* @return Current USD global cap.
*/
function getCurrentTotalStakes(address _staker) public view returns (uint96, uint96) {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
// Maintain running totals
uint96 normalizedStakerStakeSum;
uint96 normalizedGlobalCapSum;
// Loop through each supported collateral
for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) {
(, , uint96 normalizedStakerStake, uint96 normalizedGlobalCap) =
getCurrentStakeByCollateralNameAndStaker(dsInsuranceFund.collateralNames[i], _staker);
normalizedStakerStakeSum = normalizedStakerStakeSum.add96(normalizedStakerStake);
normalizedGlobalCapSum = normalizedGlobalCapSum.add96(normalizedGlobalCap);
}
return (normalizedStakerStakeSum, normalizedGlobalCapSum);
}
/**
* @notice This function gets a participant's current DIFund token
* holdings and global DIFund token holdings for a
* collateral type and staker, in addition to the
* USD-normalized collateral in the system and the
* redemption value for the staker.
* @param _collateralName Name of collateral.
* @param _staker Participant's address.
* @return DIFund tokens for staker.
* @return DIFund tokens globally.
* @return Redemption value for staker (USD-denominated).
* @return Underlying collateral (USD-denominated) in staking system.
*/
function getCurrentStakeByCollateralNameAndStaker(bytes32 _collateralName, address _staker)
public
view
returns (
uint96,
uint96,
uint96,
uint96
)
{
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName];
// Get DIFund tokens for staker
uint96 stakerStake = stakeCollateral.diFundToken.balanceOf(_staker).safe96("IFund: exceeds 96 bits.");
// Get DIFund tokens globally
uint96 globalCap = stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits.");
// Compute global USD-denominated stake capitalization. This is
// is straightforward for non-Compound assets, but requires
// exchange rate conversion for Compound assets.
uint96 normalizedGlobalCap =
(stakeCollateral.flavor != InsuranceFundDefs.Flavor.Compound)
? getUnderlyingTokenAmountForVanilla(stakeCollateral.cap, stakeCollateral.collateralToken)
: getUnderlyingTokenAmountForCompound(
stakeCollateral.cap,
ICToken(stakeCollateral.collateralToken).exchangeRateStored()
);
// Compute the redemption value (USD-normalized) for staker
// given DIFund token holdings
uint96 normalizedStakerStake = globalCap > 0 ? normalizedGlobalCap.proportion96(stakerStake, globalCap) : 0;
return (stakerStake, globalCap, normalizedStakerStake, normalizedGlobalCap);
}
/**
* @notice This function gets a participant's DIFund token
* holdings and global DIFund token holdings for Compound
* and Aave tokens for a collateral type and staker as of
* the checkpointed block, in addition to the
* USD-normalized collateral in the system and the
* redemption value for the staker.
* @param _collateralName Name of collateral.
* @param _staker Participant's address.
* @return DIFund tokens for staker.
* @return DIFund tokens globally.
* @return Redemption value for staker (USD-denominated).
* @return Underlying collateral (USD-denominated) in staking system.
*/
function getOtherRewardsStakeByCollateralNameAndStaker(bytes32 _collateralName, address _staker)
public
view
returns (
uint96,
uint96,
uint96,
uint96
)
{
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName];
// Get DIFund tokens for staker as of the checkpointed block
uint96 stakerStake =
stakeCollateral.diFundToken.getPriorValues(_staker, dsInsuranceFund.otherRewardsCheckpointBlock.sub(1));
// Get DIFund tokens globally as of the checkpointed block
uint96 globalCap =
stakeCollateral.diFundToken.getTotalPriorValues(dsInsuranceFund.otherRewardsCheckpointBlock.sub(1));
// If Aave, don't worry about the normalized values since 1-1
if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) {
return (stakerStake, globalCap, 0, 0);
}
// Compute global USD-denominated stake capitalization. This is
// is straightforward for non-Compound assets, but requires
// exchange rate conversion for Compound assets.
uint96 normalizedGlobalCap =
getUnderlyingTokenAmountForCompound(stakeCollateral.checkpointCap, stakeCollateral.exchangeRate);
// Compute the redemption value (USD-normalized) for staker
// given DIFund token holdings
uint96 normalizedStakerStake = globalCap > 0 ? normalizedGlobalCap.proportion96(stakerStake, globalCap) : 0;
return (stakerStake, globalCap, normalizedStakerStake, normalizedGlobalCap);
}
/**
* @notice Claim other rewards (COMP and aTokens) for a claimant.
* @param _claimant The address for the claimant.
*/
function claimOtherRewardsFromInsuranceMining(address _claimant) internal {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
// Maintain a running total of COMP to be claimed from
// insurance mining contract as a by product of cToken deposits
uint96 compClaimedAmountSum;
// Loop through collateral names that are supported
for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) {
// Obtain collateral struct under consideration
InsuranceFundDefs.StakeCollateral storage stakeCollateral =
dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]];
if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Vanilla) {
// If collateral is of Vanilla flavor, we just
// continue...
continue;
}
// Compute the DIFund token holdings and the normalized,
// USDT-normalized collateral value for the user
(uint96 collateralStaker, uint96 collateralTotal, uint96 normalizedCollateralStaker, ) =
getOtherRewardsStakeByCollateralNameAndStaker(dsInsuranceFund.collateralNames[i], _claimant);
if ((collateralTotal == 0) || (collateralStaker == 0)) {
// If there are no DIFund tokens, there is no reason to
// claim rewards, so we continue...
continue;
}
if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) {
// Aave has a special circumstance, where every
// aToken results in additional aTokens accruing
// to the holder's wallet. In this case, this is
// the DerivaDEX contract. Therefore, we must
// appropriately distribute the extra aTokens to
// users claiming DDX for their aToken deposits.
transferTokensAave(_claimant, dsInsuranceFund.collateralNames[i], collateralStaker, collateralTotal);
} else if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Compound) {
// If collateral is of type Compound, determine the
// COMP claimant is entitled to based on the COMP
// yield for this interval, the claimant's
// DIFundToken share, and the USD-denominated
// share for this market.
uint96 compClaimedAmount =
dsInsuranceFund.compYields.accrued.proportion96(
normalizedCollateralStaker,
dsInsuranceFund.compYields.totalNormalizedCap
);
// Increment the COMP claimed sum to be paid out
// later
compClaimedAmountSum = compClaimedAmountSum.add96(compClaimedAmount);
}
}
// Distribute any COMP to be shared with the user
if (compClaimedAmountSum > 0) {
transferTokensCompound(_claimant, compClaimedAmountSum);
}
}
/**
* @notice This function transfers extra Aave aTokens to claimant.
*/
function transferTokensAave(
address _claimant,
bytes32 _collateralName,
uint96 _aaveStaker,
uint96 _aaveTotal
) internal {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
// Obtain collateral struct under consideration
InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName];
uint96 aTokenClaimedAmount =
dsInsuranceFund.aTokenYields[_collateralName].accrued.proportion96(_aaveStaker, _aaveTotal);
// Continues in scenarios token transfer fails (such as
// transferring 0 tokens)
try IAToken(stakeCollateral.collateralToken).transfer(_claimant, aTokenClaimedAmount) {} catch {}
}
/**
* @notice This function transfers COMP tokens from the contract to
* a recipient.
* @param _amount Amount of COMP to receive.
*/
function transferTokensCompound(address _claimant, uint96 _amount) internal {
// Continues in scenarios token transfer fails (such as
// transferring 0 tokens)
try COMP_TOKEN.transfer(_claimant, _amount) {} catch {}
}
/**
* @notice Updates the DDX market state to ensure that claimants can receive
* their earned DDX rewards.
*/
function updateDDXMarketState(LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund)
internal
{
// Number of blocks that have elapsed from the last protocol
// interaction resulting in DDX accrual. If insurance mining
// has ended, we use this as the reference point, so deltaBlocks
// will be 0 from the second time onwards.
uint256 endBlock = Math.min(block.number, dsInsuranceFund.miningFinalBlockNumber);
uint256 deltaBlocks = endBlock.sub(dsInsuranceFund.ddxMarketState.block);
// If number of blocks elapsed and mine rate per block are
// non-zero
if (deltaBlocks > 0 && dsInsuranceFund.mineRatePerBlock > 0) {
// Maintain a running total of USDT-normalized claim tokens
// (i.e. 1e6 multiplier)
uint256 claimTokens;
// Loop through each of the supported collateral types
for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) {
// Obtain the collateral struct for the collateral type
// participant is staking
InsuranceFundDefs.StakeCollateral storage stakeCollateral =
dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]];
// Increment the USDT-normalized claim tokens count with
// the current total supply
claimTokens = claimTokens.add(
getNormalizedCollateralValue(
dsInsuranceFund.collateralNames[i],
stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits")
)
);
}
// Compute DDX accrued during the time elapsed and the
// number of tokens accrued per claim token outstanding
uint256 ddxAccrued = deltaBlocks.mul(dsInsuranceFund.mineRatePerBlock);
uint256 ratio = claimTokens > 0 ? ddxAccrued.mul(1e36).div(claimTokens) : 0;
// Increment the index
uint256 index = uint256(dsInsuranceFund.ddxMarketState.index).add(ratio);
// Update the claim ddx market state with the new index
// and block
dsInsuranceFund.ddxMarketState.index = index.safe224("IFund: exceeds 224 bits");
dsInsuranceFund.ddxMarketState.block = endBlock.safe32("IFund: exceeds 32 bits");
} else if (deltaBlocks > 0) {
dsInsuranceFund.ddxMarketState.block = endBlock.safe32("IFund: exceeds 32 bits");
}
}
/**
* @notice This function checks if a collateral token is present.
* @param _collateralToken Collateral token address.
* @return Whether collateral token is present or not.
*/
function isCollateralTokenPresent(address _collateralToken) internal view returns (bool) {
LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund =
LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund();
for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) {
// Return true if collateral token has been added
if (
dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]].collateralToken == _collateralToken
) {
return true;
}
}
// Collateral token has not been added, return false
return false;
}
/**
* @notice This function computes the underlying token amount for a
* vanilla token.
* @param _vanillaAmount Number of vanilla tokens.
* @param _collateral Address of vanilla collateral.
* @return Underlying token amount.
*/
function getUnderlyingTokenAmountForVanilla(uint96 _vanillaAmount, address _collateral)
internal
view
returns (uint96)
{
uint256 vanillaDecimals = uint256(IERCCustom(_collateral).decimals());
if (vanillaDecimals >= 6) {
return uint256(_vanillaAmount).div(10**(vanillaDecimals.sub(6))).safe96("IFund: amount exceeds 96 bits");
}
return
uint256(_vanillaAmount).mul(10**(uint256(6).sub(vanillaDecimals))).safe96("IFund: amount exceeds 96 bits");
}
/**
* @notice This function computes the underlying token amount for a
* cToken amount by computing the current exchange rate.
* @param _cTokenAmount Number of cTokens.
* @param _exchangeRate Exchange rate derived from Compound.
* @return Underlying token amount.
*/
function getUnderlyingTokenAmountForCompound(uint96 _cTokenAmount, uint256 _exchangeRate)
internal
pure
returns (uint96)
{
return _exchangeRate.mul(_cTokenAmount).div(1e18).safe96("IFund: amount exceeds 96 bits.");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath32 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add32(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 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 sub32(uint32 a, uint32 b) internal pure returns (uint32) {
return sub32(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 sub32(
uint32 a,
uint32 b,
string memory errorMessage
) internal pure returns (uint32) {
require(b <= a, errorMessage);
uint32 c = a - b;
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { Math } from "openzeppelin-solidity/contracts/math/Math.sol";
import { SafeMath96 } from "./SafeMath96.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library MathHelpers {
using SafeMath96 for uint96;
using SafeMath for uint256;
function proportion96(
uint96 a,
uint256 b,
uint256 c
) internal pure returns (uint96) {
return safe96(uint256(a).mul(b).div(c), "Amount exceeds 96 bits");
}
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
/**
* @dev Returns the largest of two numbers.
*/
function clamp96(
uint96 a,
uint256 b,
uint256 c
) internal pure returns (uint96) {
return safe96(Math.min(Math.max(a, b), c), "Amount exceeds 96 bits");
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { IDIFundToken } from "../../tokens/interfaces/IDIFundToken.sol";
/**
* @title InsuranceFundDefs
* @author DerivaDEX
*
* This library contains the common structs and enums pertaining to
* the insurance fund.
*/
library InsuranceFundDefs {
// DDX market state maintaining claim index and last updated block
struct DDXMarketState {
uint224 index;
uint32 block;
}
// DDX claimant state maintaining claim index and claimed DDX
struct DDXClaimantState {
uint256 index;
uint96 claimedDDX;
}
// Supported collateral struct consisting of the collateral's token
// addresses, collateral flavor/type, current cap and withdrawal
// amounts, the latest checkpointed cap, and exchange rate (for
// cTokens). An interface for the DerivaDEX Insurance Fund token
// corresponding to this collateral is also maintained.
struct StakeCollateral {
address underlyingToken;
address collateralToken;
IDIFundToken diFundToken;
uint96 cap;
uint96 withdrawalFeeCap;
uint96 checkpointCap;
uint96 exchangeRate;
Flavor flavor;
}
// Contains the yield accrued and the total normalized cap.
// Total normalized cap is maintained for Compound flavors so COMP
// distribution can be paid out properly
struct ExternalYieldCheckpoint {
uint96 accrued;
uint96 totalNormalizedCap;
}
// Type of collateral
enum Flavor { Vanilla, Compound, Aave }
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { InsuranceFundDefs } from "../libs/defs/InsuranceFundDefs.sol";
import { IDIFundTokenFactory } from "../tokens/interfaces/IDIFundTokenFactory.sol";
library LibDiamondStorageInsuranceFund {
struct DiamondStorageInsuranceFund {
// List of supported collateral names
bytes32[] collateralNames;
// Collateral name to stake collateral struct
mapping(bytes32 => InsuranceFundDefs.StakeCollateral) stakeCollaterals;
mapping(address => InsuranceFundDefs.DDXClaimantState) ddxClaimantState;
// aToken name to yield checkpoints
mapping(bytes32 => InsuranceFundDefs.ExternalYieldCheckpoint) aTokenYields;
mapping(address => uint256) stakerToOtherRewardsClaims;
// Interval to COMP yield checkpoint
InsuranceFundDefs.ExternalYieldCheckpoint compYields;
// Set the interval for other rewards claiming checkpoints
// (i.e. COMP and aTokens that accrue to the contract)
// (e.g. 40320 ~ 1 week = 7 * 24 * 60 * 60 / 15 blocks)
uint32 interval;
// Current insurance mining withdrawal factor
uint32 withdrawalFactor;
// DDX to be issued per block as insurance mining reward
uint96 mineRatePerBlock;
// Incentive to advance the insurance mining interval
// (e.g. 100e18 = 100 DDX)
uint96 advanceIntervalReward;
// Total DDX insurance mined
uint96 minedAmount;
// Insurance fund capitalization due to liquidations and fees
uint96 liqAndFeeCapitalization;
// Checkpoint block for other rewards
uint256 otherRewardsCheckpointBlock;
// Insurance mining final block number
uint256 miningFinalBlockNumber;
InsuranceFundDefs.DDXMarketState ddxMarketState;
IDIFundTokenFactory diFundTokenFactory;
}
bytes32 constant DIAMOND_STORAGE_POSITION_INSURANCE_FUND =
keccak256("diamond.standard.diamond.storage.DerivaDEX.InsuranceFund");
function diamondStorageInsuranceFund() internal pure returns (DiamondStorageInsuranceFund storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION_INSURANCE_FUND;
assembly {
ds_slot := position
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
library LibDiamondStoragePause {
struct DiamondStoragePause {
bool isPaused;
}
bytes32 constant DIAMOND_STORAGE_POSITION_PAUSE = keccak256("diamond.standard.diamond.storage.DerivaDEX.Pause");
function diamondStoragePause() internal pure returns (DiamondStoragePause storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION_PAUSE;
assembly {
ds_slot := position
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IAToken {
function decimals() external returns (uint256);
function transfer(address _recipient, uint256 _amount) external;
function balanceOf(address _user) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
abstract contract IComptroller {
struct CompMarketState {
uint224 index;
uint32 block;
}
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true; // solhint-disable-line const-name-snakecase
// @notice The COMP market supply state for each market
mapping(address => CompMarketState) public compSupplyState;
/// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP
mapping(address => mapping(address => uint256)) public compSupplierIndex;
/// @notice The portion of compRate that each market currently receives
mapping(address => uint256) public compSpeeds;
/// @notice The COMP accrued but not yet transferred to each user
mapping(address => uint256) public compAccrued;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory);
function exitMarket(address cToken) external virtual returns (uint256);
/*** Policy Hooks ***/
function mintAllowed(
address cToken,
address minter,
uint256 mintAmount
) external virtual returns (uint256);
function mintVerify(
address cToken,
address minter,
uint256 mintAmount,
uint256 mintTokens
) external virtual;
function redeemAllowed(
address cToken,
address redeemer,
uint256 redeemTokens
) external virtual returns (uint256);
function redeemVerify(
address cToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
) external virtual;
function borrowAllowed(
address cToken,
address borrower,
uint256 borrowAmount
) external virtual returns (uint256);
function borrowVerify(
address cToken,
address borrower,
uint256 borrowAmount
) external virtual;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint256 repayAmount
) external virtual returns (uint256);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint256 repayAmount,
uint256 borrowerIndex
) external virtual;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external virtual returns (uint256);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount,
uint256 seizeTokens
) external virtual;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external virtual returns (uint256);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external virtual;
function transferAllowed(
address cToken,
address src,
address dst,
uint256 transferTokens
) external virtual returns (uint256);
function transferVerify(
address cToken,
address src,
address dst,
uint256 transferTokens
) external virtual;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint256 repayAmount
) external virtual returns (uint256, uint256);
function claimComp(address holder) public virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface ICToken {
function accrueInterest() external returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOfUnderlying(address owner) external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function decimals() external view returns (uint256);
function exchangeRateStored() external view returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function getCash() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/**
* @title IDIFundToken
* @author DerivaDEX (Borrowed/inspired from Compound)
* @notice This is the native token contract for DerivaDEX. It
* implements the ERC-20 standard, with additional
* functionality to efficiently handle the governance aspect of
* the DerivaDEX ecosystem.
* @dev The contract makes use of some nonstandard types not seen in
* the ERC-20 standard. The DDX token makes frequent use of the
* uint96 data type, as opposed to the more standard uint256 type.
* Given the maintenance of arrays of balances, allowances, and
* voting checkpoints, this allows us to more efficiently pack
* data together, thereby resulting in cheaper transactions.
*/
interface IDIFundToken {
function transfer(address _recipient, uint256 _amount) external returns (bool);
function mint(address _recipient, uint256 _amount) external;
function burnFrom(address _account, uint256 _amount) external;
function delegate(address _delegatee) external;
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) external returns (bool);
function approve(address _spender, uint256 _amount) external returns (bool);
function getPriorValues(address account, uint256 blockNumber) external view returns (uint96);
function getTotalPriorValues(uint256 blockNumber) external view returns (uint96);
function balanceOf(address _account) external view returns (uint256);
function totalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { DIFundToken } from "../DIFundToken.sol";
/**
* @title DIFundToken
* @author DerivaDEX (Borrowed/inspired from Compound)
* @notice This is the token contract for tokenized DerivaDEX insurance
* fund positions. It implements the ERC-20 standard, with
* additional functionality around snapshotting user and global
* balances.
* @dev The contract makes use of some nonstandard types not seen in
* the ERC-20 standard. The DIFundToken makes frequent use of the
* uint96 data type, as opposed to the more standard uint256 type.
* Given the maintenance of arrays of balances and allowances, this
* allows us to more efficiently pack data together, thereby
* resulting in cheaper transactions.
*/
interface IDIFundTokenFactory {
function createNewDIFundToken(
string calldata _name,
string calldata _symbol,
uint8 _decimals
) external returns (address);
function diFundTokens(uint256 index) external returns (DIFundToken);
function issuer() external view returns (address);
function getDIFundTokens() external view returns (DIFundToken[] memory);
function getDIFundTokensLength() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { LibBytes } from "../libs/LibBytes.sol";
import { LibEIP712 } from "../libs/LibEIP712.sol";
import { LibPermit } from "../libs/LibPermit.sol";
import { SafeMath96 } from "../libs/SafeMath96.sol";
import { IInsuranceFund } from "../facets/interfaces/IInsuranceFund.sol";
/**
* @title DIFundToken
* @author DerivaDEX (Borrowed/inspired from Compound)
* @notice This is the token contract for tokenized DerivaDEX insurance
* fund positions. It implements the ERC-20 standard, with
* additional functionality around snapshotting user and global
* balances.
* @dev The contract makes use of some nonstandard types not seen in
* the ERC-20 standard. The DIFundToken makes frequent use of the
* uint96 data type, as opposed to the more standard uint256 type.
* Given the maintenance of arrays of balances and allowances, this
* allows us to more efficiently pack data together, thereby
* resulting in cheaper transactions.
*/
contract DIFundToken {
using SafeMath96 for uint96;
using SafeMath for uint256;
using LibBytes for bytes;
uint256 internal _totalSupply;
string private _name;
string private _symbol;
string private _version;
uint8 private _decimals;
/// @notice Address authorized to issue/mint DDX tokens
address public issuer;
mapping(address => mapping(address => uint96)) internal allowances;
mapping(address => uint96) internal balances;
/// @notice A checkpoint for marking vote count from given block
struct Checkpoint {
uint32 id;
uint96 values;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint256 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint256) public numCheckpoints;
mapping(uint256 => Checkpoint) totalCheckpoints;
uint256 numTotalCheckpoints;
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice Emitted when a user account's balance changes
event ValuesChanged(address indexed user, uint96 previousValue, uint96 newValue);
/// @notice Emitted when a user account's balance changes
event TotalValuesChanged(uint96 previousValue, uint96 newValue);
/// @notice Emitted when transfer takes place
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice Emitted when approval takes place
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new DIFundToken token
*/
constructor(
string memory name,
string memory symbol,
uint8 decimals,
address _issuer
) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_version = "1";
// Set issuer to deploying address
issuer = _issuer;
}
/**
* @notice Returns the name of the token.
* @return Name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @notice Returns the symbol of the token.
* @return Symbol of the token.
*/
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}.
* @return Number of decimals.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @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 (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address _spender, uint256 _amount) external returns (bool) {
require(_spender != address(0), "DIFT: approve to the zero address.");
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DIFT: amount exceeds 96 bits.");
}
// Set allowance
allowances[msg.sender][_spender] = amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
* Emits an {Approval} event indicating the updated allowance.
* Requirements:
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address _spender, uint256 _addedValue) external returns (bool) {
require(_spender != address(0), "DIFT: approve to the zero address.");
// Convert amount to uint96
uint96 amount;
if (_addedValue == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_addedValue, "DIFT: amount exceeds 96 bits.");
}
// Increase allowance
allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add96(amount);
emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
* Emits an {Approval} event indicating the updated allowance.
* Requirements:
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue) external returns (bool) {
require(_spender != address(0), "DIFT: approve to the zero address.");
// Convert amount to uint96
uint96 amount;
if (_subtractedValue == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_subtractedValue, "DIFT: amount exceeds 96 bits.");
}
// Decrease allowance
allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub96(
amount,
"DIFT: decreased allowance below zero."
);
emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param _account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address _account) external view returns (uint256) {
return balances[_account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param _recipient The address of the destination account
* @param _amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address _recipient, uint256 _amount) external returns (bool) {
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DIFT: amount exceeds 96 bits.");
}
// Claim DDX rewards on behalf of the sender
IInsuranceFund(issuer).claimDDXFromInsuranceMining(msg.sender);
// Claim DDX rewards on behalf of the recipient
IInsuranceFund(issuer).claimDDXFromInsuranceMining(_recipient);
// Transfer tokens from sender to recipient
_transferTokens(msg.sender, _recipient, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param _sender The address of the source account
* @param _recipient The address of the destination account
* @param _amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) external returns (bool) {
uint96 spenderAllowance = allowances[_sender][msg.sender];
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DIFT: amount exceeds 96 bits.");
}
if (msg.sender != _sender && spenderAllowance != uint96(-1)) {
// Tx sender is not the same as transfer sender and doesn't
// have unlimited allowance.
// Reduce allowance by amount being transferred
uint96 newAllowance = spenderAllowance.sub96(amount);
allowances[_sender][msg.sender] = newAllowance;
emit Approval(_sender, msg.sender, newAllowance);
}
// Claim DDX rewards on behalf of the sender
IInsuranceFund(issuer).claimDDXFromInsuranceMining(_sender);
// Claim DDX rewards on behalf of the recipient
IInsuranceFund(issuer).claimDDXFromInsuranceMining(_recipient);
// Transfer tokens from sender to recipient
_transferTokens(_sender, _recipient, amount);
return true;
}
/**
* @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 _recipient, uint256 _amount) external {
require(msg.sender == issuer, "DIFT: unauthorized mint.");
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DIFT: amount exceeds 96 bits.");
}
// Mint tokens to recipient
_transferTokensMint(_recipient, amount);
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, decreasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function burn(uint256 _amount) external {
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DIFT: amount exceeds 96 bits.");
}
// Burn tokens from sender
_transferTokensBurn(msg.sender, 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 burnFrom(address _account, uint256 _amount) external {
uint96 spenderAllowance = allowances[_account][msg.sender];
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DIFT: amount exceeds 96 bits.");
}
if (msg.sender != _account && spenderAllowance != uint96(-1) && msg.sender != issuer) {
// Tx sender is not the same as burn account and doesn't
// have unlimited allowance.
// Reduce allowance by amount being transferred
uint96 newAllowance = spenderAllowance.sub96(amount, "DIFT: burn amount exceeds allowance.");
allowances[_account][msg.sender] = newAllowance;
emit Approval(_account, msg.sender, newAllowance);
}
// Burn tokens from account
_transferTokensBurn(_account, amount);
}
/**
* @notice Permits allowance from signatory to `spender`
* @param _spender The spender being approved
* @param _value The value being approved
* @param _nonce The contract state required to match the signature
* @param _expiry The time at which to expire the signature
* @param _signature Signature
*/
function permit(
address _spender,
uint256 _value,
uint256 _nonce,
uint256 _expiry,
bytes memory _signature
) external {
// Perform EIP712 hashing logic
bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(_name, _version, getChainId(), address(this));
bytes32 permitHash =
LibPermit.getPermitHash(
LibPermit.Permit({ spender: _spender, value: _value, nonce: _nonce, expiry: _expiry }),
eip712OrderParamsDomainHash
);
// Perform sig recovery
uint8 v = uint8(_signature[0]);
bytes32 r = _signature.readBytes32(1);
bytes32 s = _signature.readBytes32(33);
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
address recovered = ecrecover(permitHash, v, r, s);
require(recovered != address(0), "DIFT: invalid signature.");
require(_nonce == nonces[recovered]++, "DIFT: invalid nonce.");
require(block.timestamp <= _expiry, "DIFT: signature expired.");
// Convert amount to uint96
uint96 amount;
if (_value == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_value, "DIFT: amount exceeds 96 bits.");
}
// Set allowance
allowances[recovered][_spender] = amount;
emit Approval(recovered, _spender, _value);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param _account The address of the account holding the funds
* @param _spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address _account, address _spender) external view returns (uint256) {
return allowances[_account][_spender];
}
/**
* @notice Get the total max supply of DDX tokens
* @return The total max supply of DDX
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @notice Determine the prior number of values for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param _account The address of the account to check
* @param _blockNumber The block number to get the vote balance at
* @return The number of values the account had as of the given block
*/
function getPriorValues(address _account, uint256 _blockNumber) external view returns (uint96) {
require(_blockNumber < block.number, "DIFT: block not yet determined.");
uint256 numCheckpointsAccount = numCheckpoints[_account];
if (numCheckpointsAccount == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) {
return checkpoints[_account][numCheckpointsAccount - 1].values;
}
// Next check implicit zero balance
if (checkpoints[_account][0].id > _blockNumber) {
return 0;
}
// Perform binary search to find the most recent token holdings
uint256 lower = 0;
uint256 upper = numCheckpointsAccount - 1;
while (upper > lower) {
// ceil, avoiding overflow
uint256 center = upper - (upper - lower) / 2;
Checkpoint memory cp = checkpoints[_account][center];
if (cp.id == _blockNumber) {
return cp.values;
} else if (cp.id < _blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[_account][lower].values;
}
/**
* @notice Determine the prior number of values for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param _blockNumber The block number to get the vote balance at
* @return The number of values the account had as of the given block
*/
function getTotalPriorValues(uint256 _blockNumber) external view returns (uint96) {
require(_blockNumber < block.number, "DIFT: block not yet determined.");
if (numTotalCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (totalCheckpoints[numTotalCheckpoints - 1].id <= _blockNumber) {
return totalCheckpoints[numTotalCheckpoints - 1].values;
}
// Next check implicit zero balance
if (totalCheckpoints[0].id > _blockNumber) {
return 0;
}
// Perform binary search to find the most recent token holdings
// leading to a measure of voting power
uint256 lower = 0;
uint256 upper = numTotalCheckpoints - 1;
while (upper > lower) {
// ceil, avoiding overflow
uint256 center = upper - (upper - lower) / 2;
Checkpoint memory cp = totalCheckpoints[center];
if (cp.id == _blockNumber) {
return cp.values;
} else if (cp.id < _blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return totalCheckpoints[lower].values;
}
function _transferTokens(
address _spender,
address _recipient,
uint96 _amount
) internal {
require(_spender != address(0), "DIFT: cannot transfer from the zero address.");
require(_recipient != address(0), "DIFT: cannot transfer to the zero address.");
// Reduce spender's balance and increase recipient balance
balances[_spender] = balances[_spender].sub96(_amount);
balances[_recipient] = balances[_recipient].add96(_amount);
emit Transfer(_spender, _recipient, _amount);
// Move values from spender to recipient
_moveTokens(_spender, _recipient, _amount);
}
function _transferTokensMint(address _recipient, uint96 _amount) internal {
require(_recipient != address(0), "DIFT: cannot transfer to the zero address.");
// Add to recipient's balance
balances[_recipient] = balances[_recipient].add96(_amount);
_totalSupply = _totalSupply.add(_amount);
emit Transfer(address(0), _recipient, _amount);
// Add value to recipient's checkpoint
_moveTokens(address(0), _recipient, _amount);
_writeTotalCheckpoint(_amount, true);
}
function _transferTokensBurn(address _spender, uint96 _amount) internal {
require(_spender != address(0), "DIFT: cannot transfer from the zero address.");
// Reduce the spender/burner's balance
balances[_spender] = balances[_spender].sub96(_amount, "DIFT: not enough balance to burn.");
// Reduce the circulating supply
_totalSupply = _totalSupply.sub(_amount);
emit Transfer(_spender, address(0), _amount);
// Reduce value from spender's checkpoint
_moveTokens(_spender, address(0), _amount);
_writeTotalCheckpoint(_amount, false);
}
function _moveTokens(
address _initUser,
address _finUser,
uint96 _amount
) internal {
if (_initUser != _finUser && _amount > 0) {
// Initial user address is different than final
// user address and nonzero number of values moved
if (_initUser != address(0)) {
uint256 initUserNum = numCheckpoints[_initUser];
// Retrieve and compute the old and new initial user
// address' values
uint96 initUserOld = initUserNum > 0 ? checkpoints[_initUser][initUserNum - 1].values : 0;
uint96 initUserNew = initUserOld.sub96(_amount);
_writeCheckpoint(_initUser, initUserOld, initUserNew);
}
if (_finUser != address(0)) {
uint256 finUserNum = numCheckpoints[_finUser];
// Retrieve and compute the old and new final user
// address' values
uint96 finUserOld = finUserNum > 0 ? checkpoints[_finUser][finUserNum - 1].values : 0;
uint96 finUserNew = finUserOld.add96(_amount);
_writeCheckpoint(_finUser, finUserOld, finUserNew);
}
}
}
function _writeCheckpoint(
address _user,
uint96 _oldValues,
uint96 _newValues
) internal {
uint32 blockNumber = safe32(block.number, "DIFT: exceeds 32 bits.");
uint256 userNum = numCheckpoints[_user];
if (userNum > 0 && checkpoints[_user][userNum - 1].id == blockNumber) {
// If latest checkpoint is current block, edit in place
checkpoints[_user][userNum - 1].values = _newValues;
} else {
// Create a new id, value pair
checkpoints[_user][userNum] = Checkpoint({ id: blockNumber, values: _newValues });
numCheckpoints[_user] = userNum.add(1);
}
emit ValuesChanged(_user, _oldValues, _newValues);
}
function _writeTotalCheckpoint(uint96 _amount, bool increase) internal {
if (_amount > 0) {
uint32 blockNumber = safe32(block.number, "DIFT: exceeds 32 bits.");
uint96 oldValues = numTotalCheckpoints > 0 ? totalCheckpoints[numTotalCheckpoints - 1].values : 0;
uint96 newValues = increase ? oldValues.add96(_amount) : oldValues.sub96(_amount);
if (numTotalCheckpoints > 0 && totalCheckpoints[numTotalCheckpoints - 1].id == block.number) {
// If latest checkpoint is current block, edit in place
totalCheckpoints[numTotalCheckpoints - 1].values = newValues;
} else {
// Create a new id, value pair
totalCheckpoints[numTotalCheckpoints].id = blockNumber;
totalCheckpoints[numTotalCheckpoints].values = newValues;
numTotalCheckpoints = numTotalCheckpoints.add(1);
}
emit TotalValuesChanged(oldValues, newValues);
}
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// SPDX-License-Identifier: MIT
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.12;
library LibBytes {
using LibBytes 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) {
require(from <= to, "FROM_LESS_THAN_TO_REQUIRED");
require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED");
// 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.
/// @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)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
) internal pure returns (bytes memory result) {
require(from <= to, "FROM_LESS_THAN_TO_REQUIRED");
require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED");
// 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) {
require(b.length > 0, "GREATER_THAN_ZERO_LENGTH_REQUIRED");
// 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 Pops the last 20 bytes off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return result The 20 byte address that was popped off.
function popLast20Bytes(bytes memory b) internal pure returns (address result) {
require(b.length >= 20, "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED");
// Store last 20 bytes.
result = readAddress(b, b.length - 20);
assembly {
// Subtract 20 from byte array length.
let newLen := sub(mload(b), 20)
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) {
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// 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 {
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// 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) {
require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED");
// 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 {
require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED");
// 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) {
require(b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED");
// 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 Reads nested bytes from a specific position.
/// @dev NOTE: the returned value overlaps with the input value.
/// Both should be treated as immutable.
/// @param b Byte array containing nested bytes.
/// @param index Index of nested bytes.
/// @return result Nested bytes.
function readBytesWithLength(bytes memory b, uint256 index) internal pure returns (bytes memory result) {
// Read length of nested bytes
uint256 nestedBytesLength = readUint256(b, index);
index += 32;
// Assert length of <b> is valid, given
// length of nested bytes
require(b.length >= index + nestedBytesLength, "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED");
// Return a pointer to the byte array as it exists inside `b`
assembly {
result := add(b, index)
}
return result;
}
/// @dev Inserts bytes at 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 bytes to insert.
function writeBytesWithLength(
bytes memory b,
uint256 index,
bytes memory input
) internal pure {
// Assert length of <b> is valid, given
// length of input
require(
b.length >= index + 32 + input.length, // 32 bytes to store length
"GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"
);
// Copy <input> into <b>
memCopy(
b.contentAddress() + index,
input.rawAddress(), // includes length of <input>
input.length + 32 // +32 bytes to store <input> length
);
}
/// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length.
/// @param dest Byte array that will be overwritten with source bytes.
/// @param source Byte array to copy onto dest bytes.
function deepCopyBytes(bytes memory dest, bytes memory source) internal pure {
uint256 sourceLen = source.length;
// Dest length must be >= source length, or some bytes would not be copied.
require(dest.length >= sourceLen, "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED");
memCopy(dest.contentAddress(), source.contentAddress(), sourceLen);
}
}
// SPDX-License-Identifier: MIT
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.12;
library LibEIP712 {
// Hash of the EIP712 Domain Separator Schema
// keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract",
// ")"
// ))
bytes32 internal constant _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH =
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev Calculates a EIP712 domain separator.
/// @param name The EIP712 domain name.
/// @param version The EIP712 domain version.
/// @param verifyingContract The EIP712 verifying contract.
/// @return result EIP712 domain separator.
function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
) internal pure returns (bytes32 result) {
bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
// keccak256(bytes(name)),
// keccak256(bytes(version)),
// chainId,
// uint256(verifyingContract)
// ))
assembly {
// Calculate hashes of dynamic data
let nameHash := keccak256(add(name, 32), mload(name))
let versionHash := keccak256(add(version, 32), mload(version))
// Load free memory pointer
let memPtr := mload(64)
// Store params in memory
mstore(memPtr, schemaHash)
mstore(add(memPtr, 32), nameHash)
mstore(add(memPtr, 64), versionHash)
mstore(add(memPtr, 96), chainId)
mstore(add(memPtr, 128), verifyingContract)
// Compute hash
result := keccak256(memPtr, 160)
}
return result;
}
/// @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
/// @param eip712DomainHash Hash of the domain domain separator data, computed
/// with getDomainHash().
/// @param hashStruct The EIP712 hash struct.
/// @return result EIP712 hash applied to the given EIP712 Domain.
function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) {
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
// SPDX-License-Identifier: MIT
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.12;
import { LibEIP712 } from "./LibEIP712.sol";
library LibPermit {
struct Permit {
address spender; // Spender
uint256 value; // Value
uint256 nonce; // Nonce
uint256 expiry; // Expiry
}
// Hash for the EIP712 LibPermit Schema
// bytes32 constant internal EIP712_PERMIT_SCHEMA_HASH = keccak256(abi.encodePacked(
// "Permit(",
// "address spender,",
// "uint256 value,",
// "uint256 nonce,",
// "uint256 expiry",
// ")"
// ));
bytes32 internal constant EIP712_PERMIT_SCHEMA_HASH =
0x58e19c95adc541dea238d3211d11e11e7def7d0c7fda4e10e0c45eb224ef2fb7;
/// @dev Calculates Keccak-256 hash of the permit.
/// @param permit The permit structure.
/// @return permitHash Keccak-256 EIP712 hash of the permit.
function getPermitHash(Permit memory permit, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 permitHash)
{
permitHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashPermit(permit));
return permitHash;
}
/// @dev Calculates EIP712 hash of the permit.
/// @param permit The permit structure.
/// @return result EIP712 hash of the permit.
function hashPermit(Permit memory permit) internal pure returns (bytes32 result) {
// Assembly for more efficiently computing:
bytes32 schemaHash = EIP712_PERMIT_SCHEMA_HASH;
assembly {
// Assert permit offset (this is an internal error that should never be triggered)
if lt(permit, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(permit, 32)
// Backup
let temp1 := mload(pos1)
// Hash in place
mstore(pos1, schemaHash)
result := keccak256(pos1, 160)
// Restore
mstore(pos1, temp1)
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IInsuranceFund {
function claimDDXFromInsuranceMining(address _claimant) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { LibBytes } from "../libs/LibBytes.sol";
import { LibEIP712 } from "../libs/LibEIP712.sol";
import { LibPermit } from "../libs/LibPermit.sol";
import { SafeMath96 } from "../libs/SafeMath96.sol";
import { DIFundToken } from "./DIFundToken.sol";
/**
* @title DIFundTokenFactory
* @author DerivaDEX (Borrowed/inspired from Compound)
* @notice This is the native token contract for DerivaDEX. It
* implements the ERC-20 standard, with additional
* functionality to efficiently handle the governance aspect of
* the DerivaDEX ecosystem.
* @dev The contract makes use of some nonstandard types not seen in
* the ERC-20 standard. The DDX token makes frequent use of the
* uint96 data type, as opposed to the more standard uint256 type.
* Given the maintenance of arrays of balances, allowances, and
* voting checkpoints, this allows us to more efficiently pack
* data together, thereby resulting in cheaper transactions.
*/
contract DIFundTokenFactory {
DIFundToken[] public diFundTokens;
address public issuer;
/**
* @notice Construct a new DDX token
*/
constructor(address _issuer) public {
// Set issuer to deploying address
issuer = _issuer;
}
function createNewDIFundToken(
string calldata _name,
string calldata _symbol,
uint8 _decimals
) external returns (address) {
require(msg.sender == issuer, "DIFTF: unauthorized.");
DIFundToken diFundToken = new DIFundToken(_name, _symbol, _decimals, issuer);
diFundTokens.push(diFundToken);
return address(diFundToken);
}
function getDIFundTokens() external view returns (DIFundToken[] memory) {
return diFundTokens;
}
function getDIFundTokensLength() external view returns (uint256) {
return diFundTokens.length;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { LibBytes } from "../libs/LibBytes.sol";
import { LibEIP712 } from "../libs/LibEIP712.sol";
import { LibDelegation } from "../libs/LibDelegation.sol";
import { LibPermit } from "../libs/LibPermit.sol";
import { SafeMath96 } from "../libs/SafeMath96.sol";
/**
* @title DDX
* @author DerivaDEX (Borrowed/inspired from Compound)
* @notice This is the native token contract for DerivaDEX. It
* implements the ERC-20 standard, with additional
* functionality to efficiently handle the governance aspect of
* the DerivaDEX ecosystem.
* @dev The contract makes use of some nonstandard types not seen in
* the ERC-20 standard. The DDX token makes frequent use of the
* uint96 data type, as opposed to the more standard uint256 type.
* Given the maintenance of arrays of balances, allowances, and
* voting checkpoints, this allows us to more efficiently pack
* data together, thereby resulting in cheaper transactions.
*/
contract DDX {
using SafeMath96 for uint96;
using SafeMath for uint256;
using LibBytes for bytes;
/// @notice ERC20 token name for this token
string public constant name = "DerivaDAO"; // solhint-disable-line const-name-snakecase
/// @notice ERC20 token symbol for this token
string public constant symbol = "DDX"; // solhint-disable-line const-name-snakecase
/// @notice ERC20 token decimals for this token
uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase
/// @notice Version number for this token. Used for EIP712 hashing.
string public constant version = "1"; // solhint-disable-line const-name-snakecase
/// @notice Max number of tokens to be issued (100 million DDX)
uint96 public constant MAX_SUPPLY = 100000000e18;
/// @notice Total number of tokens in circulation (50 million DDX)
uint96 public constant PRE_MINE_SUPPLY = 50000000e18;
/// @notice Issued supply of tokens
uint96 public issuedSupply;
/// @notice Current total/circulating supply of tokens
uint96 public totalSupply;
/// @notice Whether ownership has been transferred to the DAO
bool public ownershipTransferred;
/// @notice Address authorized to issue/mint DDX tokens
address public issuer;
mapping(address => mapping(address => uint96)) internal allowances;
mapping(address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping(address => address) public delegates;
/// @notice A checkpoint for marking vote count from given block
struct Checkpoint {
uint32 id;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint256 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint256) public numCheckpoints;
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice Emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice Emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint96 previousBalance, uint96 newBalance);
/// @notice Emitted when transfer takes place
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice Emitted when approval takes place
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new DDX token
*/
constructor() public {
// Set issuer to deploying address
issuer = msg.sender;
// Issue pre-mine token supply to deploying address and
// set the issued and circulating supplies to pre-mine amount
_transferTokensMint(msg.sender, PRE_MINE_SUPPLY);
}
/**
* @notice Transfer ownership of DDX token from the deploying
* address to the DerivaDEX Proxy/DAO
* @param _derivaDEXProxy DerivaDEX Proxy address
*/
function transferOwnershipToDerivaDEXProxy(address _derivaDEXProxy) external {
// Ensure deploying address is calling this, destination is not
// the zero address, and that ownership has never been
// transferred thus far
require(msg.sender == issuer, "DDX: unauthorized transfer of ownership.");
require(_derivaDEXProxy != address(0), "DDX: transferring to zero address.");
require(!ownershipTransferred, "DDX: ownership already transferred.");
// Set ownership transferred boolean flag and the new authorized
// issuer
ownershipTransferred = true;
issuer = _derivaDEXProxy;
}
/**
* @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 (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address _spender, uint256 _amount) external returns (bool) {
require(_spender != address(0), "DDX: approve to the zero address.");
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DDX: amount exceeds 96 bits.");
}
// Set allowance
allowances[msg.sender][_spender] = amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
* Emits an {Approval} event indicating the updated allowance.
* Requirements:
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address _spender, uint256 _addedValue) external returns (bool) {
require(_spender != address(0), "DDX: approve to the zero address.");
// Convert amount to uint96
uint96 amount;
if (_addedValue == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_addedValue, "DDX: amount exceeds 96 bits.");
}
// Increase allowance
allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add96(amount);
emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
* Emits an {Approval} event indicating the updated allowance.
* Requirements:
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue) external returns (bool) {
require(_spender != address(0), "DDX: approve to the zero address.");
// Convert amount to uint96
uint96 amount;
if (_subtractedValue == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_subtractedValue, "DDX: amount exceeds 96 bits.");
}
// Decrease allowance
allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub96(
amount,
"DDX: decreased allowance below zero."
);
emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param _account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address _account) external view returns (uint256) {
return balances[_account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param _recipient The address of the destination account
* @param _amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address _recipient, uint256 _amount) external returns (bool) {
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DDX: amount exceeds 96 bits.");
}
// Transfer tokens from sender to recipient
_transferTokens(msg.sender, _recipient, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param _from The address of the source account
* @param _recipient The address of the destination account
* @param _amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address _from,
address _recipient,
uint256 _amount
) external returns (bool) {
uint96 spenderAllowance = allowances[_from][msg.sender];
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DDX: amount exceeds 96 bits.");
}
if (msg.sender != _from && spenderAllowance != uint96(-1)) {
// Tx sender is not the same as transfer sender and doesn't
// have unlimited allowance.
// Reduce allowance by amount being transferred
uint96 newAllowance = spenderAllowance.sub96(amount);
allowances[_from][msg.sender] = newAllowance;
emit Approval(_from, msg.sender, newAllowance);
}
// Transfer tokens from sender to recipient
_transferTokens(_from, _recipient, amount);
return true;
}
/**
* @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 _recipient, uint256 _amount) external {
require(msg.sender == issuer, "DDX: unauthorized mint.");
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DDX: amount exceeds 96 bits.");
}
// Ensure the mint doesn't cause the issued supply to exceed
// the total supply that could ever be issued
require(issuedSupply.add96(amount) <= MAX_SUPPLY, "DDX: cap exceeded.");
// Mint tokens to recipient
_transferTokensMint(_recipient, amount);
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, decreasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function burn(uint256 _amount) external {
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DDX: amount exceeds 96 bits.");
}
// Burn tokens from sender
_transferTokensBurn(msg.sender, 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 burnFrom(address _account, uint256 _amount) external {
uint96 spenderAllowance = allowances[_account][msg.sender];
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DDX: amount exceeds 96 bits.");
}
if (msg.sender != _account && spenderAllowance != uint96(-1)) {
// Tx sender is not the same as burn account and doesn't
// have unlimited allowance.
// Reduce allowance by amount being transferred
uint96 newAllowance = spenderAllowance.sub96(amount, "DDX: burn amount exceeds allowance.");
allowances[_account][msg.sender] = newAllowance;
emit Approval(_account, msg.sender, newAllowance);
}
// Burn tokens from account
_transferTokensBurn(_account, amount);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param _delegatee The address to delegate votes to
*/
function delegate(address _delegatee) external {
_delegate(msg.sender, _delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param _delegatee The address to delegate votes to
* @param _nonce The contract state required to match the signature
* @param _expiry The time at which to expire the signature
* @param _signature Signature
*/
function delegateBySig(
address _delegatee,
uint256 _nonce,
uint256 _expiry,
bytes memory _signature
) external {
// Perform EIP712 hashing logic
bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this));
bytes32 delegationHash =
LibDelegation.getDelegationHash(
LibDelegation.Delegation({ delegatee: _delegatee, nonce: _nonce, expiry: _expiry }),
eip712OrderParamsDomainHash
);
// Perform sig recovery
uint8 v = uint8(_signature[0]);
bytes32 r = _signature.readBytes32(1);
bytes32 s = _signature.readBytes32(33);
address recovered = ecrecover(delegationHash, v, r, s);
require(recovered != address(0), "DDX: invalid signature.");
require(_nonce == nonces[recovered]++, "DDX: invalid nonce.");
require(block.timestamp <= _expiry, "DDX: signature expired.");
// Delegate votes from recovered address to delegatee
_delegate(recovered, _delegatee);
}
/**
* @notice Permits allowance from signatory to `spender`
* @param _spender The spender being approved
* @param _value The value being approved
* @param _nonce The contract state required to match the signature
* @param _expiry The time at which to expire the signature
* @param _signature Signature
*/
function permit(
address _spender,
uint256 _value,
uint256 _nonce,
uint256 _expiry,
bytes memory _signature
) external {
// Perform EIP712 hashing logic
bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this));
bytes32 permitHash =
LibPermit.getPermitHash(
LibPermit.Permit({ spender: _spender, value: _value, nonce: _nonce, expiry: _expiry }),
eip712OrderParamsDomainHash
);
// Perform sig recovery
uint8 v = uint8(_signature[0]);
bytes32 r = _signature.readBytes32(1);
bytes32 s = _signature.readBytes32(33);
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
address recovered = ecrecover(permitHash, v, r, s);
require(recovered != address(0), "DDX: invalid signature.");
require(_nonce == nonces[recovered]++, "DDX: invalid nonce.");
require(block.timestamp <= _expiry, "DDX: signature expired.");
// Convert amount to uint96
uint96 amount;
if (_value == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_value, "DDX: amount exceeds 96 bits.");
}
// Set allowance
allowances[recovered][_spender] = amount;
emit Approval(recovered, _spender, _value);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param _account The address of the account holding the funds
* @param _spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address _account, address _spender) external view returns (uint256) {
return allowances[_account][_spender];
}
/**
* @notice Gets the current votes balance.
* @param _account The address to get votes balance.
* @return The number of current votes.
*/
function getCurrentVotes(address _account) external view returns (uint96) {
uint256 numCheckpointsAccount = numCheckpoints[_account];
return numCheckpointsAccount > 0 ? checkpoints[_account][numCheckpointsAccount - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param _account The address of the account to check
* @param _blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address _account, uint256 _blockNumber) external view returns (uint96) {
require(_blockNumber < block.number, "DDX: block not yet determined.");
uint256 numCheckpointsAccount = numCheckpoints[_account];
if (numCheckpointsAccount == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) {
return checkpoints[_account][numCheckpointsAccount - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[_account][0].id > _blockNumber) {
return 0;
}
// Perform binary search to find the most recent token holdings
// leading to a measure of voting power
uint256 lower = 0;
uint256 upper = numCheckpointsAccount - 1;
while (upper > lower) {
// ceil, avoiding overflow
uint256 center = upper - (upper - lower) / 2;
Checkpoint memory cp = checkpoints[_account][center];
if (cp.id == _blockNumber) {
return cp.votes;
} else if (cp.id < _blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[_account][lower].votes;
}
function _delegate(address _delegator, address _delegatee) internal {
// Get the current address delegator has delegated
address currentDelegate = _getDelegatee(_delegator);
// Get delegator's DDX balance
uint96 delegatorBalance = balances[_delegator];
// Set delegator's new delegatee address
delegates[_delegator] = _delegatee;
emit DelegateChanged(_delegator, currentDelegate, _delegatee);
// Move votes from currently-delegated address to
// new address
_moveDelegates(currentDelegate, _delegatee, delegatorBalance);
}
function _transferTokens(
address _spender,
address _recipient,
uint96 _amount
) internal {
require(_spender != address(0), "DDX: cannot transfer from the zero address.");
require(_recipient != address(0), "DDX: cannot transfer to the zero address.");
// Reduce spender's balance and increase recipient balance
balances[_spender] = balances[_spender].sub96(_amount);
balances[_recipient] = balances[_recipient].add96(_amount);
emit Transfer(_spender, _recipient, _amount);
// Move votes from currently-delegated address to
// recipient's delegated address
_moveDelegates(_getDelegatee(_spender), _getDelegatee(_recipient), _amount);
}
function _transferTokensMint(address _recipient, uint96 _amount) internal {
require(_recipient != address(0), "DDX: cannot transfer to the zero address.");
// Add to recipient's balance
balances[_recipient] = balances[_recipient].add96(_amount);
// Increase the issued supply and circulating supply
issuedSupply = issuedSupply.add96(_amount);
totalSupply = totalSupply.add96(_amount);
emit Transfer(address(0), _recipient, _amount);
// Add delegates to recipient's delegated address
_moveDelegates(address(0), _getDelegatee(_recipient), _amount);
}
function _transferTokensBurn(address _spender, uint96 _amount) internal {
require(_spender != address(0), "DDX: cannot transfer from the zero address.");
// Reduce the spender/burner's balance
balances[_spender] = balances[_spender].sub96(_amount, "DDX: not enough balance to burn.");
// Reduce the total supply
totalSupply = totalSupply.sub96(_amount);
emit Transfer(_spender, address(0), _amount);
// MRedduce delegates from spender's delegated address
_moveDelegates(_getDelegatee(_spender), address(0), _amount);
}
function _moveDelegates(
address _initDel,
address _finDel,
uint96 _amount
) internal {
if (_initDel != _finDel && _amount > 0) {
// Initial delegated address is different than final
// delegated address and nonzero number of votes moved
if (_initDel != address(0)) {
uint256 initDelNum = numCheckpoints[_initDel];
// Retrieve and compute the old and new initial delegate
// address' votes
uint96 initDelOld = initDelNum > 0 ? checkpoints[_initDel][initDelNum - 1].votes : 0;
uint96 initDelNew = initDelOld.sub96(_amount);
_writeCheckpoint(_initDel, initDelOld, initDelNew);
}
if (_finDel != address(0)) {
uint256 finDelNum = numCheckpoints[_finDel];
// Retrieve and compute the old and new final delegate
// address' votes
uint96 finDelOld = finDelNum > 0 ? checkpoints[_finDel][finDelNum - 1].votes : 0;
uint96 finDelNew = finDelOld.add96(_amount);
_writeCheckpoint(_finDel, finDelOld, finDelNew);
}
}
}
function _writeCheckpoint(
address _delegatee,
uint96 _oldVotes,
uint96 _newVotes
) internal {
uint32 blockNumber = safe32(block.number, "DDX: exceeds 32 bits.");
uint256 delNum = numCheckpoints[_delegatee];
if (delNum > 0 && checkpoints[_delegatee][delNum - 1].id == blockNumber) {
// If latest checkpoint is current block, edit in place
checkpoints[_delegatee][delNum - 1].votes = _newVotes;
} else {
// Create a new id, vote pair
checkpoints[_delegatee][delNum] = Checkpoint({ id: blockNumber, votes: _newVotes });
numCheckpoints[_delegatee] = delNum.add(1);
}
emit DelegateVotesChanged(_delegatee, _oldVotes, _newVotes);
}
function _getDelegatee(address _delegator) internal view returns (address) {
if (delegates[_delegator] == address(0)) {
return _delegator;
}
return delegates[_delegator];
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// SPDX-License-Identifier: MIT
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.12;
import { LibEIP712 } from "./LibEIP712.sol";
library LibDelegation {
struct Delegation {
address delegatee; // Delegatee
uint256 nonce; // Nonce
uint256 expiry; // Expiry
}
// Hash for the EIP712 OrderParams Schema
// bytes32 constant internal EIP712_DELEGATION_SCHEMA_HASH = keccak256(abi.encodePacked(
// "Delegation(",
// "address delegatee,",
// "uint256 nonce,",
// "uint256 expiry",
// ")"
// ));
bytes32 internal constant EIP712_DELEGATION_SCHEMA_HASH =
0xe48329057bfd03d55e49b547132e39cffd9c1820ad7b9d4c5307691425d15adf;
/// @dev Calculates Keccak-256 hash of the delegation.
/// @param delegation The delegation structure.
/// @return delegationHash Keccak-256 EIP712 hash of the delegation.
function getDelegationHash(Delegation memory delegation, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 delegationHash)
{
delegationHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashDelegation(delegation));
return delegationHash;
}
/// @dev Calculates EIP712 hash of the delegation.
/// @param delegation The delegation structure.
/// @return result EIP712 hash of the delegation.
function hashDelegation(Delegation memory delegation) internal pure returns (bytes32 result) {
// Assembly for more efficiently computing:
bytes32 schemaHash = EIP712_DELEGATION_SCHEMA_HASH;
assembly {
// Assert delegation offset (this is an internal error that should never be triggered)
if lt(delegation, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(delegation, 32)
// Backup
let temp1 := mload(pos1)
// Hash in place
mstore(pos1, schemaHash)
result := keccak256(pos1, 128)
// Restore
mstore(pos1, temp1)
}
return result;
}
}
// SPDX-License-Identifier: MIT
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.12;
import { LibEIP712 } from "./LibEIP712.sol";
library LibVoteCast {
struct VoteCast {
uint128 proposalId; // Proposal ID
bool support; // Support
}
// Hash for the EIP712 OrderParams Schema
// bytes32 constant internal EIP712_VOTE_CAST_SCHEMA_HASH = keccak256(abi.encodePacked(
// "VoteCast(",
// "uint128 proposalId,",
// "bool support",
// ")"
// ));
bytes32 internal constant EIP712_VOTE_CAST_SCHEMA_HASH =
0x4abb8ae9facc09d5584ac64f616551bfc03c3ac63e5c431132305bd9bc8f8246;
/// @dev Calculates Keccak-256 hash of the vote cast.
/// @param voteCast The vote cast structure.
/// @return voteCastHash Keccak-256 EIP712 hash of the vote cast.
function getVoteCastHash(VoteCast memory voteCast, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 voteCastHash)
{
voteCastHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashVoteCast(voteCast));
return voteCastHash;
}
/// @dev Calculates EIP712 hash of the vote cast.
/// @param voteCast The vote cast structure.
/// @return result EIP712 hash of the vote cast.
function hashVoteCast(VoteCast memory voteCast) internal pure returns (bytes32 result) {
// Assembly for more efficiently computing:
bytes32 schemaHash = EIP712_VOTE_CAST_SCHEMA_HASH;
assembly {
// Assert vote cast offset (this is an internal error that should never be triggered)
if lt(voteCast, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(voteCast, 32)
// Backup
let temp1 := mload(pos1)
// Hash in place
mstore(pos1, schemaHash)
result := keccak256(pos1, 96)
// Restore
mstore(pos1, temp1)
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { GovernanceDefs } from "../../libs/defs/GovernanceDefs.sol";
import { LibEIP712 } from "../../libs/LibEIP712.sol";
import { LibVoteCast } from "../../libs/LibVoteCast.sol";
import { LibBytes } from "../../libs/LibBytes.sol";
import { SafeMath32 } from "../../libs/SafeMath32.sol";
import { SafeMath96 } from "../../libs/SafeMath96.sol";
import { SafeMath128 } from "../../libs/SafeMath128.sol";
import { MathHelpers } from "../../libs/MathHelpers.sol";
import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol";
import { LibDiamondStorageGovernance } from "../../storage/LibDiamondStorageGovernance.sol";
/**
* @title Governance
* @author DerivaDEX (Borrowed/inspired from Compound)
* @notice This is a facet to the DerivaDEX proxy contract that handles
* the logic pertaining to governance. The Diamond storage
* will only be affected when facet functions are called via
* the proxy contract, no checks are necessary.
* @dev The Diamond storage will only be affected when facet functions
* are called via the proxy contract, no checks are necessary.
*/
contract Governance {
using SafeMath32 for uint32;
using SafeMath96 for uint96;
using SafeMath128 for uint128;
using SafeMath for uint256;
using MathHelpers for uint96;
using MathHelpers for uint256;
using LibBytes for bytes;
/// @notice name for this Governance contract
string public constant name = "DDX Governance"; // solhint-disable-line const-name-snakecase
/// @notice version for this Governance contract
string public constant version = "1"; // solhint-disable-line const-name-snakecase
/// @notice Emitted when a new proposal is created
event ProposalCreated(
uint128 indexed id,
address indexed proposer,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
uint256 startBlock,
uint256 endBlock,
string description
);
/// @notice Emitted when a vote has been cast on a proposal
event VoteCast(address indexed voter, uint128 indexed proposalId, bool support, uint96 votes);
/// @notice Emitted when a proposal has been canceled
event ProposalCanceled(uint128 indexed id);
/// @notice Emitted when a proposal has been queued
event ProposalQueued(uint128 indexed id, uint256 eta);
/// @notice Emitted when a proposal has been executed
event ProposalExecuted(uint128 indexed id);
/// @notice Emitted when a proposal action has been canceled
event CancelTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
/// @notice Emitted when a proposal action has been executed
event ExecuteTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
/// @notice Emitted when a proposal action has been queued
event QueueTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
/**
* @notice Limits functions to only be called via governance.
*/
modifier onlyAdmin {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
require(msg.sender == dsDerivaDEX.admin, "Governance: must be called by Governance admin.");
_;
}
/**
* @notice This function initializes the state with some critical
* information. This can only be called once and must be
* done via governance.
* @dev This function is best called as a parameter to the
* diamond cut function. This is removed prior to the selectors
* being added to the diamond, meaning it cannot be called
* again.
* @param _quorumVotes Minimum number of for votes required, even
* if there's a majority in favor.
* @param _proposalThreshold Minimum DDX token holdings required
* to create a proposal
* @param _proposalMaxOperations Max number of operations/actions a
* proposal can have
* @param _votingDelay Number of blocks after a proposal is made
* that voting begins.
* @param _votingPeriod Number of blocks voting will be held.
* @param _skipRemainingVotingThreshold Number of for or against
* votes that are necessary to skip the remainder of the
* voting period.
* @param _gracePeriod Period in which a successful proposal must be
* executed, otherwise will be expired.
* @param _timelockDelay Time (s) in which a successful proposal
* must be in the queue before it can be executed.
*/
function initialize(
uint32 _proposalMaxOperations,
uint32 _votingDelay,
uint32 _votingPeriod,
uint32 _gracePeriod,
uint32 _timelockDelay,
uint32 _quorumVotes,
uint32 _proposalThreshold,
uint32 _skipRemainingVotingThreshold
) external onlyAdmin {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
// Ensure state variable comparisons are valid
requireValidSkipRemainingVotingThreshold(_skipRemainingVotingThreshold);
requireSkipRemainingVotingThresholdGtQuorumVotes(_skipRemainingVotingThreshold, _quorumVotes);
// Set initial variable values
dsGovernance.proposalMaxOperations = _proposalMaxOperations;
dsGovernance.votingDelay = _votingDelay;
dsGovernance.votingPeriod = _votingPeriod;
dsGovernance.gracePeriod = _gracePeriod;
dsGovernance.timelockDelay = _timelockDelay;
dsGovernance.quorumVotes = _quorumVotes;
dsGovernance.proposalThreshold = _proposalThreshold;
dsGovernance.skipRemainingVotingThreshold = _skipRemainingVotingThreshold;
dsGovernance.fastPathFunctionSignatures["setIsPaused(bool)"] = true;
}
/**
* @notice This function allows participants who have sufficient
* DDX holdings to create new proposals up for vote. The
* proposals contain the ordered lists of on-chain
* executable calldata.
* @param _targets Addresses of contracts involved.
* @param _values Values to be passed along with the calls.
* @param _signatures Function signatures.
* @param _calldatas Calldata passed to the function.
* @param _description Text description of proposal.
*/
function propose(
address[] memory _targets,
uint256[] memory _values,
string[] memory _signatures,
bytes[] memory _calldatas,
string memory _description
) external returns (uint128) {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
// Ensure proposer has sufficient token holdings to propose
require(
dsDerivaDEX.ddxToken.getPriorVotes(msg.sender, block.number.sub(1)) >= getProposerThresholdCount(),
"Governance: proposer votes below proposal threshold."
);
require(
_targets.length == _values.length &&
_targets.length == _signatures.length &&
_targets.length == _calldatas.length,
"Governance: proposal function information parity mismatch."
);
require(_targets.length != 0, "Governance: must provide actions.");
require(_targets.length <= dsGovernance.proposalMaxOperations, "Governance: too many actions.");
if (dsGovernance.latestProposalIds[msg.sender] != 0) {
// Ensure proposer doesn't already have one active/pending
GovernanceDefs.ProposalState proposersLatestProposalState =
state(dsGovernance.latestProposalIds[msg.sender]);
require(
proposersLatestProposalState != GovernanceDefs.ProposalState.Active,
"Governance: one live proposal per proposer, found an already active proposal."
);
require(
proposersLatestProposalState != GovernanceDefs.ProposalState.Pending,
"Governance: one live proposal per proposer, found an already pending proposal."
);
}
// Proposal voting starts votingDelay after proposal is made
uint256 startBlock = block.number.add(dsGovernance.votingDelay);
// Increment count of proposals
dsGovernance.proposalCount++;
// Create new proposal struct and add to mapping
GovernanceDefs.Proposal memory newProposal =
GovernanceDefs.Proposal({
id: dsGovernance.proposalCount,
proposer: msg.sender,
delay: getTimelockDelayForSignatures(_signatures),
eta: 0,
targets: _targets,
values: _values,
signatures: _signatures,
calldatas: _calldatas,
startBlock: startBlock,
endBlock: startBlock.add(dsGovernance.votingPeriod),
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
dsGovernance.proposals[newProposal.id] = newProposal;
// Update proposer's latest proposal
dsGovernance.latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(
newProposal.id,
msg.sender,
_targets,
_values,
_signatures,
_calldatas,
startBlock,
startBlock.add(dsGovernance.votingPeriod),
_description
);
return newProposal.id;
}
/**
* @notice This function allows any participant to queue a
* successful proposal for execution. Proposals are deemed
* successful if at any point the number of for votes has
* exceeded the skip remaining voting threshold or if there
* is a simple majority (and more for votes than the
* minimum quorum) at the end of voting.
* @param _proposalId Proposal id.
*/
function queue(uint128 _proposalId) external {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
// Ensure proposal has succeeded (i.e. it has either enough for
// votes to skip the remainder of the voting period or the
// voting period has ended and there is a simple majority in
// favor and also above the quorum
require(
state(_proposalId) == GovernanceDefs.ProposalState.Succeeded,
"Governance: proposal can only be queued if it is succeeded."
);
GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId];
// Establish eta of execution, which is a number of seconds
// after queuing at which point proposal can actually execute
uint256 eta = block.timestamp.add(proposal.delay);
for (uint256 i = 0; i < proposal.targets.length; i++) {
// Ensure proposal action is not already in the queue
bytes32 txHash =
keccak256(
abi.encode(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
eta
)
);
require(!dsGovernance.queuedTransactions[txHash], "Governance: proposal action already queued at eta.");
dsGovernance.queuedTransactions[txHash] = true;
emit QueueTransaction(
txHash,
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
eta
);
}
// Set proposal eta timestamp after which it can be executed
proposal.eta = eta;
emit ProposalQueued(_proposalId, eta);
}
/**
* @notice This function allows any participant to execute a
* queued proposal. A proposal in the queue must be in the
* queue for the delay period it was proposed with prior to
* executing, allowing the community to position itself
* accordingly.
* @param _proposalId Proposal id.
*/
function execute(uint128 _proposalId) external payable {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
// Ensure proposal is queued
require(
state(_proposalId) == GovernanceDefs.ProposalState.Queued,
"Governance: proposal can only be executed if it is queued."
);
GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId];
// Ensure proposal has been in the queue long enough
require(block.timestamp >= proposal.eta, "Governance: proposal hasn't finished queue time length.");
// Ensure proposal hasn't been in the queue for too long
require(block.timestamp <= proposal.eta.add(dsGovernance.gracePeriod), "Governance: transaction is stale.");
proposal.executed = true;
// Loop through each of the actions in the proposal
for (uint256 i = 0; i < proposal.targets.length; i++) {
bytes32 txHash =
keccak256(
abi.encode(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
)
);
require(dsGovernance.queuedTransactions[txHash], "Governance: transaction hasn't been queued.");
dsGovernance.queuedTransactions[txHash] = false;
// Execute action
bytes memory callData;
require(bytes(proposal.signatures[i]).length != 0, "Governance: Invalid function signature.");
callData = abi.encodePacked(bytes4(keccak256(bytes(proposal.signatures[i]))), proposal.calldatas[i]);
// solium-disable-next-line security/no-call-value
(bool success, ) = proposal.targets[i].call{ value: proposal.values[i] }(callData);
require(success, "Governance: transaction execution reverted.");
emit ExecuteTransaction(
txHash,
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
);
}
emit ProposalExecuted(_proposalId);
}
/**
* @notice This function allows any participant to cancel any non-
* executed proposal. It can be canceled if the proposer's
* token holdings has dipped below the proposal threshold
* at the time of cancellation.
* @param _proposalId Proposal id.
*/
function cancel(uint128 _proposalId) external {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
GovernanceDefs.ProposalState state = state(_proposalId);
// Ensure proposal hasn't executed
require(state != GovernanceDefs.ProposalState.Executed, "Governance: cannot cancel executed proposal.");
GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId];
// Ensure proposer's token holdings has dipped below the
// proposer threshold, leaving their proposal subject to
// cancellation
require(
dsDerivaDEX.ddxToken.getPriorVotes(proposal.proposer, block.number.sub(1)) < getProposerThresholdCount(),
"Governance: proposer above threshold."
);
proposal.canceled = true;
// Loop through each of the proposal's actions
for (uint256 i = 0; i < proposal.targets.length; i++) {
bytes32 txHash =
keccak256(
abi.encode(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
)
);
dsGovernance.queuedTransactions[txHash] = false;
emit CancelTransaction(
txHash,
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
);
}
emit ProposalCanceled(_proposalId);
}
/**
* @notice This function allows participants to cast either in
* favor or against a particular proposal.
* @param _proposalId Proposal id.
* @param _support In favor (true) or against (false).
*/
function castVote(uint128 _proposalId, bool _support) external {
return _castVote(msg.sender, _proposalId, _support);
}
/**
* @notice This function allows participants to cast votes with
* offline signatures in favor or against a particular
* proposal.
* @param _proposalId Proposal id.
* @param _support In favor (true) or against (false).
* @param _signature Signature
*/
function castVoteBySig(
uint128 _proposalId,
bool _support,
bytes memory _signature
) external {
// EIP712 hashing logic
bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this));
bytes32 voteCastHash =
LibVoteCast.getVoteCastHash(
LibVoteCast.VoteCast({ proposalId: _proposalId, support: _support }),
eip712OrderParamsDomainHash
);
// Recover the signature and EIP712 hash
uint8 v = uint8(_signature[0]);
bytes32 r = _signature.readBytes32(1);
bytes32 s = _signature.readBytes32(33);
address recovered = ecrecover(voteCastHash, v, r, s);
require(recovered != address(0), "Governance: invalid signature.");
return _castVote(recovered, _proposalId, _support);
}
/**
* @notice This function sets the quorum votes required for a
* proposal to pass. It must be called via
* governance.
* @param _quorumVotes Quorum votes threshold.
*/
function setQuorumVotes(uint32 _quorumVotes) external onlyAdmin {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
requireSkipRemainingVotingThresholdGtQuorumVotes(dsGovernance.skipRemainingVotingThreshold, _quorumVotes);
dsGovernance.quorumVotes = _quorumVotes;
}
/**
* @notice This function sets the token holdings threshold required
* to propose something. It must be called via
* governance.
* @param _proposalThreshold Proposal threshold.
*/
function setProposalThreshold(uint32 _proposalThreshold) external onlyAdmin {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
dsGovernance.proposalThreshold = _proposalThreshold;
}
/**
* @notice This function sets the max operations a proposal can
* carry out. It must be called via governance.
* @param _proposalMaxOperations Proposal's max operations.
*/
function setProposalMaxOperations(uint32 _proposalMaxOperations) external onlyAdmin {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
dsGovernance.proposalMaxOperations = _proposalMaxOperations;
}
/**
* @notice This function sets the voting delay in blocks from when
* a proposal is made and voting begins. It must be called
* via governance.
* @param _votingDelay Voting delay (blocks).
*/
function setVotingDelay(uint32 _votingDelay) external onlyAdmin {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
dsGovernance.votingDelay = _votingDelay;
}
/**
* @notice This function sets the voting period in blocks that a
* vote will last. It must be called via
* governance.
* @param _votingPeriod Voting period (blocks).
*/
function setVotingPeriod(uint32 _votingPeriod) external onlyAdmin {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
dsGovernance.votingPeriod = _votingPeriod;
}
/**
* @notice This function sets the threshold at which a proposal can
* immediately be deemed successful or rejected if the for
* or against votes exceeds this threshold, even if the
* voting period is still ongoing. It must be called
* governance.
* @param _skipRemainingVotingThreshold Threshold for or against
* votes must reach to skip remainder of voting period.
*/
function setSkipRemainingVotingThreshold(uint32 _skipRemainingVotingThreshold) external onlyAdmin {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
requireValidSkipRemainingVotingThreshold(_skipRemainingVotingThreshold);
requireSkipRemainingVotingThresholdGtQuorumVotes(_skipRemainingVotingThreshold, dsGovernance.quorumVotes);
dsGovernance.skipRemainingVotingThreshold = _skipRemainingVotingThreshold;
}
/**
* @notice This function sets the grace period in seconds that a
* queued proposal can last before expiring. It must be
* called via governance.
* @param _gracePeriod Grace period (seconds).
*/
function setGracePeriod(uint32 _gracePeriod) external onlyAdmin {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
dsGovernance.gracePeriod = _gracePeriod;
}
/**
* @notice This function sets the timelock delay (s) a proposal
* must be queued before execution.
* @param _timelockDelay Timelock delay (seconds).
*/
function setTimelockDelay(uint32 _timelockDelay) external onlyAdmin {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
dsGovernance.timelockDelay = _timelockDelay;
}
/**
* @notice This function allows any participant to retrieve
* the actions involved in a given proposal.
* @param _proposalId Proposal id.
* @return targets Addresses of contracts involved.
* @return values Values to be passed along with the calls.
* @return signatures Function signatures.
* @return calldatas Calldata passed to the function.
*/
function getActions(uint128 _proposalId)
external
view
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
)
{
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
GovernanceDefs.Proposal storage p = dsGovernance.proposals[_proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
/**
* @notice This function allows any participant to retrieve
* the receipt for a given proposal and voter.
* @param _proposalId Proposal id.
* @param _voter Voter address.
* @return Voter receipt.
*/
function getReceipt(uint128 _proposalId, address _voter) external view returns (GovernanceDefs.Receipt memory) {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
return dsGovernance.proposals[_proposalId].receipts[_voter];
}
/**
* @notice This function gets a proposal from an ID.
* @param _proposalId Proposal id.
* @return Proposal attributes.
*/
function getProposal(uint128 _proposalId)
external
view
returns (
bool,
bool,
address,
uint32,
uint96,
uint96,
uint128,
uint256,
uint256,
uint256
)
{
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
GovernanceDefs.Proposal memory proposal = dsGovernance.proposals[_proposalId];
return (
proposal.canceled,
proposal.executed,
proposal.proposer,
proposal.delay,
proposal.forVotes,
proposal.againstVotes,
proposal.id,
proposal.eta,
proposal.startBlock,
proposal.endBlock
);
}
/**
* @notice This function gets whether a proposal action transaction
* hash is queued or not.
* @param _txHash Proposal action tx hash.
* @return Is proposal action transaction hash queued or not.
*/
function getIsQueuedTransaction(bytes32 _txHash) external view returns (bool) {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
return dsGovernance.queuedTransactions[_txHash];
}
/**
* @notice This function gets the Governance facet's current
* parameters.
* @return Proposal max operations.
* @return Voting delay.
* @return Voting period.
* @return Grace period.
* @return Timelock delay.
* @return Quorum votes threshold.
* @return Proposal threshold.
* @return Skip remaining voting threshold.
*/
function getGovernanceParameters()
external
view
returns (
uint32,
uint32,
uint32,
uint32,
uint32,
uint32,
uint32,
uint32
)
{
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
return (
dsGovernance.proposalMaxOperations,
dsGovernance.votingDelay,
dsGovernance.votingPeriod,
dsGovernance.gracePeriod,
dsGovernance.timelockDelay,
dsGovernance.quorumVotes,
dsGovernance.proposalThreshold,
dsGovernance.skipRemainingVotingThreshold
);
}
/**
* @notice This function gets the proposal count.
* @return Proposal count.
*/
function getProposalCount() external view returns (uint128) {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
return dsGovernance.proposalCount;
}
/**
* @notice This function gets the latest proposal ID for a user.
* @param _proposer Proposer's address.
* @return Proposal ID.
*/
function getLatestProposalId(address _proposer) external view returns (uint128) {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
return dsGovernance.latestProposalIds[_proposer];
}
/**
* @notice This function gets the quorum vote count given the
* quorum vote percentage relative to the total DDX supply.
* @return Quorum vote count.
*/
function getQuorumVoteCount() public view returns (uint96) {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits");
return totalSupply.proportion96(dsGovernance.quorumVotes, 100);
}
/**
* @notice This function gets the quorum vote count given the
* quorum vote percentage relative to the total DDX supply.
* @return Quorum vote count.
*/
function getProposerThresholdCount() public view returns (uint96) {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits");
return totalSupply.proportion96(dsGovernance.proposalThreshold, 100);
}
/**
* @notice This function gets the quorum vote count given the
* quorum vote percentage relative to the total DDX supply.
* @return Quorum vote count.
*/
function getSkipRemainingVotingThresholdCount() public view returns (uint96) {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits");
return totalSupply.proportion96(dsGovernance.skipRemainingVotingThreshold, 100);
}
/**
* @notice This function retrieves the status for any given
* proposal.
* @param _proposalId Proposal id.
* @return Status of proposal.
*/
function state(uint128 _proposalId) public view returns (GovernanceDefs.ProposalState) {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
require(dsGovernance.proposalCount >= _proposalId && _proposalId > 0, "Governance: invalid proposal id.");
GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId];
// Note the 3rd conditional where we can escape out of the vote
// phase if the for or against votes exceeds the skip remaining
// voting threshold
if (proposal.canceled) {
return GovernanceDefs.ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return GovernanceDefs.ProposalState.Pending;
} else if (
(block.number <= proposal.endBlock) &&
(proposal.forVotes < getSkipRemainingVotingThresholdCount()) &&
(proposal.againstVotes < getSkipRemainingVotingThresholdCount())
) {
return GovernanceDefs.ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < getQuorumVoteCount()) {
return GovernanceDefs.ProposalState.Defeated;
} else if (proposal.eta == 0) {
return GovernanceDefs.ProposalState.Succeeded;
} else if (proposal.executed) {
return GovernanceDefs.ProposalState.Executed;
} else if (block.timestamp >= proposal.eta.add(dsGovernance.gracePeriod)) {
return GovernanceDefs.ProposalState.Expired;
} else {
return GovernanceDefs.ProposalState.Queued;
}
}
function _castVote(
address _voter,
uint128 _proposalId,
bool _support
) internal {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
require(state(_proposalId) == GovernanceDefs.ProposalState.Active, "Governance: voting is closed.");
GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId];
GovernanceDefs.Receipt storage receipt = proposal.receipts[_voter];
// Ensure voter has not already voted
require(!receipt.hasVoted, "Governance: voter already voted.");
// Obtain the token holdings (voting power) for participant at
// the time voting started. They may have gained or lost tokens
// since then, doesn't matter.
uint96 votes = dsDerivaDEX.ddxToken.getPriorVotes(_voter, proposal.startBlock);
// Ensure voter has nonzero voting power
require(votes > 0, "Governance: voter has no voting power.");
if (_support) {
// Increment the for votes in favor
proposal.forVotes = proposal.forVotes.add96(votes);
} else {
// Increment the against votes
proposal.againstVotes = proposal.againstVotes.add96(votes);
}
// Set receipt attributes based on cast vote parameters
receipt.hasVoted = true;
receipt.support = _support;
receipt.votes = votes;
emit VoteCast(_voter, _proposalId, _support, votes);
}
function getTimelockDelayForSignatures(string[] memory _signatures) internal view returns (uint32) {
LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance =
LibDiamondStorageGovernance.diamondStorageGovernance();
for (uint256 i = 0; i < _signatures.length; i++) {
if (!dsGovernance.fastPathFunctionSignatures[_signatures[i]]) {
return dsGovernance.timelockDelay;
}
}
return 1;
}
function requireSkipRemainingVotingThresholdGtQuorumVotes(uint32 _skipRemainingVotingThreshold, uint32 _quorumVotes)
internal
pure
{
require(_skipRemainingVotingThreshold > _quorumVotes, "Governance: skip rem votes must be higher than quorum.");
}
function requireValidSkipRemainingVotingThreshold(uint32 _skipRemainingVotingThreshold) internal pure {
require(_skipRemainingVotingThreshold >= 50, "Governance: skip rem votes must be higher than 50pct.");
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/**
* @title GovernanceDefs
* @author DerivaDEX
*
* This library contains the common structs and enums pertaining to
* the governance.
*/
library GovernanceDefs {
struct Proposal {
bool canceled;
bool executed;
address proposer;
uint32 delay;
uint96 forVotes;
uint96 againstVotes;
uint128 id;
uint256 eta;
address[] targets;
string[] signatures;
bytes[] calldatas;
uint256[] values;
uint256 startBlock;
uint256 endBlock;
mapping(address => Receipt) receipts;
}
struct Receipt {
bool hasVoted;
bool support;
uint96 votes;
}
enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed }
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 c = a + b;
require(c >= a, "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(uint128 a, uint128 b) internal pure returns (uint128) {
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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b <= a, errorMessage);
uint128 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint128 a, uint128 b) internal pure returns (uint128) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint128 c = a * b;
require(c / a == b, "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(uint128 a, uint128 b) internal pure returns (uint128) {
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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b > 0, errorMessage);
uint128 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint128 a, uint128 b) internal pure returns (uint128) {
return mod(a, b, "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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { GovernanceDefs } from "../libs/defs/GovernanceDefs.sol";
library LibDiamondStorageGovernance {
struct DiamondStorageGovernance {
// Proposal struct by ID
mapping(uint256 => GovernanceDefs.Proposal) proposals;
// Latest proposal IDs by proposer address
mapping(address => uint128) latestProposalIds;
// Whether transaction hash is currently queued
mapping(bytes32 => bool) queuedTransactions;
// Fast path for governance
mapping(string => bool) fastPathFunctionSignatures;
// Max number of operations/actions a proposal can have
uint32 proposalMaxOperations;
// Number of blocks after a proposal is made that voting begins
// (e.g. 1 block)
uint32 votingDelay;
// Number of blocks voting will be held
// (e.g. 17280 blocks ~ 3 days of blocks)
uint32 votingPeriod;
// Time window (s) a successful proposal must be executed,
// otherwise will be expired, measured in seconds
// (e.g. 1209600 seconds)
uint32 gracePeriod;
// Minimum time (s) in which a successful proposal must be
// in the queue before it can be executed
// (e.g. 0 seconds)
uint32 minimumDelay;
// Maximum time (s) in which a successful proposal must be
// in the queue before it can be executed
// (e.g. 2592000 seconds ~ 30 days)
uint32 maximumDelay;
// Minimum number of for votes required, even if there's a
// majority in favor
// (e.g. 2000000e18 ~ 4% of pre-mine DDX supply)
uint32 quorumVotes;
// Minimum DDX token holdings required to create a proposal
// (e.g. 500000e18 ~ 1% of pre-mine DDX supply)
uint32 proposalThreshold;
// Number of for or against votes that are necessary to skip
// the remainder of the voting period
// (e.g. 25000000e18 tokens/votes)
uint32 skipRemainingVotingThreshold;
// Time (s) proposals must be queued before executing
uint32 timelockDelay;
// Total number of proposals
uint128 proposalCount;
}
bytes32 constant DIAMOND_STORAGE_POSITION_GOVERNANCE =
keccak256("diamond.standard.diamond.storage.DerivaDEX.Governance");
function diamondStorageGovernance() internal pure returns (DiamondStorageGovernance storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION_GOVERNANCE;
assembly {
ds_slot := position
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol";
import { LibDiamondStoragePause } from "../../storage/LibDiamondStoragePause.sol";
/**
* @title Pause
* @author DerivaDEX
* @notice This is a facet to the DerivaDEX proxy contract that handles
* the logic pertaining to pausing functionality. The purpose
* of this is to ensure the system can pause in the unlikely
* scenario of a bug or issue materially jeopardizing users'
* funds or experience. This facet will be removed entirely
* as the system stabilizes shortly. It's important to note that
* unlike the vast majority of projects, even during this
* short-lived period of time in which the system can be paused,
* no single admin address can wield this power, but rather
* pausing must be carried out via governance.
*/
contract Pause {
event PauseInitialized();
event IsPausedSet(bool isPaused);
/**
* @notice Limits functions to only be called via governance.
*/
modifier onlyAdmin {
LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX =
LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX();
require(msg.sender == dsDerivaDEX.admin, "Pause: must be called by Gov.");
_;
}
/**
* @notice This function initializes the facet.
*/
function initialize() external onlyAdmin {
emit PauseInitialized();
}
/**
* @notice This function sets the paused status.
* @param _isPaused Whether contracts are paused or not.
*/
function setIsPaused(bool _isPaused) external onlyAdmin {
LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause();
dsPause.isPaused = _isPaused;
emit IsPausedSet(_isPaused);
}
/**
* @notice This function gets whether the contract ecosystem is
* currently paused.
* @return Whether contracts are paused or not.
*/
function getIsPaused() public view returns (bool) {
LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause();
return dsPause.isPaused;
}
}
// SPDX-License-Identifier: MIT
/**
*Submitted for verification at Etherscan.io on 2019-07-18
*/
pragma solidity 0.6.12;
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { Ownable } from "openzeppelin-solidity/contracts/access/Ownable.sol";
import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
library Roles {
struct Role {
mapping(address => bool) bearer;
}
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
contract PauserRole is Ownable {
using Roles for Roles.Role;
Roles.Role private _pausers;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
constructor() internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyOwner {
_addPauser(account);
}
function removePauser(address account) public onlyOwner {
_removePauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
contract Pausable is PauserRole {
bool private _paused;
event Paused(address account);
event Unpaused(address account);
constructor() internal {
_paused = false;
}
function paused() public view returns (bool) {
return _paused;
}
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
contract ERC20 is IERC20, Ownable {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
event Issue(address indexed account, uint256 amount);
event Redeem(address indexed account, uint256 value);
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 value) public virtual override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _approve(
address owner,
address spender,
uint256 value
) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _issue(address account, uint256 amount) internal {
require(account != address(0), "CoinFactory: issue to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
emit Issue(account, amount);
}
function _redeem(address account, uint256 value) internal {
require(account != address(0), "CoinFactory: redeem from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
emit Redeem(account, value);
}
}
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public virtual override whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(
address from,
address to,
uint256 value
) public virtual override whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public virtual override whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
override
whenNotPaused
returns (bool)
{
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
override
whenNotPaused
returns (bool)
{
return super.decreaseAllowance(spender, subtractedValue);
}
}
contract CoinFactoryAdminRole is Ownable {
using Roles for Roles.Role;
event CoinFactoryAdminRoleAdded(address indexed account);
event CoinFactoryAdminRoleRemoved(address indexed account);
Roles.Role private _coinFactoryAdmins;
constructor() internal {
_addCoinFactoryAdmin(msg.sender);
}
modifier onlyCoinFactoryAdmin() {
require(isCoinFactoryAdmin(msg.sender), "CoinFactoryAdminRole: caller does not have the CoinFactoryAdmin role");
_;
}
function isCoinFactoryAdmin(address account) public view returns (bool) {
return _coinFactoryAdmins.has(account);
}
function addCoinFactoryAdmin(address account) public onlyOwner {
_addCoinFactoryAdmin(account);
}
function removeCoinFactoryAdmin(address account) public onlyOwner {
_removeCoinFactoryAdmin(account);
}
function renounceCoinFactoryAdmin() public {
_removeCoinFactoryAdmin(msg.sender);
}
function _addCoinFactoryAdmin(address account) internal {
_coinFactoryAdmins.add(account);
emit CoinFactoryAdminRoleAdded(account);
}
function _removeCoinFactoryAdmin(address account) internal {
_coinFactoryAdmins.remove(account);
emit CoinFactoryAdminRoleRemoved(account);
}
}
contract CoinFactory is ERC20, CoinFactoryAdminRole {
function issue(address account, uint256 amount) public onlyCoinFactoryAdmin returns (bool) {
_issue(account, amount);
return true;
}
function redeem(address account, uint256 amount) public onlyCoinFactoryAdmin returns (bool) {
_redeem(account, amount);
return true;
}
}
contract BlacklistAdminRole is Ownable {
using Roles for Roles.Role;
event BlacklistAdminAdded(address indexed account);
event BlacklistAdminRemoved(address indexed account);
Roles.Role private _blacklistAdmins;
constructor() internal {
_addBlacklistAdmin(msg.sender);
}
modifier onlyBlacklistAdmin() {
require(isBlacklistAdmin(msg.sender), "BlacklistAdminRole: caller does not have the BlacklistAdmin role");
_;
}
function isBlacklistAdmin(address account) public view returns (bool) {
return _blacklistAdmins.has(account);
}
function addBlacklistAdmin(address account) public onlyOwner {
_addBlacklistAdmin(account);
}
function removeBlacklistAdmin(address account) public onlyOwner {
_removeBlacklistAdmin(account);
}
function renounceBlacklistAdmin() public {
_removeBlacklistAdmin(msg.sender);
}
function _addBlacklistAdmin(address account) internal {
_blacklistAdmins.add(account);
emit BlacklistAdminAdded(account);
}
function _removeBlacklistAdmin(address account) internal {
_blacklistAdmins.remove(account);
emit BlacklistAdminRemoved(account);
}
}
contract Blacklist is ERC20, BlacklistAdminRole {
mapping(address => bool) private _blacklist;
event BlacklistAdded(address indexed account);
event BlacklistRemoved(address indexed account);
function addBlacklist(address[] memory accounts) public onlyBlacklistAdmin returns (bool) {
for (uint256 i = 0; i < accounts.length; i++) {
_addBlacklist(accounts[i]);
}
}
function removeBlacklist(address[] memory accounts) public onlyBlacklistAdmin returns (bool) {
for (uint256 i = 0; i < accounts.length; i++) {
_removeBlacklist(accounts[i]);
}
}
function isBlacklist(address account) public view returns (bool) {
return _blacklist[account];
}
function _addBlacklist(address account) internal {
_blacklist[account] = true;
emit BlacklistAdded(account);
}
function _removeBlacklist(address account) internal {
_blacklist[account] = false;
emit BlacklistRemoved(account);
}
}
contract HDUMToken is ERC20, ERC20Pausable, CoinFactory, Blacklist {
string public name;
string public symbol;
uint8 public decimals;
uint256 private _totalSupply;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public {
_totalSupply = 0;
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function transfer(address to, uint256 value) public override(ERC20, ERC20Pausable) whenNotPaused returns (bool) {
require(!isBlacklist(msg.sender), "HDUMToken: caller in blacklist can't transfer");
require(!isBlacklist(to), "HDUMToken: not allow to transfer to recipient address in blacklist");
return super.transfer(to, value);
}
function transferFrom(
address from,
address to,
uint256 value
) public override(ERC20, ERC20Pausable) whenNotPaused returns (bool) {
require(!isBlacklist(msg.sender), "HDUMToken: caller in blacklist can't transferFrom");
require(!isBlacklist(from), "HDUMToken: from in blacklist can't transfer");
require(!isBlacklist(to), "HDUMToken: not allow to transfer to recipient address in blacklist");
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public virtual override(ERC20, ERC20Pausable) returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
override(ERC20, ERC20Pausable)
returns (bool)
{
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
override(ERC20, ERC20Pausable)
returns (bool)
{
return super.decreaseAllowance(spender, subtractedValue);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { Context } from "openzeppelin-solidity/contracts/GSN/Context.sol";
import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
contract SafeERC20Wrapper is Context {
using SafeERC20 for IERC20;
IERC20 private _token;
constructor(IERC20 token) public {
_token = token;
}
function transfer(address recipient, uint256 amount) public {
_token.safeTransfer(recipient, amount);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public {
_token.safeTransferFrom(sender, recipient, amount);
}
function approve(address spender, uint256 amount) public {
_token.safeApprove(spender, amount);
}
function increaseAllowance(address spender, uint256 amount) public {
_token.safeIncreaseAllowance(spender, amount);
}
function decreaseAllowance(address spender, uint256 amount) public {
_token.safeDecreaseAllowance(spender, amount);
}
function allowance(address owner, address spender) public view returns (uint256) {
return _token.allowance(owner, spender);
}
function balanceOf(address account) public view returns (uint256) {
return _token.balanceOf(account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
// mock class using ERC20
contract DummyToken is ERC20 {
uint256 public constant INITIAL_SUPPLY = 100000000 * (10**18);
constructor(string memory name, string memory symbol) public payable ERC20(name, symbol) {
_mint(msg.sender, INITIAL_SUPPLY);
}
function mint(address account, uint256 amount) public {
_mint(account, amount);
}
function burn(address account, uint256 amount) public {
_burn(account, amount);
}
function transferInternal(
address from,
address to,
uint256 value
) public {
_transfer(from, to, value);
}
function approveInternal(
address owner,
address spender,
uint256 value
) public {
_approve(owner, spender, value);
}
}
|
Reads a uint256 value from a position in a byte array. b Byte array containing a uint256 value. 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;
}
| 1,813,777 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.