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/1/0x1B34C8633a4E513A4796EbF8A41b962a9136dd18/sources/contracts/libs/SafeERC20.sol | Return data is optional solhint-disable-next-line max-line-length | function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
| 9,663,994 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../node_modules/@openzeppelin/contracts/access/Ownable.sol";
import "../node_modules/@openzeppelin/contracts/utils/math/SafeMath.sol";
/*********************************************************************************************************
* @title Voting
* @author
* @dev
***********************************************************************************************************/
contract Voting is Ownable{
using SafeMath for uint256;
struct Voter {
uint votedProposalId;
bool isRegistered;
bool hasVoted;
}
struct Proposal {
string description;
uint voteCount;
}
enum WorkflowStatus {
RegisteringVoters,
ProposalsRegistrationStarted,
ProposalsRegistrationEnded,
VotingSessionStarted,
VotingSessionEnded,
VotesTallied
}
mapping (address => Voter) private electeur;
address[] public addresses;
Proposal [] public proposition;
uint public winningProposalId;
WorkflowStatus public Status = WorkflowStatus.RegisteringVoters;
uint max=0;
event VoterRegistered(address voterAddress);
event ProposalsRegistrationStarted();
event ProposalsRegistrationEnded();
event ProposalRegistered(uint proposalId);
event VotingSessionStarted();
event VotingSessionEnded();
event Voted (address voter, uint proposalId);
event VotesTallied();
event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus);
/*********************************************************************************************************
* @dev L'administrateur du vote enregistre une liste blanche d'électeurs identifiés par leur adresse Ethereum.
* @param _address Adresse Ethereum qui doit etre enregistre
***********************************************************************************************************/
function whitelist(address _address) public onlyOwner{
require(!electeur[_address].isRegistered, "Cette Adresse est deja enregistre!");
require(Status==WorkflowStatus.RegisteringVoters,"La session d'enregistre pour la whitelist doit etre ouverte");
electeur[_address].isRegistered=true;
addresses.push(_address);
emit VoterRegistered(_address);
}
function Nb_Electeur() public view returns(uint){
return addresses.length;
}
/*********************************************************************************************************
* @dev L'administrateur du vote enregistre une liste blanche d'électeurs identifiés par leur adresse Ethereum.
* @param _address Adresse Ethereum qui doit etre enregistre
***********************************************************************************************************/
function getAddresses() public view returns(address[] memory){
return addresses;
}
/*********************************************************************************************************
* @dev StartSessionEnrigrement'administrateur du vote commence la session d'enregistrement de la proposition
*
***********************************************************************************************************/
function StartEnregristrement () public onlyOwner{
require(Status==WorkflowStatus.RegisteringVoters,"La session d'enregistre pour la whitelist doit etre ouverte");
emit ProposalsRegistrationStarted();
Status = WorkflowStatus.ProposalsRegistrationStarted;
emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded,WorkflowStatus.ProposalsRegistrationStarted);
}
/*********************************************************************************************************
* @dev Les électeurs inscrits sont autorisés à enregistrer leurs propositions pendant que la session d'enregistrement est active.
* @param _information _information pour leurs propositions
*
***********************************************************************************************************/
function Addproposal (string memory _information) public{
require(Status == WorkflowStatus.ProposalsRegistrationStarted,"La session de proposition n'est pas Ouvert");
require(electeur[msg.sender].isRegistered==true,"Ne figure pas dans la whitelist");
Proposal memory newPropo = Proposal(_information, 0);
proposition.push(newPropo);
emit ProposalRegistered(proposition.length);
}
function Nb_Proposition() public view returns(uint){
return proposition.length;
}
/*********************************************************************************************************
* @dev L'administrateur de vote met fin à la session d'enregistrement des propositions.
*
***********************************************************************************************************/
function EndEnregristrement () public onlyOwner{
require(Status==WorkflowStatus.ProposalsRegistrationStarted);
emit ProposalsRegistrationEnded();
Status = WorkflowStatus.ProposalsRegistrationEnded;
emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted,WorkflowStatus.ProposalsRegistrationEnded);
}
/*********************************************************************************************************
* @dev L'administrateur du vote commence la session de vote.
*
***********************************************************************************************************/
function StartVote () public onlyOwner{
require(Status==WorkflowStatus.ProposalsRegistrationEnded,"La Session d'enregistrement doit etre ouvert");
emit VotingSessionStarted();
Status = WorkflowStatus.VotingSessionStarted;
emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationEnded,WorkflowStatus.VotingSessionStarted);
}
/*********************************************************************************************************
* @dev Les électeurs inscrits votent pour leurs propositions préférées.
* @param idPropal l'identifiant de la propositions
***********************************************************************************************************/
function Vote (uint idPropal) public {
require(Status == WorkflowStatus.VotingSessionStarted,"La Session de vote doit etre ferme avant");
require(electeur[msg.sender].isRegistered==true,"Ne figure pas dans la whitelist");
require(!electeur[msg.sender].hasVoted,"Vous avez deja vote");
proposition[idPropal].voteCount=proposition[idPropal].voteCount.add(1);
electeur[msg.sender].hasVoted=true;
electeur[msg.sender].votedProposalId=idPropal;
if (proposition[idPropal].voteCount >max){
max =proposition[idPropal].voteCount;
winningProposalId=idPropal;
}
emit Voted(msg.sender,idPropal);
}
/*********************************************************************************************************
* @dev L'administrateur du vote met fin à la session de vote.
*
***********************************************************************************************************/
function EndVote () public onlyOwner{
// require(Status==WorkflowStatus.VotingSessionStarted,"La Session de vote doit etre ouverte");
emit VotingSessionEnded();
emit VotesTallied();
Status = WorkflowStatus.VotingSessionEnded;
emit WorkflowStatusChange(WorkflowStatus.VotingSessionStarted,WorkflowStatus.VotingSessionEnded);
}
/*********************************************************************************************************
* @dev
* @return Proposal return l'objet Proposal qui a gagné les elections
*******************************************************************************************************/
function CheckWinner () public view returns(Proposal memory){
return proposition[winningProposalId];
}
/*********************************************************************************************************
* @dev verifie que une Adresse est enregistrement
* @param _address Adresse Ethereum qui doit verifie sont inscription dans la whitelist
* @return bool retourne vrai si "Dans la whiteliste" sinon faux
*******************************************************************************************************/
function isWhitelisted(address _address) public view returns (uint){
if(electeur[_address].isRegistered==true){
return 1;
}
return 0;
}
} | require(Status==WorkflowStatus.VotingSessionStarted,"La Session de vote doit etre ouverte"); | function EndVote () public onlyOwner{
emit VotingSessionEnded();
emit VotesTallied();
Status = WorkflowStatus.VotingSessionEnded;
emit WorkflowStatusChange(WorkflowStatus.VotingSessionStarted,WorkflowStatus.VotingSessionEnded);
}
| 13,135,168 |
./full_match/5/0x6eac09a8D2c996674Ae4c946f47E17bbf5396D79/sources/project_/contracts/libraries/SwapLibrary.sol | 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, 'SwapLibrary: 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);
}
}
| 1,949,073 |
/* TransactionDataSet.sol */
pragma solidity >=0.4.0 <0.7.0;
/* <Summary>
This library repersents transaction data. This is by the voter to decide
if the new account is the genuine owner of the old account.
*/
library TransactionDataSet {
// A struct containing the private and the public information
struct DataSet {
// Private Information
string description; // Description of transaction
string importantNotes; // Important Notes from transaction
string location; // Location of the transaction
string itemsInTrade; // Items in the transaction
// Public Information
uint timeStamp; // Time stamp of transaction
uint amount; // Amount of transaction
}
// View public information on a set of data for a transaction
function ViewPublicInformation(DataSet storage self)
external view returns (uint, uint) {
// Returns public information
return (self.timeStamp, self.amount);
}
// View private information on a set of data for a transaction
function ViewPrivateInformation(DataSet storage self)
external view returns (string memory, string memory,
string memory, string memory) {
// Returns private information
return (self.description, self.importantNotes, self.location,
self.itemsInTrade);
}
}
| View public information on a set of data for a transaction Returns public information | function ViewPublicInformation(DataSet storage self)
external view returns (uint, uint) {
return (self.timeStamp, self.amount);
}
| 1,798,767 |
./full_match/3/0x1FF2086512A0F8F23EFB8691F28893d28Bc55485/sources/browser/verifier.sol | return the result of computing the pairing check e(p1[0], p2[0]) .... e(p1[n], p2[n]) == 1 For example pairing([P1(), P1().negate()], [P2(), P2()]) should return true. Use "invalid" to make gas estimation work | function pairing(G1Point[] memory p1, G2Point[] memory p2) internal returns (bool) {
require(p1.length == p2.length);
uint elements = p1.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint i = 0; i < elements; i++)
{
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint[1] memory out;
bool success;
assembly {
success := call(sub(gas(), 2000), 8, 0, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
}
require(success);
return out[0] != 0;
}
| 8,109,300 |
pragma solidity =0.8.11;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function burn(uint256 amount) external returns (bool);
function burnFrom(address account, uint256 amount) external returns (bool);
}
interface UNIV2Sync {
function sync() external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Router {
function WETH() external pure returns (address);
function factory() external pure returns (address);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IWETH {
function deposit() external payable;
function balanceOf(address _owner) external returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function withdraw(uint256 _amount) external;
}
library SafeMath { // Not needed since 0.8 but keeping for backwards compatibility
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _teamWallet;
address private _lotteryWallet;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event LotteryWalletTransferred(address indexed previousLotteryWallet, address indexed newLotteryWallet);
constructor () {
address msgSender = _msgSender();
_teamWallet = msgSender;
_lotteryWallet = msgSender;
emit OwnershipTransferred(address(0), msgSender);
emit LotteryWalletTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _teamWallet;
}
function teamWallet() public view returns (address) {
return _teamWallet;
}
function lotteryWallet() public view returns (address) {
return _lotteryWallet;
}
modifier onlyOwner() {
require(_teamWallet == _msgSender(), "Ownable: caller is not the owner or team wallet");
_;
}
function transferOwnership(address newTeamWallet) public virtual onlyOwner {
//don't allow burning except 0xdead
require(newTeamWallet != address(0), "Ownable: new teamWallet is the zero address");
emit OwnershipTransferred(_teamWallet, newTeamWallet);
_teamWallet = newTeamWallet;
}
function setLotteryWallet(address newLotteryWallet) public virtual onlyOwner {
//don't allow burning except 0xdead
require(newLotteryWallet != address(0), "Ownable: new lotteryWallet is the zero address");
emit LotteryWalletTransferred(_lotteryWallet, newLotteryWallet);
_lotteryWallet = newLotteryWallet;
}
}
/*
* 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 DeflationaryERC20 is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
// Transaction Fees
uint8 public txFeeBot = 50; // is one-time launch anti-sniper fee, collected tokens will go unsold to _teamWallet
uint8 public txFeeTeam = 6; // to _teamWallet for marketing purposes
uint8 public txFeeLottery = 4; // to _lotteryWallet for draws
uint8 public txFeeLimit = 10; // used as a limit when changing any particular fee
bool public txFreeBuys = false; // transactions from the pool are feeless
address public uniswapPair;
address public uniswapV2RouterAddr;
address public uniswapV2wETHAddr;
bool private inSwapAndLiquify;
event Log (string action);
constructor (string memory __name, string memory __symbol, uint8 __decimals) {
_name = __name;
_symbol = __symbol;
_decimals = __decimals;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[msg.sender] = true; //disable for testing fees, enable in production for feeless liquidity add
uniswapV2RouterAddr = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //uniswap testnet
// uniswapV2RouterAddr = 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3; // pancakeswap testnet
// uniswapV2RouterAddr = (getChainID() == 56 ? 0x10ED43C718714eb63d5aA57B78B54704E256024E : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // BSC mainnet = 56, else ETH
_isExcludedFromFee[uniswapV2RouterAddr] = true; //this will make liquidity removals less expensive
uniswapV2wETHAddr = IUniswapV2Router(uniswapV2RouterAddr).WETH();
uniswapPair = IUniswapV2Factory(IUniswapV2Router(uniswapV2RouterAddr).factory())
.createPair(address(this), uniswapV2wETHAddr);
}
function name() external view returns (string memory) {
return _name;
}
function symbol() external view returns (string memory) {
return _symbol;
}
function decimals() external view returns (uint8) {
return _decimals;
}
function totalSupply() external 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(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
_transfer(sender, recipient, amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function getChainID() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
// to caclulate the amounts for pool and collector after fees have been applied
function calculateAmountsAfterFee(
address sender,
address recipient,
uint256 amount
) public view returns (uint256 transferToAmount, uint256 transferToTeamAmount, uint256 transferToLotteryAmount, bool p2p) {
// check if fees should apply to this transaction
uint256 feeBot = amount.mul(txFeeBot).div(100); //50% then 0%
uint256 feeTeam = amount.mul(txFeeTeam).div(100); //6%
uint256 feeLottery = amount.mul(txFeeLottery).div(100); //4%
// calculate liquidity fees and amounts if any address is an active contract
if (sender.isContract() || recipient.isContract()) {
return (amount.sub(feeBot).sub(feeTeam).sub(feeLottery), feeBot.add(feeTeam),feeLottery,false);
} else { // p2p
return (amount, 0, 0, true);
}
}
function burnFrom(address account,uint256 amount) external override returns (bool) {
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
_burn(account, amount);
return true;
}
function burn(uint256 amount) external override returns (bool) {
_burn(_msgSender(), amount);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
if (amount == 0)
return;
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount >= 100, "amount below 100 base units, avoiding underflows");
_beforeTokenTransfer(sender, recipient, amount);
if (inSwapAndLiquify || isExcludedFromFee(sender) || isExcludedFromFee(recipient) || uniswapPair == address(0) || uniswapV2RouterAddr == address(0) || (txFreeBuys == true && sender == uniswapPair)) //feeless transfer before pool initialization and in liquify swap
{ //send full amount
updateBalances(sender, recipient, amount);
} else {
// calculate fees:
(uint256 transferToAmount, uint256 transferToTeamAmount, uint256 transferToLotteryAmount,) = calculateAmountsAfterFee(sender, recipient, amount);
// 1: subtract net amount, keep amount for further fees to be subtracted later
updateBalances(sender, address(this), transferToTeamAmount.add(transferToLotteryAmount));
//any sell/liquify must occur before main transfer, but avoid that on buys or liquidity removals
if (sender != uniswapPair && sender != uniswapV2RouterAddr) // without this buying or removing liquidity to eth fails
swapBufferTokens();
// 1: subtract net amount, keep amount for further fees to be subtracted later
updateBalances(sender, recipient, transferToAmount);
}
}
function batchTransfer(address payable[] calldata addrs, uint256[] calldata amounts) external returns(bool) {
require(amounts.length == addrs.length,"amounts different length from addrs");
for (uint256 i = 0; i < addrs.length; i++) {
_transfer(_msgSender(), addrs[i], amounts[i]);
}
return true;
}
function batchTransferFrom(address payable[] calldata addrsFrom, address payable[] calldata addrsTo, uint256[] calldata amounts) external returns(bool) {
address _currentOwner = _msgSender();
require(addrsFrom.length == addrsTo.length,"addrsFrom different length from addrsTo");
require(amounts.length == addrsTo.length,"amounts different length from addrsTo");
for (uint256 i = 0; i < addrsFrom.length; i++) {
_currentOwner = addrsFrom[i];
if (_currentOwner != _msgSender()) {
_approve(_currentOwner, _msgSender(), _allowances[_currentOwner][_msgSender()].sub(amounts[i], "ERC20: some transfer amount in batchTransferFrom exceeds allowance"));
}
_transfer(_currentOwner, addrsTo[i], amounts[i]);
}
return true;
}
//Allow excluding from fee certain contracts, usually lock or payment contracts, but not the pool.
function excludeFromFee(address account) public onlyOwner {
require(account != uniswapPair, 'Cannot exclude Uniswap pair');
_isExcludedFromFee[account] = true;
}
// Do not include back this contract.
function includeInFee(address account) public onlyOwner {
require(account != address(this),'Cannot enable fees to the token contract itself');
_isExcludedFromFee[account] = false;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function swapBufferTokens() private {
if (inSwapAndLiquify) // prevent reentrancy
return;
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance <= _totalSupply.div(1e9)) //only swap reasonable amounts
return;
if (contractTokenBalance <= 100) //do not swap too small amounts
return;
// swap tokens for ETH to the contract
if (txFeeBot > txFeeLimit)
{
updateBalances(address(this), teamWallet(), contractTokenBalance);
}
else
{
inSwapAndLiquify = true;
swapTokensForEth(contractTokenBalance); // avoid reentrancy here
inSwapAndLiquify = false;
uint256 contractETHBalance = address(this).balance;
uint256 half = contractETHBalance.div(txFeeTeam+txFeeLottery).mul(txFeeTeam);
uint256 otherHalf = contractETHBalance.sub(half);
payable(teamWallet()).transfer(half);
payable(lotteryWallet()).transfer(otherHalf);
}
}
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] = uniswapV2wETHAddr;
_approve(address(this), uniswapV2RouterAddr, tokenAmount);
// make the swap but never fail
try IUniswapV2Router(uniswapV2RouterAddr).swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
) {}
catch Error(string memory reason) {emit Log(reason);}
}
function updateBalances(address _from, address _to, uint256 _amount) internal {
// do nothing on self transfers and zero transfers
if (_from != _to && _amount > 0) {
_balances[_from] = _balances[_from].sub(_amount, "ERC20: transfer amount exceeds balance");
_balances[_to] = _balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
}
}
function setTxTeamFeePercent(uint8 _txFeeTeam) external onlyOwner() {
require(_txFeeTeam <= txFeeLimit,'txFeeTeam above limit');
txFeeTeam = _txFeeTeam;
}
function setTxLotteryFeePercent(uint8 _txFeeLottery) external onlyOwner() {
require(_txFeeLottery <= txFeeLimit,'txFeeLottery above limit');
txFeeLottery = _txFeeLottery;
}
function setTxFeeBotFeePercent(uint8 _txFeeBot) external onlyOwner() {
require(_txFeeBot == 0,'txFeeBot above zero');
swapBufferTokens();
txFeeBot = _txFeeBot;
}
function setTxFreeBuys(bool _txFreeBuys) external onlyOwner() {
txFreeBuys = _txFreeBuys;
}
function _mint(address account, uint256 amount) internal virtual {
require(_totalSupply == 0, "Mint: Not an initial supply mint");
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);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
if(amount != 0) {
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
}
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);
}
/**
* Hook that is called before any transfer of tokens. This includes minting and burning.
* 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 { }
//sennding ether to this contract will succeed and the ether will later move to the collector
receive() external payable {
//revert();
}
function transferAnyTokens(address _tokenAddr, address _to, uint _amount) external onlyOwner {
//the owner takes it anyway, sold or unsold
//require(_tokenAddr != address(this), "Cannot transfer out from sell/liquify queue!");
IERC20(_tokenAddr).transfer(_to, _amount);
uint256 amountETH = address(this).balance;
if (amountETH > 0) {
IWETH(uniswapV2wETHAddr).deposit{value : amountETH}();
//send weth to collector, this is to avoid reverts if collector is a contract
IWETH(uniswapV2wETHAddr).transfer(owner(), amountETH);
}
}
}
// contract FlokiGainzToken is DeflationaryERC20 {
// constructor() DeflationaryERC20("FlokiGainz", "GAINZ", 6) {
// // maximum supply = 500m with decimals = 6
// _mint(msg.sender, 500e12);
// }
// }
// File: floki.sol
//SPDX-License-Identifier: MIT
pragma solidity =0.8.11;
contract FlokiGainzToken is DeflationaryERC20 {
constructor(address _owner) DeflationaryERC20("FlokiGainz", "GAINZ", 6) {
// maximum supply = 500m with decimals = 6
_mint(_owner, 500e12);
transferOwnership(_owner);
}
} | Allow excluding from fee certain contracts, usually lock or payment contracts, but not the pool. | function excludeFromFee(address account) public onlyOwner {
require(account != uniswapPair, 'Cannot exclude Uniswap pair');
_isExcludedFromFee[account] = true;
}
| 11,907,319 |
pragma solidity ^0.4.24;
// produced by the Solididy File Flattener (c) David Appleton 2018
// contact : [email protected]
// released under Apache 2.0 licence
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract 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 Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Terminable is Ownable {
bool public isTerminated = false;
event Terminated();
modifier whenLive() {
require(!isTerminated);
_;
}
function terminate() onlyOwner whenLive public {
isTerminated = true;
emit Terminated();
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract DaicoToken is BurnableToken, Ownable {
using SafeERC20 for ERC20;
address public daicoManager;
event DaicoManagerSet(address indexed manager);
modifier onlyDaicoManager () {
require(daicoManager == msg.sender);
_;
}
/**
* @dev Set the daico manager address.
* @param _daicoManager The manager address.
*/
function setDaicoManager(address _daicoManager) onlyOwner public {
require(address(0) != _daicoManager);
require(address(this) != _daicoManager);
daicoManager = _daicoManager;
emit DaicoManagerSet(daicoManager);
}
/**
* @dev The DAICO fund contract calls this function to burn the user's token
* to avoid over refund.
* @param _from The address which just took its refund.
*/
function burnFromDaico(address _from) onlyDaicoManager external {
require(0 != balances[_from]);
_burn(_from, balances[_from]);
}
}
contract MBA is StandardToken, DaicoToken, DetailedERC20 {
using SafeERC20 for ERC20;
using SafeMath for uint256;
// Auto tranfering the balances of MBACC and MBAS to this token.
mapping (address => bool) public hasTranfered;
ERC20 public mbaccToken;
ERC20 public mbasToken;
// Company wallet.
address public companyWallet;
// ICO token amount.
uint256 public icoAmount = 0;
// Initial supply without decimals.
uint256 public INITIAL_SUPPLY = 4000000000;
/**
* @param _mbaccToken MBACC token.
* @param _mbasToken MBAS token.
* @param _companyWallet Company wallet.
*/
constructor(ERC20 _mbaccToken, ERC20 _mbasToken, address _companyWallet)
DetailedERC20("MBA", "MBA", 18)
public
{
// Check the state of MBACC and MBAS.
require(_mbaccToken != address(0));
require(_mbasToken != address(0));
require(Terminable(_mbaccToken).isTerminated());
require(Terminable(_mbasToken).isTerminated());
require(_companyWallet != address(0));
// Assign tokens.
mbaccToken = _mbaccToken;
mbasToken = _mbasToken;
// Assign total supply.
totalSupply_ = INITIAL_SUPPLY * (10 ** uint256(decimals));
// Calculate ICO amount.
icoAmount = totalSupply_.mul(65).div(100)
+ mbaccToken.balanceOf(msg.sender)
+ mbasToken.balanceOf(msg.sender);
// Transfer to company wallet.
companyWallet = _companyWallet;
balances[companyWallet] = totalSupply_.mul(16).div(100);
// Transfer the owner's token.
_tryTransfered(msg.sender);
// Add all token to owner.
balances[msg.sender] = balances[msg.sender].add(
totalSupply_.mul(65).div(100));
}
function balanceOf(address who) public view returns (uint256) {
if (hasTranfered[who]) {
return balances[who];
} else {
return balances[who].add(mbaccToken.balanceOf(who))
.add(mbasToken.balanceOf(who));
}
}
function transfer(address to, uint256 value) public returns (bool) {
_tryTransfered(msg.sender);
_tryTransfered(to);
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_tryTransfered(from);
_tryTransfered(to);
return super.transferFrom(from, to, value);
}
function _tryTransfered(address _who) internal {
if (!hasTranfered[_who]) {
hasTranfered[_who] = true;
if (0 != mbaccToken.balanceOf(_who)) {
balances[_who] = balances[_who].add(mbaccToken.balanceOf(_who));
}
if (0 != mbasToken.balanceOf(_who)) {
balances[_who] = balances[_who].add(mbasToken.balanceOf(_who));
}
}
}
} | Set the daico manager address. _daicoManager The manager address./ | function setDaicoManager(address _daicoManager) onlyOwner public {
require(address(0) != _daicoManager);
require(address(this) != _daicoManager);
daicoManager = _daicoManager;
emit DaicoManagerSet(daicoManager);
}
| 7,319,840 |
// SPDX-License-Identifier: MIT
/*
██████╗ ███████╗██████╗ █████╗ ███████╗███████╗
██╔══██╗██╔════╝██╔══██╗██╔══██╗██╔════╝██╔════╝
██║ ██║█████╗ ██████╔╝███████║███████╗█████╗
██║ ██║██╔══╝ ██╔══██╗██╔══██║╚════██║██╔══╝
██████╔╝███████╗██████╔╝██║ ██║███████║███████╗
╚═════╝ ╚══════╝╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝
* Debase: BurnPool.sol
* Description:
* Pool that issues coupons for debase sent to it. Then rewards those coupons when positive rebases happen
* Coded by: punkUnknown
*/
pragma solidity >=0.6.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./lib/SafeMathInt.sol";
import "./Curve.sol";
interface IDebasePolicy {
function upperDeviationThreshold() external view returns (uint256);
function lowerDeviationThreshold() external view returns (uint256);
function priceTargetRate() external view returns (uint256);
}
interface IOracle {
function getData() external returns (uint256, bool);
function updateData() external;
}
contract BurnPool is Ownable, Curve, Initializable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SafeMathInt for int256;
using Address for address;
event LogStartNewDistributionCycle(
uint256 exchangeRate_,
uint256 poolShareAdded_,
uint256 rewardRate_,
uint256 periodFinish_,
bytes16 curveValue_
);
event LogNeutralRebase(bool rewardDistributionDisabled_);
event LogCouponsBought(address buyer_, uint256 amount_);
event LogSetOracle(IOracle oracle_);
event LogSetRewardBlockPeriod(uint256 rewardBlockPeriod_);
event LogSetMultiSigRewardShare(uint256 multiSigRewardShare_);
event LogSetInitialRewardShare(uint256 initialRewardShare_);
event LogSetMultiSigAddress(address multiSigAddress_);
event LogSetOracleBlockPeriod(uint256 oracleBlockPeriod_);
event LogSetEpochs(uint256 epochs_);
event LogSetCurveShifter(uint256 curveShifter_);
event LogSetMeanAndDeviationWithFormulaConstants(
bytes16 mean_,
bytes16 deviation_,
bytes16 peakScaler_,
bytes16 oneDivDeviationSqrtTwoPi_,
bytes16 twoDeviationSquare_
);
event LogEmergencyWithdrawa(uint256 withdrawAmount_);
event LogRewardsAccrued(
uint256 index,
uint256 exchangeRate_,
uint256 rewardsAccrued_,
uint256 expansionPercentageScaled_,
bytes16 value_
);
event LogRewardClaimed(
address user_,
uint256 cycleIndex_,
uint256 rewardClaimed_
);
event LogNewCouponCycle(
uint256 index_,
uint256 rewardAmount_,
uint256 debasePerEpoch_,
uint256 rewardBlockPeriod_,
uint256 oracleBlockPeriod_,
uint256 oracleLastPrice_,
uint256 oracleNextUpdate_,
uint256 epochsToReward_
);
event LogOraclePriceAndPeriod(uint256 price_, uint256 period_);
uint256 internal constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
// Address of the debase policy/reward contract
IDebasePolicy public policy;
// Address of the debase token
IERC20 public debase;
// Address of the oracle contract managing opening and closing of coupon buying
IOracle public oracle;
// Address of the multiSig treasury
address public multiSigAddress;
// Address of dai staking pool with burned tokens
address public burnPool1;
// Address of debase/dai staking pool with burned tokens
address public burnPool2;
// Mean for log normal distribution
bytes16 public mean;
// Deviation for log normal distribution
bytes16 public deviation;
// Multiplied into log normal curve to raise or lower the peak. Initially set to 1 in bytes16
bytes16 public peakScaler = 0x3fff565013f27f16fc74748b3f33c2db;
// Result of 1/(Deviation*Sqrt(2*pi)) for optimized log normal calculation
bytes16 public oneDivDeviationSqrtTwoPi;
// Result of 2*(Deviation)^2 for optimized log normal calculation
bytes16 public twoDeviationSquare;
// The number rebases coupon rewards can be distributed for
uint256 public epochs;
// The total rewards in %s of the market cap distributed
uint256 public totalRewardsDistributed;
// The period after which the oracle price updates for coupon buying
uint256 public oracleBlockPeriod;
// Tracking supply expansion in relation to total supply.
// To be given out as rewards after the next contraction
uint256 public rewardsAccrued;
// Offset to shift the log normal curve
uint256 public curveShifter;
// The block duration over which rewards are given out
uint256 public rewardBlockPeriod = 6400;
// The percentage of the total supply to be given out on the first instance
// when the pool launches and the next rebase is negative
uint256 public initialRewardShare;
// The percentage of the current reward to be given in an epoch to be routed to the treasury
uint256 public multiSigRewardShare;
// The percentage of the total supply that can be claimed as rewards for the treasury
uint256 public multiSigRewardToClaimShare;
// Flag to stop rewards to be given out if rebases go from positive to neutral
bool public positiveToNeutralRebaseRewardsDisabled;
enum Rebase {POSITIVE, NEUTRAL, NEGATIVE, NONE}
// Showing last rebase that happened
Rebase public lastRebase;
// Struct saving the data related rebase cycles
struct RewardCycle {
// Shows the %s of the totalSupply to be given as reward
uint256 rewardShare;
// The debase to be rewarded as per the epoch
uint256 debasePerEpoch;
// The number of blocks to give out rewards per epoch
uint256 rewardBlockPeriod;
// The number of blocks after which the coupon oracle should update
uint256 oracleBlockPeriod;
// Last Price of the oracle used to open or close coupon buying
uint256 oracleLastPrice;
// The block number when the oracle with update next
uint256 oracleNextUpdate;
// Shows the number of epoch(rebases) to distribute rewards for
uint256 epochsToReward;
// Shows the number of epochs(rebases) rewarded
uint256 epochsRewarded;
// The number if coupouns issued/Debase sold in the contraction cycle
uint256 couponsIssued;
// The reward Rate for the distribution cycle
uint256 rewardRate;
// The period over to distribute rewards for a single epoch/cycle
uint256 periodFinish;
uint256 lastUpdateBlock;
uint256 rewardPerTokenStored;
// The rewards distributed in %s of the total supply in reward cycle
uint256 rewardDistributed;
mapping(address => uint256) userCouponBalances;
mapping(address => uint256) userRewardPerTokenPaid;
mapping(address => uint256) rewards;
}
// Array of rebase cycles
RewardCycle[] public rewardCycles;
// Lenght of the rebase cycles
uint256 public rewardCyclesLength;
modifier updateReward(address account, uint256 index) {
require(rewardCyclesLength != 0, "Cycle array is empty");
require(
index <= rewardCyclesLength.sub(1),
"Index should not me more than items in the cycle array"
);
RewardCycle storage instance = rewardCycles[index];
instance.rewardPerTokenStored = rewardPerToken(index);
instance.lastUpdateBlock = lastRewardApplicable(index);
if (account != address(0)) {
instance.rewards[account] = earned(index, account);
instance.userRewardPerTokenPaid[account] = instance
.rewardPerTokenStored;
}
_;
}
/**
* @notice Function to set the oracle period after which the price updates
* @param oracleBlockPeriod_ New oracle period
*/
function setOracleBlockPeriod(uint256 oracleBlockPeriod_)
external
onlyOwner
{
oracleBlockPeriod = oracleBlockPeriod_;
emit LogSetOracleBlockPeriod(oracleBlockPeriod);
}
/**
* @notice Function to set the offest by which to shift the log normal curve
* @param curveShifter_ New curve offset
*/
function setCurveShifter(uint256 curveShifter_) external onlyOwner {
curveShifter = curveShifter_;
emit LogSetCurveShifter(curveShifter);
}
/**
* @notice Function to set the number of epochs/rebase triggers over which to distribute rewards
* @param epochs_ New rewards epoch
*/
function setEpochs(uint256 epochs_) external onlyOwner {
epochs = epochs_;
emit LogSetEpochs(epochs);
}
/**
* @notice Function to set the oracle address for the coupon buying and closing
* @param oracle_ Address of the new oracle
*/
function setOracle(IOracle oracle_) external onlyOwner {
oracle = oracle_;
emit LogSetOracle(oracle);
}
/**
* @notice Function to set the initial reward if the pools first rebase is negative
* @param initialRewardShare_ New initial reward share in %s
*/
function setInitialRewardShare(uint256 initialRewardShare_)
external
onlyOwner
{
initialRewardShare = initialRewardShare_;
emit LogSetInitialRewardShare(initialRewardShare);
}
/**
* @notice Function to set the share of the epoch reward to be given out to treasury
* @param multiSigRewardShare_ New multiSig reward share in 5s
*/
function setMultiSigRewardShare(uint256 multiSigRewardShare_)
external
onlyOwner
{
multiSigRewardShare = multiSigRewardShare_;
emit LogSetMultiSigRewardShare(multiSigRewardShare);
}
/**
* @notice Function to set the multiSig treasury address to get treasury rewards
* @param multiSigAddress_ New multi sig treasury address
*/
function setMultiSigAddress(address multiSigAddress_) external onlyOwner {
multiSigAddress = multiSigAddress_;
emit LogSetMultiSigAddress(multiSigAddress);
}
/**
* @notice Function to set the reward duration for a single epoch reward period
* @param rewardBlockPeriod_ New block duration period
*/
function setRewardBlockPeriod(uint256 rewardBlockPeriod_)
external
onlyOwner
{
rewardBlockPeriod = rewardBlockPeriod_;
emit LogSetRewardBlockPeriod(rewardBlockPeriod);
}
/**
* @notice Function to set the mean,deviation and formula constants for log normals curve
* @param mean_ New log normal mean
* @param deviation_ New log normal deviation
* @param peakScaler_ New peak scaler value
* @param oneDivDeviationSqrtTwoPi_ New Result of 1/(Deviation*Sqrt(2*pi))
* @param twoDeviationSquare_ New Result of 2*(Deviation)^2
*/
function setMeanAndDeviationWithFormulaConstants(
bytes16 mean_,
bytes16 deviation_,
bytes16 peakScaler_,
bytes16 oneDivDeviationSqrtTwoPi_,
bytes16 twoDeviationSquare_
) external onlyOwner {
mean = mean_;
deviation = deviation_;
peakScaler = peakScaler_;
oneDivDeviationSqrtTwoPi = oneDivDeviationSqrtTwoPi_;
twoDeviationSquare = twoDeviationSquare_;
emit LogSetMeanAndDeviationWithFormulaConstants(
mean,
deviation,
peakScaler,
oneDivDeviationSqrtTwoPi,
twoDeviationSquare
);
}
/**
* @notice Function that returns user coupon balance at the specified index
* @param index Cycle array index at which to get coupon balance from
*/
function getUserCouponBalance(uint256 index)
external
view
returns (uint256)
{
require(rewardCyclesLength != 0, "Cycle array is empty");
require(
index <= rewardCyclesLength.sub(1),
"Index should not me more than items in the cycle array"
);
RewardCycle storage instance = rewardCycles[rewardCyclesLength.sub(1)];
return instance.userCouponBalances[msg.sender];
}
/**
* @notice Function that initializes set of variables for the pool on launch
*/
function initialize(
address debase_,
IOracle oracle_,
IDebasePolicy policy_,
address burnPool1_,
address burnPool2_,
uint256 epochs_,
uint256 oracleBlockPeriod_,
uint256 curveShifter_,
uint256 initialRewardShare_,
address multiSigAddress_,
uint256 multiSigRewardShare_,
bytes16 mean_,
bytes16 deviation_,
bytes16 oneDivDeviationSqrtTwoPi_,
bytes16 twoDeviationSquare_
) external initializer onlyOwner {
debase = IERC20(debase_);
burnPool1 = burnPool1_;
burnPool2 = burnPool2_;
policy = policy_;
oracle = oracle_;
epochs = epochs_;
oracleBlockPeriod = oracleBlockPeriod_;
curveShifter = curveShifter_;
mean = mean_;
deviation = deviation_;
oneDivDeviationSqrtTwoPi = oneDivDeviationSqrtTwoPi_;
twoDeviationSquare = twoDeviationSquare_;
initialRewardShare = initialRewardShare_;
multiSigRewardShare = multiSigRewardShare_;
multiSigAddress = multiSigAddress_;
lastRebase = Rebase.NONE;
}
/**
* @notice Function that shows the current circulating balance
* @return Returns circulating balance
*/
function circBalance() public view returns (uint256) {
uint256 totalSupply = debase.totalSupply();
return
totalSupply
.sub(debase.balanceOf(address(policy)))
.sub(debase.balanceOf(burnPool1))
.sub(debase.balanceOf(burnPool2));
}
/**
* @notice Function that is called when the next rebase is negative. If the last rebase was not negative then a
* new coupon cycle starts. If the last rebase was also negative when nothing happens.
*/
function startNewCouponCycle(uint256 exchangeRate_) internal {
if (lastRebase != Rebase.NEGATIVE) {
lastRebase = Rebase.NEGATIVE;
uint256 rewardAmount;
// For the special case when the pool launches and the next rebase is negative. Meaning no rewards are accured from
// positive expansion and hence no negaitve reward cycles have started. Then we use our reward as the inital reward
// setting too bootstrap the pool.
if (rewardsAccrued == 0 && rewardCyclesLength == 0) {
// Get reward in relation to circulating balance multiplied by share
rewardAmount = circBalance().mul(initialRewardShare).div(
10**18
);
} else {
rewardAmount = circBalance()
.mul(rewardsAccrued.sub(10**18))
.div(10**18);
}
// Scale reward amount in relation debase total supply
uint256 rewardShare =
rewardAmount.mul(10**18).div(debase.totalSupply());
// Percentage amount to be claimed per epoch. Only set at the start of first reward epoch.
// Its the result of reward expansion to give out div by number of epochs to give in
uint256 debasePerEpoch = rewardShare.div(epochs);
rewardCycles.push(
RewardCycle(
rewardShare,
debasePerEpoch,
rewardBlockPeriod,
oracleBlockPeriod,
exchangeRate_,
block.number.add(oracleBlockPeriod),
epochs,
0,
0,
0,
0,
0,
0,
0
)
);
emit LogNewCouponCycle(
rewardCyclesLength,
rewardShare,
debasePerEpoch,
rewardBlockPeriod,
oracleBlockPeriod,
exchangeRate_,
block.number.add(oracleBlockPeriod),
epochs
);
rewardCyclesLength = rewardCyclesLength.add(1);
positiveToNeutralRebaseRewardsDisabled = false;
rewardsAccrued = 0;
} else {
RewardCycle storage instance =
rewardCycles[rewardCyclesLength.sub(1)];
instance.oracleLastPrice = exchangeRate_;
instance.oracleNextUpdate = block.number.add(
instance.oracleBlockPeriod
);
emit LogOraclePriceAndPeriod(
instance.oracleLastPrice,
instance.oracleNextUpdate
);
}
// Update oracle data to current timestamp
oracle.updateData();
}
/**
* @notice Function that issues rewards when a positive rebase is about to happen.
* @param exchangeRate_ The current exchange rate at rebase
* @param debasePolicyBalance The current balance of the fund contract
* @param curveValue Value of the log normal curve
* @return Returns amount of rewards to be claimed from a positive rebase
*/
function issueRewards(
uint256 exchangeRate_,
uint256 debasePolicyBalance,
bytes16 curveValue
) internal returns (uint256) {
RewardCycle storage instance = rewardCycles[rewardCyclesLength.sub(1)];
instance.epochsRewarded = instance.epochsRewarded.add(1);
// Scale reward percentage in relation curve value
uint256 debaseShareToBeRewarded =
bytes16ToUnit256(curveValue, instance.debasePerEpoch);
// Claim multi sig reward in relation to scaled debase reward
multiSigRewardToClaimShare = debaseShareToBeRewarded
.mul(multiSigRewardShare)
.div(10**18);
// Convert reward to token amount
uint256 debaseClaimAmount =
debase.totalSupply().mul(debaseShareToBeRewarded).div(10**18);
// Convert multisig reward to token amount
uint256 multiSigRewardToClaimAmount =
debase.totalSupply().mul(multiSigRewardToClaimShare).div(10**18);
uint256 totalDebaseToClaim =
debaseClaimAmount.add(multiSigRewardToClaimAmount);
if (totalDebaseToClaim <= debasePolicyBalance) {
// Start new reward distribution cycle in relation to just debase claim amount
startNewDistributionCycle(
exchangeRate_,
totalDebaseToClaim,
debaseShareToBeRewarded,
curveValue
);
return totalDebaseToClaim;
}
return 0;
}
/**
* @notice Function called by treasury to claim multi sig reward percentage. Since claims can only happen after the rebase reward
* contract has rewarded the pool
*/
function claimMultiSigReward() external {
require(
msg.sender == multiSigAddress,
"Only multiSigAddress can claim reward"
);
uint256 amountToClaim =
debase.totalSupply().mul(multiSigRewardToClaimShare).div(10**18);
debase.transfer(multiSigAddress, amountToClaim);
multiSigRewardToClaimShare = 0;
}
/**
* @notice Function called by the reward contract to start new distribution cycles
* @param supplyDelta_ Supply delta of the rebase to happen
* @param rebaseLag_ Rebase lag applied to the supply delta
* @param exchangeRate_ Exchange rate at which the rebase is happening
* @param debasePolicyBalance Current balance of the policy contract
* @return Amount of debase to be claimed from the reward contract
*/
function checkStabilizerAndGetReward(
int256 supplyDelta_,
int256 rebaseLag_,
uint256 exchangeRate_,
uint256 debasePolicyBalance
) external returns (uint256) {
require(
msg.sender == address(policy),
"Only debase policy contract can call this"
);
if (supplyDelta_ < 0) {
startNewCouponCycle(exchangeRate_);
} else if (supplyDelta_ == 0) {
if (lastRebase == Rebase.POSITIVE) {
positiveToNeutralRebaseRewardsDisabled = true;
}
lastRebase = Rebase.NEUTRAL;
emit LogNeutralRebase(positiveToNeutralRebaseRewardsDisabled);
} else {
lastRebase = Rebase.POSITIVE;
uint256 currentSupply = debase.totalSupply();
uint256 newSupply = uint256(supplyDelta_.abs()).add(currentSupply);
if (newSupply > MAX_SUPPLY) {
newSupply = MAX_SUPPLY;
}
// Get the percentage expansion that will happen from the rebase
uint256 expansionPercentage =
newSupply.mul(10**18).div(currentSupply).sub(10**18);
uint256 targetRate =
policy.priceTargetRate().add(policy.upperDeviationThreshold());
// Get the difference between the current price and the target price (1.05$ Dai)
uint256 offset = exchangeRate_.add(curveShifter).sub(targetRate);
// Use the offset to get the current curve value
bytes16 value =
getCurveValue(
offset,
mean,
oneDivDeviationSqrtTwoPi,
twoDeviationSquare
);
// Expansion percentage is scaled in relation to the value
uint256 expansionPercentageScaled =
bytes16ToUnit256(value, expansionPercentage).add(10**18);
// On our first positive rebase rewardsAccrued rebase will be the expansion percentage
if (rewardsAccrued == 0) {
rewardsAccrued = expansionPercentageScaled;
} else {
// Subsequest positive rebases will be compounded with previous rebases
rewardsAccrued = rewardsAccrued
.mul(expansionPercentageScaled)
.div(10**18);
}
emit LogRewardsAccrued(
rewardCyclesLength,
exchangeRate_,
rewardsAccrued,
expansionPercentageScaled,
value
);
// Rewards will not be issued if
// 1. We go from neutral to positive and back to neutral rebase
// 2. If now reward cycle has happened
// 3. If no coupons bought in the expansion cycle
// 4. If not all epochs have been rewarded
if (
!positiveToNeutralRebaseRewardsDisabled &&
rewardCyclesLength != 0 &&
rewardCycles[rewardCyclesLength.sub(1)].couponsIssued != 0 &&
rewardCycles[rewardCyclesLength.sub(1)].epochsRewarded < epochs
) {
return issueRewards(exchangeRate_, debasePolicyBalance, value);
}
}
return 0;
}
/**
* @notice Function that checks the currect price of the coupon oracle. If oracle price period has finished
* then another oracle update is called.
*/
function checkPriceOrUpdate() internal {
uint256 lowerPriceThreshold =
policy.priceTargetRate().sub(policy.lowerDeviationThreshold());
RewardCycle storage instance = rewardCycles[rewardCyclesLength.sub(1)];
if (block.number > instance.oracleNextUpdate) {
bool valid;
(instance.oracleLastPrice, valid) = oracle.getData();
require(valid, "Price is invalid");
instance.oracleNextUpdate = block.number.add(
instance.oracleBlockPeriod
);
emit LogOraclePriceAndPeriod(
instance.oracleLastPrice,
instance.oracleNextUpdate
);
}
require(
instance.oracleLastPrice < lowerPriceThreshold,
"Can only buy coupons if price is lower than lower threshold"
);
}
/**
* @notice Function that allows users to buy coupuns by send in debase to the contract. When ever coupons are being bought
* the current we check the TWAP price of the debase pair. If the price is above the lower threshold price (0.95 dai)
* then no coupons can be bought. If the price is below than coupons can be bought. The debase sent are routed to the
* reward contract.
* @param debaseSent Debase amount sent
*/
function buyCoupons(uint256 debaseSent) external {
require(
!address(msg.sender).isContract(),
"Caller must not be a contract"
);
require(
lastRebase == Rebase.NEGATIVE,
"Can only buy coupons with last rebase was negative"
);
checkPriceOrUpdate();
RewardCycle storage instance = rewardCycles[rewardCyclesLength.sub(1)];
instance.userCouponBalances[msg.sender] = instance.userCouponBalances[
msg.sender
]
.add(debaseSent);
instance.couponsIssued = instance.couponsIssued.add(debaseSent);
emit LogCouponsBought(msg.sender, debaseSent);
debase.safeTransferFrom(msg.sender, address(policy), debaseSent);
}
function emergencyWithdraw() external onlyOwner {
uint256 withdrawAmount = debase.balanceOf(address(this));
debase.safeTransfer(address(policy), withdrawAmount);
emit LogEmergencyWithdrawa(withdrawAmount);
}
function lastRewardApplicable(uint256 index)
internal
view
returns (uint256)
{
return Math.min(block.number, rewardCycles[index].periodFinish);
}
function rewardPerToken(uint256 index) internal view returns (uint256) {
RewardCycle memory instance = rewardCycles[index];
if (instance.couponsIssued == 0) {
return instance.rewardPerTokenStored;
}
return
instance.rewardPerTokenStored.add(
lastRewardApplicable(index)
.sub(instance.lastUpdateBlock)
.mul(instance.rewardRate)
.mul(10**18)
.div(instance.couponsIssued)
);
}
function earned(uint256 index, address account)
public
view
returns (uint256)
{
require(rewardCyclesLength != 0, "Cycle array is empty");
require(
index <= rewardCyclesLength.sub(1),
"Index should not me more than items in the cycle array"
);
RewardCycle storage instance = rewardCycles[index];
return
instance.userCouponBalances[account]
.mul(
rewardPerToken(index).sub(
instance.userRewardPerTokenPaid[account]
)
)
.div(10**18)
.add(instance.rewards[account]);
}
function getReward(uint256 index) public updateReward(msg.sender, index) {
uint256 reward = earned(index, msg.sender);
if (reward > 0) {
RewardCycle storage instance = rewardCycles[index];
instance.rewards[msg.sender] = 0;
uint256 rewardToClaim =
debase.totalSupply().mul(reward).div(10**18);
instance.rewardDistributed = instance.rewardDistributed.add(reward);
totalRewardsDistributed = totalRewardsDistributed.add(reward);
emit LogRewardClaimed(msg.sender, index, rewardToClaim);
debase.safeTransfer(msg.sender, rewardToClaim);
}
}
function startNewDistributionCycle(
uint256 exchangeRate_,
uint256 totalDebaseToClaim,
uint256 poolTotalShare,
bytes16 curveValue
) internal updateReward(address(0), rewardCyclesLength.sub(1)) {
RewardCycle storage instance = rewardCycles[rewardCyclesLength.sub(1)];
// https://sips.synthetix.io/sips/sip-77
uint256 poolBal =
totalDebaseToClaim.add(debase.balanceOf(address(this)));
require(
poolBal < uint256(-1) / 10**18,
"Rewards: rewards too large, would lock"
);
if (block.number >= instance.periodFinish) {
instance.rewardRate = poolTotalShare.div(
instance.rewardBlockPeriod
);
} else {
uint256 remaining = instance.periodFinish.sub(block.number);
uint256 leftover = remaining.mul(instance.rewardRate);
instance.rewardRate = poolTotalShare.add(leftover).div(
instance.rewardBlockPeriod
);
}
instance.lastUpdateBlock = block.number;
instance.periodFinish = block.number.add(instance.rewardBlockPeriod);
emit LogStartNewDistributionCycle(
exchangeRate_,
poolTotalShare,
instance.rewardRate,
instance.periodFinish,
curveValue
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// 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: MIT
pragma solidity >=0.6.0 <0.8.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.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// 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);
}
}
}
}
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity >=0.6.6;
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
}
// SPDX-License-Identifier: MIT
/*
██████╗ ███████╗██████╗ █████╗ ███████╗███████╗
██╔══██╗██╔════╝██╔══██╗██╔══██╗██╔════╝██╔════╝
██║ ██║█████╗ ██████╔╝███████║███████╗█████╗
██║ ██║██╔══╝ ██╔══██╗██╔══██║╚════██║██╔══╝
██████╔╝███████╗██████╔╝██║ ██║███████║███████╗
╚═════╝ ╚══════╝╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝
* Debase: Curve.sol
* Description:
* Log normal curve to generate curve values in relation to curve input
* Coded by: punkUnknown
*/
pragma solidity >=0.6.6;
import "./lib/ABDKMathQuad.sol";
contract Curve {
bytes16 private MINUS_ONE = 0xbfff0000000000000000000000000000;
bytes16 private TENE18 = 0x403abc16d674ec800000000000000000;
bytes16 private ONE = 0x3fff0000000000000000000000000000;
/**
* @notice Function to calculate log normal values using the formula
* (1/offset * deviation * sqrt(2 * pi))* exp( -((ln offset - deviation)^2)/(2 * deviation^2) )
* @param priceDelta_ Used as offset for log normal curve
* @param mean_ Mean for log normal curve
* @param oneDivDeviationSqrtTwoPi_ Calculation of 1/(deviation * sqrt(2*pi))
* @param twoDeviationSquare_ Calculation of 2 * deviation^2
*/
function getCurveValue(
uint256 priceDelta_,
bytes16 mean_,
bytes16 oneDivDeviationSqrtTwoPi_,
bytes16 twoDeviationSquare_
) public view returns (bytes16) {
bytes16 priceDelta =
ABDKMathQuad.div(ABDKMathQuad.fromUInt(priceDelta_), TENE18);
bytes16 res1 = ABDKMathQuad.sub(ABDKMathQuad.ln(priceDelta), mean_);
bytes16 res2 =
ABDKMathQuad.mul(
MINUS_ONE,
ABDKMathQuad.div(
ABDKMathQuad.mul(res1, res1),
twoDeviationSquare_
)
);
return
ABDKMathQuad.mul(
ABDKMathQuad.mul(
ABDKMathQuad.div(ONE, priceDelta),
oneDivDeviationSqrtTwoPi_
),
ABDKMathQuad.exp(res2)
);
}
function uint256ToBytes16(uint256 number_, uint256 scale_)
public
pure
returns (bytes16)
{
bytes16 number = ABDKMathQuad.fromUInt(number_);
bytes16 scale = ABDKMathQuad.fromUInt(scale_);
return ABDKMathQuad.div(number, scale);
}
function bytes16ToUnit256(bytes16 number_, uint256 scale_)
public
pure
returns (uint256)
{
bytes16 scale = ABDKMathQuad.fromUInt(scale_);
return ABDKMathQuad.toUInt(ABDKMathQuad.mul(number_, scale));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math Quad Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity >=0.6.6;
/**
* Smart contract library of mathematical functions operating with IEEE 754
* quadruple-precision binary floating-point numbers (quadruple precision
* numbers). As long as quadruple precision numbers are 16-bytes long, they are
* represented by bytes16 type.
*/
library ABDKMathQuad {
/*
* 0.
*/
bytes16 private constant POSITIVE_ZERO = 0x00000000000000000000000000000000;
/*
* -0.
*/
bytes16 private constant NEGATIVE_ZERO = 0x80000000000000000000000000000000;
/*
* +Infinity.
*/
bytes16 private constant POSITIVE_INFINITY = 0x7FFF0000000000000000000000000000;
/*
* -Infinity.
*/
bytes16 private constant NEGATIVE_INFINITY = 0xFFFF0000000000000000000000000000;
/*
* Canonical NaN value.
*/
bytes16 private constant NaN = 0x7FFF8000000000000000000000000000;
/**
* Convert signed 256-bit integer number into quadruple precision number.
*
* @param x signed 256-bit integer number
* @return quadruple precision number
*/
function fromInt (int256 x) internal pure returns (bytes16) {
if (x == 0) return bytes16 (0);
else {
// We rely on overflow behavior here
uint256 result = uint256 (x > 0 ? x : -x);
uint256 msb = msb (result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16383 + msb << 112;
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16 (uint128 (result));
}
}
/**
* Convert quadruple precision number into signed 256-bit integer number
* rounding towards zero. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 256-bit integer number
*/
function toInt (bytes16 x) internal pure returns (int256) {
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
require (exponent <= 16638); // Overflow
if (exponent < 16383) return 0; // Underflow
uint256 result = uint256 (uint128 (x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF |
0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
if (uint128 (x) >= 0x80000000000000000000000000000000) { // Negative
require (result <= 0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (result); // We rely on overflow behavior here
} else {
require (result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (result);
}
}
/**
* Convert unsigned 256-bit integer number into quadruple precision number.
*
* @param x unsigned 256-bit integer number
* @return quadruple precision number
*/
function fromUInt (uint256 x) internal pure returns (bytes16) {
if (x == 0) return bytes16 (0);
else {
uint256 result = x;
uint256 msb = msb (result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16383 + msb << 112;
return bytes16 (uint128 (result));
}
}
/**
* Convert quadruple precision number into unsigned 256-bit integer number
* rounding towards zero. Revert on underflow. Note, that negative floating
* point numbers in range (-1.0 .. 0.0) may be converted to unsigned integer
* without error, because they are rounded to zero.
*
* @param x quadruple precision number
* @return unsigned 256-bit integer number
*/
function toUInt (bytes16 x) internal pure returns (uint256) {
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
if (exponent < 16383) return 0; // Underflow
require (uint128 (x) < 0x80000000000000000000000000000000); // Negative
require (exponent <= 16638); // Overflow
uint256 result = uint256 (uint128 (x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF |
0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
return result;
}
/**
* Convert signed 128.128 bit fixed point number into quadruple precision
* number.
*
* @param x signed 128.128 bit fixed point number
* @return quadruple precision number
*/
function from128x128 (int256 x) internal pure returns (bytes16) {
if (x == 0) return bytes16 (0);
else {
// We rely on overflow behavior here
uint256 result = uint256 (x > 0 ? x : -x);
uint256 msb = msb (result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16255 + msb << 112;
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16 (uint128 (result));
}
}
/**
* Convert quadruple precision number into signed 128.128 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 128.128 bit fixed point number
*/
function to128x128 (bytes16 x) internal pure returns (int256) {
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
require (exponent <= 16510); // Overflow
if (exponent < 16255) return 0; // Underflow
uint256 result = uint256 (uint128 (x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF |
0x10000000000000000000000000000;
if (exponent < 16367) result >>= 16367 - exponent;
else if (exponent > 16367) result <<= exponent - 16367;
if (uint128 (x) >= 0x80000000000000000000000000000000) { // Negative
require (result <= 0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (result); // We rely on overflow behavior here
} else {
require (result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (result);
}
}
/**
* Convert signed 64.64 bit fixed point number into quadruple precision
* number.
*
* @param x signed 64.64 bit fixed point number
* @return quadruple precision number
*/
function from64x64 (int128 x) internal pure returns (bytes16) {
if (x == 0) return bytes16 (0);
else {
// We rely on overflow behavior here
uint256 result = uint128 (x > 0 ? x : -x);
uint256 msb = msb (result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16319 + msb << 112;
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16 (uint128 (result));
}
}
/**
* Convert quadruple precision number into signed 64.64 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 64.64 bit fixed point number
*/
function to64x64 (bytes16 x) internal pure returns (int128) {
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
require (exponent <= 16446); // Overflow
if (exponent < 16319) return 0; // Underflow
uint256 result = uint256 (uint128 (x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF |
0x10000000000000000000000000000;
if (exponent < 16431) result >>= 16431 - exponent;
else if (exponent > 16431) result <<= exponent - 16431;
if (uint128 (x) >= 0x80000000000000000000000000000000) { // Negative
require (result <= 0x80000000000000000000000000000000);
return -int128 (result); // We rely on overflow behavior here
} else {
require (result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (result);
}
}
/**
* Convert octuple precision number into quadruple precision number.
*
* @param x octuple precision number
* @return quadruple precision number
*/
function fromOctuple (bytes32 x) internal pure returns (bytes16) {
bool negative = x & 0x8000000000000000000000000000000000000000000000000000000000000000 > 0;
uint256 exponent = uint256 (x) >> 236 & 0x7FFFF;
uint256 significand = uint256 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFFF) {
if (significand > 0) return NaN;
else return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
}
if (exponent > 278526)
return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
else if (exponent < 245649)
return negative ? NEGATIVE_ZERO : POSITIVE_ZERO;
else if (exponent < 245761) {
significand = (significand | 0x100000000000000000000000000000000000000000000000000000000000) >> 245885 - exponent;
exponent = 0;
} else {
significand >>= 124;
exponent -= 245760;
}
uint128 result = uint128 (significand | exponent << 112);
if (negative) result |= 0x80000000000000000000000000000000;
return bytes16 (result);
}
/**
* Convert quadruple precision number into octuple precision number.
*
* @param x quadruple precision number
* @return octuple precision number
*/
function toOctuple (bytes16 x) internal pure returns (bytes32) {
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
uint256 result = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF) exponent = 0x7FFFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = msb (result);
result = result << 236 - msb & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 245649 + msb;
}
} else {
result <<= 124;
exponent += 245760;
}
result |= exponent << 236;
if (uint128 (x) >= 0x80000000000000000000000000000000)
result |= 0x8000000000000000000000000000000000000000000000000000000000000000;
return bytes32 (result);
}
/**
* Convert double precision number into quadruple precision number.
*
* @param x double precision number
* @return quadruple precision number
*/
function fromDouble (bytes8 x) internal pure returns (bytes16) {
uint256 exponent = uint64 (x) >> 52 & 0x7FF;
uint256 result = uint64 (x) & 0xFFFFFFFFFFFFF;
if (exponent == 0x7FF) exponent = 0x7FFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = msb (result);
result = result << 112 - msb & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 15309 + msb;
}
} else {
result <<= 60;
exponent += 15360;
}
result |= exponent << 112;
if (x & 0x8000000000000000 > 0)
result |= 0x80000000000000000000000000000000;
return bytes16 (uint128 (result));
}
/**
* Convert quadruple precision number into double precision number.
*
* @param x quadruple precision number
* @return double precision number
*/
function toDouble (bytes16 x) internal pure returns (bytes8) {
bool negative = uint128 (x) >= 0x80000000000000000000000000000000;
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
uint256 significand = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF) {
if (significand > 0) return 0x7FF8000000000000; // NaN
else return negative ?
bytes8 (0xFFF0000000000000) : // -Infinity
bytes8 (0x7FF0000000000000); // Infinity
}
if (exponent > 17406)
return negative ?
bytes8 (0xFFF0000000000000) : // -Infinity
bytes8 (0x7FF0000000000000); // Infinity
else if (exponent < 15309)
return negative ?
bytes8 (0x8000000000000000) : // -0
bytes8 (0x0000000000000000); // 0
else if (exponent < 15361) {
significand = (significand | 0x10000000000000000000000000000) >> 15421 - exponent;
exponent = 0;
} else {
significand >>= 60;
exponent -= 15360;
}
uint64 result = uint64 (significand | exponent << 52);
if (negative) result |= 0x8000000000000000;
return bytes8 (result);
}
/**
* Test whether given quadruple precision number is NaN.
*
* @param x quadruple precision number
* @return true if x is NaN, false otherwise
*/
function isNaN (bytes16 x) internal pure returns (bool) {
return uint128 (x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF >
0x7FFF0000000000000000000000000000;
}
/**
* Test whether given quadruple precision number is positive or negative
* infinity.
*
* @param x quadruple precision number
* @return true if x is positive or negative infinity, false otherwise
*/
function isInfinity (bytes16 x) internal pure returns (bool) {
return uint128 (x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ==
0x7FFF0000000000000000000000000000;
}
/**
* Calculate sign of x, i.e. -1 if x is negative, 0 if x if zero, and 1 if x
* is positive. Note that sign (-0) is zero. Revert if x is NaN.
*
* @param x quadruple precision number
* @return sign of x
*/
function sign (bytes16 x) internal pure returns (int8) {
uint128 absoluteX = uint128 (x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require (absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
if (absoluteX == 0) return 0;
else if (uint128 (x) >= 0x80000000000000000000000000000000) return -1;
else return 1;
}
/**
* Calculate sign (x - y). Revert if either argument is NaN, or both
* arguments are infinities of the same sign.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return sign (x - y)
*/
function cmp (bytes16 x, bytes16 y) internal pure returns (int8) {
uint128 absoluteX = uint128 (x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require (absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
uint128 absoluteY = uint128 (y) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require (absoluteY <= 0x7FFF0000000000000000000000000000); // Not NaN
// Not infinities of the same sign
require (x != y || absoluteX < 0x7FFF0000000000000000000000000000);
if (x == y) return 0;
else {
bool negativeX = uint128 (x) >= 0x80000000000000000000000000000000;
bool negativeY = uint128 (y) >= 0x80000000000000000000000000000000;
if (negativeX) {
if (negativeY) return absoluteX > absoluteY ? -1 : int8 (1);
else return -1;
} else {
if (negativeY) return 1;
else return absoluteX > absoluteY ? int8 (1) : -1;
}
}
}
/**
* Test whether x equals y. NaN, infinity, and -infinity are not equal to
* anything.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return true if x equals to y, false otherwise
*/
function eq (bytes16 x, bytes16 y) internal pure returns (bool) {
if (x == y) {
return uint128 (x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF <
0x7FFF0000000000000000000000000000;
} else return false;
}
/**
* Calculate x + y. Special values behave in the following way:
*
* NaN + x = NaN for any x.
* Infinity + x = Infinity for any finite x.
* -Infinity + x = -Infinity for any finite x.
* Infinity + Infinity = Infinity.
* -Infinity + -Infinity = -Infinity.
* Infinity + -Infinity = -Infinity + Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function add (bytes16 x, bytes16 y) internal pure returns (bytes16) {
uint256 xExponent = uint128 (x) >> 112 & 0x7FFF;
uint256 yExponent = uint128 (y) >> 112 & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y) return x;
else return NaN;
} else return x;
} else if (yExponent == 0x7FFF) return y;
else {
bool xSign = uint128 (x) >= 0x80000000000000000000000000000000;
uint256 xSignifier = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
bool ySign = uint128 (y) >= 0x80000000000000000000000000000000;
uint256 ySignifier = uint128 (y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return y == NEGATIVE_ZERO ? POSITIVE_ZERO : y;
else if (ySignifier == 0) return x == NEGATIVE_ZERO ? POSITIVE_ZERO : x;
else {
int256 delta = int256 (xExponent) - int256 (yExponent);
if (xSign == ySign) {
if (delta > 112) return x;
else if (delta > 0) ySignifier >>= uint256 (delta);
else if (delta < -112) return y;
else if (delta < 0) {
xSignifier >>= uint256 (-delta);
xExponent = yExponent;
}
xSignifier += ySignifier;
if (xSignifier >= 0x20000000000000000000000000000) {
xSignifier >>= 1;
xExponent += 1;
}
if (xExponent == 0x7FFF)
return xSign ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
else {
if (xSignifier < 0x10000000000000000000000000000) xExponent = 0;
else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
return bytes16 (uint128 (
(xSign ? 0x80000000000000000000000000000000 : 0) |
(xExponent << 112) |
xSignifier));
}
} else {
if (delta > 0) {
xSignifier <<= 1;
xExponent -= 1;
} else if (delta < 0) {
ySignifier <<= 1;
xExponent = yExponent - 1;
}
if (delta > 112) ySignifier = 1;
else if (delta > 1) ySignifier = (ySignifier - 1 >> uint256 (delta - 1)) + 1;
else if (delta < -112) xSignifier = 1;
else if (delta < -1) xSignifier = (xSignifier - 1 >> uint256 (-delta - 1)) + 1;
if (xSignifier >= ySignifier) xSignifier -= ySignifier;
else {
xSignifier = ySignifier - xSignifier;
xSign = ySign;
}
if (xSignifier == 0)
return POSITIVE_ZERO;
uint256 msb = msb (xSignifier);
if (msb == 113) {
xSignifier = xSignifier >> 1 & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent += 1;
} else if (msb < 112) {
uint256 shift = 112 - msb;
if (xExponent > shift) {
xSignifier = xSignifier << shift & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent -= shift;
} else {
xSignifier <<= xExponent - 1;
xExponent = 0;
}
} else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF)
return xSign ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
else return bytes16 (uint128 (
(xSign ? 0x80000000000000000000000000000000 : 0) |
(xExponent << 112) |
xSignifier));
}
}
}
}
/**
* Calculate x - y. Special values behave in the following way:
*
* NaN - x = NaN for any x.
* Infinity - x = Infinity for any finite x.
* -Infinity - x = -Infinity for any finite x.
* Infinity - -Infinity = Infinity.
* -Infinity - Infinity = -Infinity.
* Infinity - Infinity = -Infinity - -Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function sub (bytes16 x, bytes16 y) internal pure returns (bytes16) {
return add (x, y ^ 0x80000000000000000000000000000000);
}
/**
* Calculate x * y. Special values behave in the following way:
*
* NaN * x = NaN for any x.
* Infinity * x = Infinity for any finite positive x.
* Infinity * x = -Infinity for any finite negative x.
* -Infinity * x = -Infinity for any finite positive x.
* -Infinity * x = Infinity for any finite negative x.
* Infinity * 0 = NaN.
* -Infinity * 0 = NaN.
* Infinity * Infinity = Infinity.
* Infinity * -Infinity = -Infinity.
* -Infinity * Infinity = -Infinity.
* -Infinity * -Infinity = Infinity.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function mul (bytes16 x, bytes16 y) internal pure returns (bytes16) {
uint256 xExponent = uint128 (x) >> 112 & 0x7FFF;
uint256 yExponent = uint128 (y) >> 112 & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y) return x ^ y & 0x80000000000000000000000000000000;
else if (x ^ y == 0x80000000000000000000000000000000) return x | y;
else return NaN;
} else {
if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return x ^ y & 0x80000000000000000000000000000000;
}
} else if (yExponent == 0x7FFF) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return y ^ x & 0x80000000000000000000000000000000;
} else {
uint256 xSignifier = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
uint256 ySignifier = uint128 (y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
xSignifier *= ySignifier;
if (xSignifier == 0)
return (x ^ y) & 0x80000000000000000000000000000000 > 0 ?
NEGATIVE_ZERO : POSITIVE_ZERO;
xExponent += yExponent;
uint256 msb =
xSignifier >= 0x200000000000000000000000000000000000000000000000000000000 ? 225 :
xSignifier >= 0x100000000000000000000000000000000000000000000000000000000 ? 224 :
msb (xSignifier);
if (xExponent + msb < 16496) { // Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb < 16608) { // Subnormal
if (xExponent < 16496)
xSignifier >>= 16496 - xExponent;
else if (xExponent > 16496)
xSignifier <<= xExponent - 16496;
xExponent = 0;
} else if (xExponent + msb > 49373) {
xExponent = 0x7FFF;
xSignifier = 0;
} else {
if (msb > 112)
xSignifier >>= msb - 112;
else if (msb < 112)
xSignifier <<= 112 - msb;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb - 16607;
}
return bytes16 (uint128 (uint128 ((x ^ y) & 0x80000000000000000000000000000000) |
xExponent << 112 | xSignifier));
}
}
/**
* Calculate x / y. Special values behave in the following way:
*
* NaN / x = NaN for any x.
* x / NaN = NaN for any x.
* Infinity / x = Infinity for any finite non-negative x.
* Infinity / x = -Infinity for any finite negative x including -0.
* -Infinity / x = -Infinity for any finite non-negative x.
* -Infinity / x = Infinity for any finite negative x including -0.
* x / Infinity = 0 for any finite non-negative x.
* x / -Infinity = -0 for any finite non-negative x.
* x / Infinity = -0 for any finite non-negative x including -0.
* x / -Infinity = 0 for any finite non-negative x including -0.
*
* Infinity / Infinity = NaN.
* Infinity / -Infinity = -NaN.
* -Infinity / Infinity = -NaN.
* -Infinity / -Infinity = NaN.
*
* Division by zero behaves in the following way:
*
* x / 0 = Infinity for any finite positive x.
* x / -0 = -Infinity for any finite positive x.
* x / 0 = -Infinity for any finite negative x.
* x / -0 = Infinity for any finite negative x.
* 0 / 0 = NaN.
* 0 / -0 = NaN.
* -0 / 0 = NaN.
* -0 / -0 = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function div (bytes16 x, bytes16 y) internal pure returns (bytes16) {
uint256 xExponent = uint128 (x) >> 112 & 0x7FFF;
uint256 yExponent = uint128 (y) >> 112 & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) return NaN;
else return x ^ y & 0x80000000000000000000000000000000;
} else if (yExponent == 0x7FFF) {
if (y & 0x0000FFFFFFFFFFFFFFFFFFFFFFFFFFFF != 0) return NaN;
else return POSITIVE_ZERO | (x ^ y) & 0x80000000000000000000000000000000;
} else if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return POSITIVE_INFINITY | (x ^ y) & 0x80000000000000000000000000000000;
} else {
uint256 ySignifier = uint128 (y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
uint256 xSignifier = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) {
if (xSignifier != 0) {
uint shift = 226 - msb (xSignifier);
xSignifier <<= shift;
xExponent = 1;
yExponent += shift - 114;
}
}
else {
xSignifier = (xSignifier | 0x10000000000000000000000000000) << 114;
}
xSignifier = xSignifier / ySignifier;
if (xSignifier == 0)
return (x ^ y) & 0x80000000000000000000000000000000 > 0 ?
NEGATIVE_ZERO : POSITIVE_ZERO;
assert (xSignifier >= 0x1000000000000000000000000000);
uint256 msb =
xSignifier >= 0x80000000000000000000000000000 ? msb (xSignifier) :
xSignifier >= 0x40000000000000000000000000000 ? 114 :
xSignifier >= 0x20000000000000000000000000000 ? 113 : 112;
if (xExponent + msb > yExponent + 16497) { // Overflow
xExponent = 0x7FFF;
xSignifier = 0;
} else if (xExponent + msb + 16380 < yExponent) { // Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb + 16268 < yExponent) { // Subnormal
if (xExponent + 16380 > yExponent)
xSignifier <<= xExponent + 16380 - yExponent;
else if (xExponent + 16380 < yExponent)
xSignifier >>= yExponent - xExponent - 16380;
xExponent = 0;
} else { // Normal
if (msb > 112)
xSignifier >>= msb - 112;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb + 16269 - yExponent;
}
return bytes16 (uint128 (uint128 ((x ^ y) & 0x80000000000000000000000000000000) |
xExponent << 112 | xSignifier));
}
}
/**
* Calculate -x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function neg (bytes16 x) internal pure returns (bytes16) {
return x ^ 0x80000000000000000000000000000000;
}
/**
* Calculate |x|.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function abs (bytes16 x) internal pure returns (bytes16) {
return x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
}
/**
* Calculate square root of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function sqrt (bytes16 x) internal pure returns (bytes16) {
if (uint128 (x) > 0x80000000000000000000000000000000) return NaN;
else {
uint256 xExponent = uint128 (x) >> 112 & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return POSITIVE_ZERO;
bool oddExponent = xExponent & 0x1 == 0;
xExponent = xExponent + 16383 >> 1;
if (oddExponent) {
if (xSignifier >= 0x10000000000000000000000000000)
xSignifier <<= 113;
else {
uint256 msb = msb (xSignifier);
uint256 shift = (226 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= shift - 112 >> 1;
}
} else {
if (xSignifier >= 0x10000000000000000000000000000)
xSignifier <<= 112;
else {
uint256 msb = msb (xSignifier);
uint256 shift = (225 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= shift - 112 >> 1;
}
}
uint256 r = 0x10000000000000000000000000000;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1; // Seven iterations should be enough
uint256 r1 = xSignifier / r;
if (r1 < r) r = r1;
return bytes16 (uint128 (xExponent << 112 | r & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF));
}
}
}
/**
* Calculate binary logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function log_2 (bytes16 x) internal pure returns (bytes16) {
if (uint128 (x) > 0x80000000000000000000000000000000) return NaN;
else if (x == 0x3FFF0000000000000000000000000000) return POSITIVE_ZERO;
else {
uint256 xExponent = uint128 (x) >> 112 & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return NEGATIVE_INFINITY;
bool resultNegative;
uint256 resultExponent = 16495;
uint256 resultSignifier;
if (xExponent >= 0x3FFF) {
resultNegative = false;
resultSignifier = xExponent - 0x3FFF;
xSignifier <<= 15;
} else {
resultNegative = true;
if (xSignifier >= 0x10000000000000000000000000000) {
resultSignifier = 0x3FFE - xExponent;
xSignifier <<= 15;
} else {
uint256 msb = msb (xSignifier);
resultSignifier = 16493 - msb;
xSignifier <<= 127 - msb;
}
}
if (xSignifier == 0x80000000000000000000000000000000) {
if (resultNegative) resultSignifier += 1;
uint256 shift = 112 - msb (resultSignifier);
resultSignifier <<= shift;
resultExponent -= shift;
} else {
uint256 bb = resultNegative ? 1 : 0;
while (resultSignifier < 0x10000000000000000000000000000) {
resultSignifier <<= 1;
resultExponent -= 1;
xSignifier *= xSignifier;
uint256 b = xSignifier >> 255;
resultSignifier += b ^ bb;
xSignifier >>= 127 + b;
}
}
return bytes16 (uint128 ((resultNegative ? 0x80000000000000000000000000000000 : 0) |
resultExponent << 112 | resultSignifier & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF));
}
}
}
/**
* Calculate natural logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function ln (bytes16 x) internal pure returns (bytes16) {
return mul (log_2 (x), 0x3FFE62E42FEFA39EF35793C7673007E5);
}
/**
* Calculate 2^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function pow_2 (bytes16 x) internal pure returns (bytes16) {
bool xNegative = uint128 (x) > 0x80000000000000000000000000000000;
uint256 xExponent = uint128 (x) >> 112 & 0x7FFF;
uint256 xSignifier = uint128 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF && xSignifier != 0) return NaN;
else if (xExponent > 16397)
return xNegative ? POSITIVE_ZERO : POSITIVE_INFINITY;
else if (xExponent < 16255)
return 0x3FFF0000000000000000000000000000;
else {
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xExponent > 16367)
xSignifier <<= xExponent - 16367;
else if (xExponent < 16367)
xSignifier >>= 16367 - xExponent;
if (xNegative && xSignifier > 0x406E00000000000000000000000000000000)
return POSITIVE_ZERO;
if (!xNegative && xSignifier > 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
return POSITIVE_INFINITY;
uint256 resultExponent = xSignifier >> 128;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xNegative && xSignifier != 0) {
xSignifier = ~xSignifier;
resultExponent += 1;
}
uint256 resultSignifier = 0x80000000000000000000000000000000;
if (xSignifier & 0x80000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (xSignifier & 0x40000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (xSignifier & 0x20000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (xSignifier & 0x10000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (xSignifier & 0x8000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (xSignifier & 0x4000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (xSignifier & 0x2000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (xSignifier & 0x1000000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (xSignifier & 0x800000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (xSignifier & 0x400000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (xSignifier & 0x200000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (xSignifier & 0x100000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (xSignifier & 0x80000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (xSignifier & 0x40000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (xSignifier & 0x20000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000162E525EE054754457D5995292026 >> 128;
if (xSignifier & 0x10000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (xSignifier & 0x8000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (xSignifier & 0x4000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (xSignifier & 0x2000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (xSignifier & 0x1000000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (xSignifier & 0x800000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (xSignifier & 0x400000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (xSignifier & 0x200000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (xSignifier & 0x100000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (xSignifier & 0x80000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (xSignifier & 0x40000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (xSignifier & 0x20000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (xSignifier & 0x10000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (xSignifier & 0x8000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (xSignifier & 0x4000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (xSignifier & 0x2000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (xSignifier & 0x1000000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (xSignifier & 0x800000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (xSignifier & 0x400000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (xSignifier & 0x200000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (xSignifier & 0x100000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (xSignifier & 0x80000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (xSignifier & 0x40000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (xSignifier & 0x20000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (xSignifier & 0x10000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (xSignifier & 0x8000000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (xSignifier & 0x4000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (xSignifier & 0x2000000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (xSignifier & 0x1000000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (xSignifier & 0x800000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (xSignifier & 0x400000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (xSignifier & 0x200000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (xSignifier & 0x100000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (xSignifier & 0x80000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (xSignifier & 0x40000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (xSignifier & 0x20000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (xSignifier & 0x10000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (xSignifier & 0x8000000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (xSignifier & 0x4000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (xSignifier & 0x2000000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (xSignifier & 0x1000000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (xSignifier & 0x800000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (xSignifier & 0x400000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (xSignifier & 0x200000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000162E42FEFA39EF366F >> 128;
if (xSignifier & 0x100000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (xSignifier & 0x80000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (xSignifier & 0x40000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (xSignifier & 0x20000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (xSignifier & 0x10000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000B17217F7D1CF79AB >> 128;
if (xSignifier & 0x8000000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000058B90BFBE8E7BCD5 >> 128;
if (xSignifier & 0x4000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000002C5C85FDF473DE6A >> 128;
if (xSignifier & 0x2000000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000162E42FEFA39EF34 >> 128;
if (xSignifier & 0x1000000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000B17217F7D1CF799 >> 128;
if (xSignifier & 0x800000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000058B90BFBE8E7BCC >> 128;
if (xSignifier & 0x400000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000002C5C85FDF473DE5 >> 128;
if (xSignifier & 0x200000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000162E42FEFA39EF2 >> 128;
if (xSignifier & 0x100000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000B17217F7D1CF78 >> 128;
if (xSignifier & 0x80000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000058B90BFBE8E7BB >> 128;
if (xSignifier & 0x40000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000002C5C85FDF473DD >> 128;
if (xSignifier & 0x20000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000162E42FEFA39EE >> 128;
if (xSignifier & 0x10000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000B17217F7D1CF6 >> 128;
if (xSignifier & 0x8000000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000058B90BFBE8E7A >> 128;
if (xSignifier & 0x4000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000002C5C85FDF473C >> 128;
if (xSignifier & 0x2000000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000162E42FEFA39D >> 128;
if (xSignifier & 0x1000000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000B17217F7D1CE >> 128;
if (xSignifier & 0x800000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000058B90BFBE8E6 >> 128;
if (xSignifier & 0x400000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000002C5C85FDF472 >> 128;
if (xSignifier & 0x200000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000162E42FEFA38 >> 128;
if (xSignifier & 0x100000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000B17217F7D1B >> 128;
if (xSignifier & 0x80000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000058B90BFBE8D >> 128;
if (xSignifier & 0x40000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000002C5C85FDF46 >> 128;
if (xSignifier & 0x20000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000162E42FEFA2 >> 128;
if (xSignifier & 0x10000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000B17217F7D0 >> 128;
if (xSignifier & 0x8000000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000058B90BFBE7 >> 128;
if (xSignifier & 0x4000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000002C5C85FDF3 >> 128;
if (xSignifier & 0x2000000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000162E42FEF9 >> 128;
if (xSignifier & 0x1000000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000B17217F7C >> 128;
if (xSignifier & 0x800000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000058B90BFBD >> 128;
if (xSignifier & 0x400000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000002C5C85FDE >> 128;
if (xSignifier & 0x200000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000162E42FEE >> 128;
if (xSignifier & 0x100000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000B17217F6 >> 128;
if (xSignifier & 0x80000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000058B90BFA >> 128;
if (xSignifier & 0x40000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000002C5C85FC >> 128;
if (xSignifier & 0x20000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000162E42FD >> 128;
if (xSignifier & 0x10000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000B17217E >> 128;
if (xSignifier & 0x8000000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000058B90BE >> 128;
if (xSignifier & 0x4000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000002C5C85E >> 128;
if (xSignifier & 0x2000000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000162E42E >> 128;
if (xSignifier & 0x1000000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000B17216 >> 128;
if (xSignifier & 0x800000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000058B90A >> 128;
if (xSignifier & 0x400000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000002C5C84 >> 128;
if (xSignifier & 0x200000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000162E41 >> 128;
if (xSignifier & 0x100000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000000B1720 >> 128;
if (xSignifier & 0x80000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000058B8F >> 128;
if (xSignifier & 0x40000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000002C5C7 >> 128;
if (xSignifier & 0x20000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000000162E3 >> 128;
if (xSignifier & 0x10000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000000B171 >> 128;
if (xSignifier & 0x8000 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000000058B8 >> 128;
if (xSignifier & 0x4000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000002C5B >> 128;
if (xSignifier & 0x2000 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000000162D >> 128;
if (xSignifier & 0x1000 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000000B16 >> 128;
if (xSignifier & 0x800 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000000058A >> 128;
if (xSignifier & 0x400 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000000002C4 >> 128;
if (xSignifier & 0x200 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000000161 >> 128;
if (xSignifier & 0x100 > 0) resultSignifier = resultSignifier * 0x1000000000000000000000000000000B0 >> 128;
if (xSignifier & 0x80 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000000057 >> 128;
if (xSignifier & 0x40 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000000002B >> 128;
if (xSignifier & 0x20 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000000015 >> 128;
if (xSignifier & 0x10 > 0) resultSignifier = resultSignifier * 0x10000000000000000000000000000000A >> 128;
if (xSignifier & 0x8 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000000004 >> 128;
if (xSignifier & 0x4 > 0) resultSignifier = resultSignifier * 0x100000000000000000000000000000001 >> 128;
if (!xNegative) {
resultSignifier = resultSignifier >> 15 & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent += 0x3FFF;
} else if (resultExponent <= 0x3FFE) {
resultSignifier = resultSignifier >> 15 & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent = 0x3FFF - resultExponent;
} else {
resultSignifier = resultSignifier >> resultExponent - 16367;
resultExponent = 0;
}
return bytes16 (uint128 (resultExponent << 112 | resultSignifier));
}
}
/**
* Calculate e^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function exp (bytes16 x) internal pure returns (bytes16) {
return pow_2 (mul (x, 0x3FFF71547652B82FE1777D0FFDA0D23A));
}
/**
* Get index of the most significant non-zero bit in binary representation of
* x. Reverts if x is zero.
*
* @return index of the most significant non-zero bit in binary representation
* of x
*/
function msb (uint256 x) private pure returns (uint256) {
require (x > 0);
uint256 result = 0;
if (x >= 0x100000000000000000000000000000000) { x >>= 128; result += 128; }
if (x >= 0x10000000000000000) { x >>= 64; result += 64; }
if (x >= 0x100000000) { x >>= 32; result += 32; }
if (x >= 0x10000) { x >>= 16; result += 16; }
if (x >= 0x100) { x >>= 8; result += 8; }
if (x >= 0x10) { x >>= 4; result += 4; }
if (x >= 0x4) { x >>= 2; result += 2; }
if (x >= 0x2) result += 1; // No need to shift x anymore
return result;
}
} | Function to set the reward duration for a single epoch reward period rewardBlockPeriod_ New block duration period/ | function setRewardBlockPeriod(uint256 rewardBlockPeriod_)
external
onlyOwner
{
rewardBlockPeriod = rewardBlockPeriod_;
emit LogSetRewardBlockPeriod(rewardBlockPeriod);
}
| 1,329,945 |
// 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;
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.6.0 <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;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view 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 { }
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20Mintable is ERC20, Ownable {
using SafeMath for uint;
constructor (string memory name_, string memory symbol_, uint totalSupply_)
ERC20(name_, symbol_)
public
{
_mint(_msgSender(), totalSupply_);
}
function mint(address to, uint256 amount)
public
onlyOwner
returns(bool)
{
_mint(to, amount);
return true;
}
}
/**
* @notice This contract is used to bridge WeOwn blockchain and any other blockchain running on EVM, primarily Ethereum.
* After establishing bridge between asset on WeOwn blockchain and ERC20 token, cross-chain transfers are enabled and
* users can move their holding between the blockchains.
*/
contract OwnAssetBridge is Ownable {
using SafeMath for uint;
enum RevertDirection{ FromNative, ToNative }
event CrossChainTransfer(address indexed token, string recipientAccountHash, uint amount);
event CrossChainTransfer(string txHash, address recipient);
mapping (string => address) public erc20Tokens;
mapping (address => string) public assetHashes;
mapping (string => string) public accountsForAssets;
mapping (string => address) public pendingCrossChainTransfers;
mapping (string => string) public pendingSignedTxs;
address public governor;
uint public targetTransferFee;
uint public nativeTransferFee;
uint public bridgeFee;
constructor(uint _bridgeFee, uint _targetTransferFee, uint _nativeTransferFee)
public
{
bridgeFee = _bridgeFee;
targetTransferFee = _targetTransferFee;
nativeTransferFee = _nativeTransferFee;
governor = _msgSender();
}
modifier onlyGovernor() {
require(_msgSender() == governor, "Caller is not the governor");
_;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Bridge management
////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Function that establishes bridge between existing ERC20 token and newly created asset on WeOwn blockchain.
* This function can only be called by the governor and all tokens should be circulating on target blockchain, while
* total supply is locked on WeOwn blockchain.
*/
/// @param _token Address of ERC20 token
/// @param _assetHash Hash of WeOwn asset
/// @param _accountHash Hash of WeOwn account that will hold all locked tokens on WeOwn blockchain
function bridgeErc20Token(address _token, string calldata _assetHash, string calldata _accountHash)
external
onlyGovernor
payable
{
require(erc20Tokens[_assetHash] == address(0));
require(bytes(assetHashes[_token]).length == 0);
require(bytes(accountsForAssets[_assetHash]).length == 0);
require(IERC20(_token).balanceOf(address(this)) == 0);
require(msg.value >= bridgeFee);
erc20Tokens[_assetHash] = _token;
assetHashes[_token] = _assetHash;
accountsForAssets[_assetHash] = _accountHash;
}
/**
* @notice Function that deploys new ERC20 token and establishes bridge between existing asset on WeOwn blockchain
* and newly created ERC20 token. This function can only be called by the governor and all tokens should be
* circulating on WeOwn blockchain, while total supply is locked on target blockchain.
*/
/// @param _assetHash Hash of WeOwn asset
/// @param _accountHash Hash of WeOwn account that will hold all locked tokens on WeOwn blockchain
/// @param _assetName Name of ERC20 token that will be deployed. Needs to correspond to the name of WeOwn asset
/// @param _assetSymbol Symbol of ERC20 token that will be deployed. Needs to correspond to the symbol of WeOwn asset
/// @param _totalSupply Total supply of ERC20 token that will be deployed. Needs to correspond to the total supply of WeOwn asset
function bridgeAsset(
string calldata _assetHash,
string calldata _accountHash,
string calldata _assetName,
string calldata _assetSymbol,
uint _totalSupply)
external
onlyGovernor
payable
{
require(erc20Tokens[_assetHash] == address(0));
require(bytes(accountsForAssets[_assetHash]).length == 0);
require(msg.value >= bridgeFee);
address token = address(new ERC20Mintable(_assetName, _assetSymbol, _totalSupply));
erc20Tokens[_assetHash] = token;
assetHashes[token] = _assetHash;
accountsForAssets[_assetHash] = _accountHash;
}
/**
* @notice Function that removes bridge between ERC20 token and asset on WeOwn blockchain. This function can only
* be called by the governor and all tokens should be circulating on target blockchain or on WeOwn blockchain.
*/
/// @param _token Address of ERC20 token
function removeBridge(address _token)
external
onlyGovernor
{
string memory assetHash = assetHashes[_token];
require(bytes(assetHash).length != 0);
require(erc20Tokens[assetHash] == _token);
require(bytes(accountsForAssets[assetHash]).length != 0);
uint bridgeBalance = IERC20(_token).balanceOf(address(this));
require(bridgeBalance == 0 || bridgeBalance == IERC20(_token).totalSupply());
delete erc20Tokens[assetHash];
delete assetHashes[_token];
delete accountsForAssets[assetHash];
}
/**
* @notice Function that mints ERC20 token created by the bridge. This function can only
* be called by the governor in order to ensure consistency between WeOwn and target blockchains.
*/
/// @param _token Address of ERC20 token
/// @param _amount Amount of tokens that will be minted
function mintErc20Token(address _token, uint _amount)
external
onlyGovernor
{
require(ERC20Mintable(_token).mint(address(this), _amount));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Cross-chain transfers
////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Function by which token holder on target blockchain can transfer tokens to WeOwn blockchain.
* ERC20 token needs to be bridged to WeOwn asset and user should previously approve this contract as
* spender of desired amount of tokens that should be cross-chain transferred.
*/
/// @param _token Address of ERC20 token
/// @param _recipientAccountHash Hash of WeOwn account that should receive tokens
/// @param _amount Number of tokens that will be transferred
function transferToNativeChain(address _token, string calldata _recipientAccountHash, uint _amount)
external
payable
{
require(msg.value >= nativeTransferFee, "Insufficient fee is paid");
require(bytes(assetHashes[_token]).length != 0, "Token is not bridged");
require(IERC20(_token).transferFrom(_msgSender(), address(this), _amount), "Transfer failed");
emit CrossChainTransfer(_token, _recipientAccountHash, _amount);
}
/**
* @notice Function by which asset holder on WeOwn blockchain can transfer tokens to target blockchain.
* Asset needs to be bridged to ERC20 token and asset transfer should be done on WeOwn blockchain.
*/
/// @param _txHash Hash of tx on WeOwn blockchain which contains asset transfer
/// @param _signature Signature of tx hash, signed by WeOwn sender address
/// @param _recipient Address on target blockchain that should receive tokens
function transferFromNativeChain(string calldata _txHash, string calldata _signature, address _recipient)
external
payable
{
require(msg.value >= targetTransferFee, "Insufficient fee is paid");
require(pendingCrossChainTransfers[_txHash] == address(0), "Recipient is already determined");
require(bytes(pendingSignedTxs[_txHash]).length == 0, "Signature is already determined");
pendingCrossChainTransfers[_txHash] = _recipient;
pendingSignedTxs[_txHash] = _signature;
emit CrossChainTransfer(_txHash, _recipient);
}
/**
* @notice Function by which contract owner confirms cross-chain transfer from WeOwn blockchain. If the tx with
* asset transfer on WeOwn blockchain is valid and correctly signed, tokens will be released to address on target blockchain.
*/
/// @param _txHash Hash of tx on WeOwn blockchain which contains asset transfer
/// @param _token Address of ERC20 token
/// @param _amount Amount of tokens that will be released
function confirmTransfer(string calldata _txHash, IERC20 _token, uint _amount)
external
onlyOwner
{
address recipient = pendingCrossChainTransfers[_txHash];
require(recipient != address(0), "Recipient does not exist");
delete pendingCrossChainTransfers[_txHash];
delete pendingSignedTxs[_txHash];
require(_token.transfer(recipient, _amount), "Transfer failed");
}
/**
* @notice Function by which contract owner reverts cross-chain transfer from WeOwn blockchain.
*/
/// @param _txHash Hash of tx on WeOwn blockchain which contains asset transfer
function revertTransferFromNativeChain(string calldata _txHash)
external
onlyOwner
{
require(pendingCrossChainTransfers[_txHash] != address(0), "Tx does not exist");
delete pendingCrossChainTransfers[_txHash];
delete pendingSignedTxs[_txHash];
}
/**
* @notice Function by which contract owner reverts cross-chain transfer from target blockchain.
*/
/// @param _txHash Hash of tx on target blockchain that is reverted
/// @param _token Address of ERC20 token
/// @param _recipient Sender address to which tokens will be transferred back
/// @param _amount Amount of tokens that will be transferred back to sender address
function revertTransferToNativeChain(string calldata _txHash, IERC20 _token, address _recipient, uint _amount)
external
onlyOwner
{
require(_token.transfer(_recipient, _amount), "Transfer failed");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Owner administration
////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Function by which contract owner sets governor address - address that can perform bridging and unbridging
* of ERC20 token and WeOwn asset.
*/
/// @param _governor New governor address
function setGovernor(address _governor)
external
onlyOwner
{
governor = _governor;
}
/**
* @notice Function by which contract owner sets fee that is paid for cross-chain transfer from WeOwn to target blockchain
*/
/// @param _amount New fee amount
function setTargetTransferFee(uint _amount)
external
onlyOwner
{
targetTransferFee = _amount;
}
/**
* @notice Function by which contract owner sets fee that is paid for cross-chain transfer from target to WeOwn blockchain
*/
/// @param _amount New fee amount
function setNativeTransferFee(uint _amount)
external
onlyOwner
{
nativeTransferFee = _amount;
}
/**
* @notice Function by which contract owner sets fee that is paid by governor when establishing bridge
*/
/// @param _amount New fee amount
function setBridgeFee(uint _amount)
external
onlyOwner
{
bridgeFee = _amount;
}
/**
* @notice Function by which contract owner withdraws fee collected through bridging and cross-chain transfers
*/
/// @param _amount Amount to be withdrawn
function withdrawFee(uint _amount)
external
onlyOwner
returns (bool)
{
payable(owner()).transfer(_amount);
return true;
}
} | Function by which contract owner sets fee that is paid by governor when establishing bridge/ _amount New fee amount | function setBridgeFee(uint _amount)
external
onlyOwner
{
bridgeFee = _amount;
}
| 13,848,587 |
contract WalletLibrary {
uint private creationTime = now;
//States definition
enum States {
InTransition,
InitialState
}
States private state = States.InitialState;
//Insert variable definitions
address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe;
uint public m_required;
uint public m_numOwners;
uint public m_dailyLimit;
uint public m_spentToday;
uint public m_lastDay;
uint[256] m_owners;
uint constant c_maxOwners = 250;
mapping(uint => uint) m_ownerIndex;
mapping(bytes32 => PendingState) m_pending;
bytes32[] m_pendingIndex;
mapping (bytes32 => Transaction) m_txs;
struct PendingState {
uint yetNeeded;
uint ownersDone;
uint index;
}
struct Transaction {
address to;
uint value;
bytes data;
}
event Confirmation(address owner, bytes32 operation);
event Revoke(address owner, bytes32 operation);
event OwnerChanged(address oldOwner, address newOwner);
event OwnerAdded(address newOwner);
event OwnerRemoved(address oldOwner);
event RequirementChanged(uint newRequirement);
event Deposit(address _from, uint value);
event SingleTransact(address owner, uint value, address to, bytes data, address created);
event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created);
event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data);
modifier onlyowner {
if (isOwner(msg.sender))
_;
}
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation))
_;
}
modifier only_uninitialized { if (m_numOwners > 0) throw; _; }
//Transitions
function addOwner (address _owner)
onlymanyowners(sha3(msg.data)) external
{
require(state == States.InitialState);
state = States.InTransition;
//Actions
if (isOwner(_owner)) return;
clearPending();
if (m_numOwners >= c_maxOwners)
reorganizeOwners();
if (m_numOwners >= c_maxOwners)
return;
m_numOwners++;
m_owners[m_numOwners] = uint(_owner);
m_ownerIndex[uint(_owner)] = m_numOwners;
OwnerAdded(_owner);
//State change
state = States.InitialState;
}
function changeOwner (address _from, address _to)
onlymanyowners(sha3(msg.data)) external
{
require(state == States.InitialState);
state = States.InTransition;
//Actions
if (isOwner(_to)) return;
uint ownerIndex = m_ownerIndex[uint(_from)];
if (ownerIndex == 0) return;
clearPending();
m_owners[ownerIndex] = uint(_to);
m_ownerIndex[uint(_from)] = 0;
m_ownerIndex[uint(_to)] = ownerIndex;
OwnerChanged(_from, _to);
//State change
state = States.InitialState;
}
function changeRequirement (uint _newRequired)
onlymanyowners(sha3(msg.data)) external
{
require(state == States.InitialState);
state = States.InTransition;
//Actions
if (_newRequired > m_numOwners) return;
m_required = _newRequired;
clearPending();
RequirementChanged(_newRequired);
//State change
state = States.InitialState;
}
function clearPending ()
internal
{
require(state == States.InitialState);
//State change
state = States.InTransition;
//Actions
uint length = m_pendingIndex.length;
for (uint i = 0; i < length; ++i) {
delete m_txs[m_pendingIndex[i]];
if (m_pendingIndex[i] != 0)
delete m_pending[m_pendingIndex[i]];
}
delete m_pendingIndex;
//State change
state = States.InitialState;
}
function confirm (bytes32 _h)
onlymanyowners(_h) returns (bool o_success)
{
require(state == States.InitialState);
state = States.InTransition;
//Actions
if (m_txs[_h].to != 0 || m_txs[_h].value != 0 || m_txs[_h].data.length != 0) {
address created;
if (m_txs[_h].to == 0) {
created = create(m_txs[_h].value, m_txs[_h].data);
} else {
if (!m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data))
throw;
}
MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data, created);
delete m_txs[_h];
return true;
}
//State change
state = States.InitialState;
}
function confirmAndCheck (bytes32 _operation)
internal returns (bool)
{
require(state == States.InitialState);
//State change
state = States.InTransition;
//Actions
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
if (ownerIndex == 0) return;
var pending = m_pending[_operation];
if (pending.yetNeeded == 0) {
pending.yetNeeded = m_required;
pending.ownersDone = 0;
pending.index = m_pendingIndex.length++;
m_pendingIndex[pending.index] = _operation;
}
uint ownerIndexBit = 2**ownerIndex;
if (pending.ownersDone & ownerIndexBit == 0) {
Confirmation(msg.sender, _operation);
if (pending.yetNeeded <= 1) {
delete m_pendingIndex[m_pending[_operation].index];
delete m_pending[_operation];
return true;
}
else
{
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
}
}
//State change
state = States.InitialState;
}
function create (uint _value, bytes _code)
internal returns (address o_addr)
{
require(state == States.InitialState);
//State change
state = States.InTransition;
//Actions
assembly {
o_addr := create(_value, add(_code, 0x20), mload(_code))
jumpi('', iszero(extcodesize(o_addr)))
}
//State change
state = States.InitialState;
}
function execute (address _to, uint _value, bytes _data)
external onlyowner returns (bytes32 o_hash)
{
require(state == States.InitialState);
state = States.InTransition;
//Actions
if ((_data.length == 0 && underLimit(_value)) || m_required == 1) {
address created;
if (_to == 0) {
created = create(_value, _data);
} else {
if (!_to.call.value(_value)(_data))
throw;
}
SingleTransact(msg.sender, _value, _to, _data, created);
} else {
o_hash = sha3(msg.data, block.number);
if (m_txs[o_hash].to == 0 && m_txs[o_hash].value == 0 && m_txs[o_hash].data.length == 0) {
m_txs[o_hash].to = _to;
m_txs[o_hash].value = _value;
m_txs[o_hash].data = _data;
}
if (!confirm(o_hash)) {
ConfirmationNeeded(o_hash, msg.sender, _value, _to, _data);
}
}
//State change
state = States.InitialState;
}
function getOwner (uint ownerIndex)
external constant returns (address)
{
require(state == States.InitialState);
//State change
state = States.InTransition;
//Actions
return address(m_owners[ownerIndex + 1]);
//State change
state = States.InitialState;
}
function hasConfirmed (bytes32 _operation, address _owner)
external constant returns (bool)
{
require(state == States.InitialState);
//State change
state = States.InTransition;
//Actions
var pending = m_pending[_operation];
uint ownerIndex = m_ownerIndex[uint(_owner)];
if (ownerIndex == 0) return false;
uint ownerIndexBit = 2**ownerIndex;
return !(pending.ownersDone & ownerIndexBit == 0);
//State change
state = States.InitialState;
}
function initDaylimit (uint _limit)
only_uninitialized
{
require(state == States.InitialState);
state = States.InTransition;
//Actions
m_dailyLimit = _limit;
m_lastDay = today();
//State change
state = States.InitialState;
}
function initMultiowned (address[] _owners, uint _required)
only_uninitialized
{
require(state == States.InitialState);
state = States.InTransition;
//Actions
m_numOwners = _owners.length + 1;
m_owners[1] = uint(msg.sender);
m_ownerIndex[uint(msg.sender)] = 1;
for (uint i = 0; i < _owners.length; ++i)
{
m_owners[2 + i] = uint(_owners[i]);
m_ownerIndex[uint(_owners[i])] = 2 + i;
}
m_required = _required;
//State change
state = States.InitialState;
}
function initWallet (address[] _owners, uint _required, uint _daylimit)
only_uninitialized
{
require(state == States.InitialState);
state = States.InTransition;
//Actions
initDaylimit(_daylimit);
initMultiowned(_owners, _required);
//State change
state = States.InitialState;
}
function isOwner (address _addr)
constant returns (bool)
{
require(state == States.InitialState);
//State change
state = States.InTransition;
//Actions
return m_ownerIndex[uint(_addr)] > 0;
//State change
state = States.InitialState;
}
function kill (address _to)
onlymanyowners(sha3(msg.data)) external
{
require(state == States.InitialState);
state = States.InTransition;
//Actions
suicide(_to);
//State change
state = States.InitialState;
}
function removeOwner (address _owner)
onlymanyowners(sha3(msg.data)) external
{
require(state == States.InitialState);
state = States.InTransition;
//Actions
uint ownerIndex = m_ownerIndex[uint(_owner)];
if (ownerIndex == 0) return;
if (m_required > m_numOwners - 1) return;
m_owners[ownerIndex] = 0;
m_ownerIndex[uint(_owner)] = 0;
clearPending();
reorganizeOwners();
OwnerRemoved(_owner);
//State change
state = States.InitialState;
}
function reorganizeOwners ()
private
{
require(state == States.InitialState);
//State change
state = States.InTransition;
//Actions
uint free = 1;
while (free < m_numOwners)
{
while (free < m_numOwners && m_owners[free] != 0) free++;
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
{
m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
}
}
//State change
state = States.InitialState;
}
function resetSpentToday ()
onlymanyowners(sha3(msg.data)) external
{
require(state == States.InitialState);
state = States.InTransition;
//Actions
m_spentToday = 0;
//State change
state = States.InitialState;
}
function revoke (bytes32 _operation)
external
{
require(state == States.InitialState);
//State change
state = States.InTransition;
//Actions
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
if (ownerIndex == 0) return;
uint ownerIndexBit = 2**ownerIndex;
var pending = m_pending[_operation];
if (pending.ownersDone & ownerIndexBit > 0) {
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
Revoke(msg.sender, _operation);
}
//State change
state = States.InitialState;
}
function setDailyLimit (uint _newLimit)
onlymanyowners(sha3(msg.data)) external
{
require(state == States.InitialState);
state = States.InTransition;
//Actions
m_dailyLimit = _newLimit;
//State change
state = States.InitialState;
}
function today ()
private constant returns (uint)
{
require(state == States.InitialState);
//State change
state = States.InTransition;
//Actions
return now / 1 days;
//State change
state = States.InitialState;
}
function underLimit (uint _value)
internal onlyowner returns (bool)
{
require(state == States.InitialState);
state = States.InTransition;
//Actions
if (today() > m_lastDay) {
m_spentToday = 0;
m_lastDay = today();
}
if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) {
m_spentToday += _value;
return true;
}
return false;
//State change
state = States.InitialState;
}
} | State changeActionsState change | function today ()
private constant returns (uint)
{
require(state == States.InitialState);
state = States.InTransition;
return now / 1 days;
state = States.InitialState;
}
| 5,457,093 |
./full_match/1/0xF66B8c3d9933a8f9362B4D30f2b918CC97E5a31E/sources/home/bugman/Projects/idle-governance/contracts/IdleController.sol | Checks caller is admin, or this contract is becoming the new implementation/ | function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
| 4,845,719 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import { PaymentSplitter, ERC721, Ownable, ProxyRegistry } from './OpenZeppelinDependencies.sol';
contract NothingBurger is ERC721, Ownable {
uint public constant START_PRICE = 0.1 ether;
uint public constant END_PRICE = 0.1 ether;
uint public startTime;
uint public immutable DURATION;
uint public immutable PRICE_PER_SECOND;
uint public constant MAX_SUPPLY = 10_000;
uint public constant MAX_MINT_AMOUNT = 10;
uint public ownerMintsRemaining = 0;
string private _contractURI = "";
string public baseURI = "";
address public immutable proxyRegistryAddress;
uint public constant decimals = 0;
uint public totalSupply = 0;
event Log(address indexed to, uint price, uint amount, uint cost, uint sent, uint change);
constructor(
uint durationInHours,
address _proxyRegistryAddress,
address _Burger
) ERC721('NothingBurger', 'BURGER')
{
DURATION = durationInHours * 60 * 60;
PRICE_PER_SECOND = (START_PRICE - END_PRICE) / (durationInHours * 60 * 60);
proxyRegistryAddress = _proxyRegistryAddress;
Burger = _Burger;
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator) public view override(ERC721) returns (bool) {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
// Whitelist OpenSea proxy contract for easy trading.
if (proxyRegistry.proxies(owner) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
function start() public onlyOwner {
require(startTime == 0, 'Already started');
startTime = block.timestamp;
}
/// @notice Reserved for owner to mint
function ownerMint(address to, uint amount) public onlyOwner {
uint mintsRemaining = ownerMintsRemaining;
/// @notice Owner mints cannot be minted after the maximum has been reached
require(mintsRemaining > 0, "Max owner mint limit reached");
if (amount > mintsRemaining){
amount = mintsRemaining;
}
uint currentTotalSupply = totalSupply;
_mintAmountTo(to, amount, currentTotalSupply);
ownerMintsRemaining = mintsRemaining - amount;
totalSupply = currentTotalSupply + amount;
}
/// @notice Batch owner minting
function batchOwnerMint(address[] calldata addresses, uint[] calldata amounts) public onlyOwner {
require(addresses.length == amounts.length, "batch length mismatch");
for (uint i=0; i<addresses.length; i++){
ownerMint(addresses[i], amounts[i]);
}
}
/// @notice Public mints
function mint(uint amount) public payable {
/// @notice public can mint a maximum quantity at a time.
require(amount <= MAX_MINT_AMOUNT, 'mint amount exceeds maximum');
uint currentTotalSupply = totalSupply;
/// @notice Cannot exceed maximum supply
require(currentTotalSupply+amount+ownerMintsRemaining <= MAX_SUPPLY, "Not enough mints remaining");
uint price = priceAtTime(block.timestamp);
uint cost = amount * price;
/// @notice public must send in correct funds
require(msg.value > 0 && msg.value >= cost, "Not enough value sent");
if (msg.value > cost){
uint change = msg.value - cost;
(bool success, ) = msg.sender.call{value: change}("");
require(success, "Change send unsuccessful");
emit Log(msg.sender, price, amount, cost, msg.value, change);
} else {
emit Log(msg.sender, price, amount, cost, msg.value, 0);
}
_mintAmountTo(msg.sender, amount, currentTotalSupply);
totalSupply = currentTotalSupply + amount;
}
function _mintAmountTo(address to, uint amount, uint startId) internal {
for (uint i = 1; i<=amount; i++){
_mint(to, startId+i);
}
}
function setBaseURI(string memory newBaseURI) external onlyOwner {
baseURI = newBaseURI;
}
function _baseURI() internal override view returns (string memory){
return baseURI;
}
function setContractURI(string memory newContractURI) external onlyOwner {
_contractURI = newContractURI;
}
function contractURI() external view returns (string memory){
return _contractURI;
}
function currentPrice() public view returns (uint){
return priceAtTime(block.timestamp);
}
function priceAtTime(uint time) public view returns (uint){
uint _startTime = startTime;
if (_startTime == 0 || time <= _startTime) return START_PRICE;
if (time >= _startTime + DURATION) return END_PRICE;
/// @notice Calculate the price decrease since start and subtract it from the starting price
return START_PRICE - (PRICE_PER_SECOND * (time - _startTime));
}
function endTime() public view returns (uint){
if (startTime == 0) return 0;
return startTime + DURATION;
}
function withdraw() public {
(bool success, ) = Burger.call{value: address(this).balance}("");
require(success, "Failed to send to Burger.");
}
function details() public view returns(uint _startTime, uint _endTime, uint _duration, uint _startPrice, uint _endPrice, uint _priceSecond, uint _priceAtBlock, uint _blockTimestamp){
return (startTime, endTime(), DURATION, START_PRICE, END_PRICE, PRICE_PER_SECOND, priceAtTime(block.timestamp), block.timestamp);
}
address public Burger;
} | Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings./ Whitelist OpenSea proxy contract for easy trading. | function isApprovedForAll(address owner, address operator) public view override(ERC721) returns (bool) {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (proxyRegistry.proxies(owner) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
| 12,158,974 |
./partial_match/1/0xF66C6fDBDD7d57dD14D23d0C8A4E58Cc4869bBfa/sources/ERC20Base.sol | 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
) internal virtual returns (bool) {
address owner_ = _msgSender();
_approve(owner_, spender, allowance(owner_, spender) + addedValue);
return true;
}
| 3,949,091 |
./full_match/5/0x76cba3fB1d80e1e98C60Ef0E970f0991ab2D39e1/sources/contracts/Router.sol | first try catch the swap remote | ) internal {
Pool pool = _getPool(_dstPoolId);
function swapRemote(
uint16 _srcChainId,
bytes memory _srcAddress,
uint256 _nonce,
uint256 _srcPoolId,
uint256 _dstPoolId,
uint256 _dstGasForCall,
address _to,
Pool.SwapObj memory _s,
bytes memory _payload
}
function _swapRemote(
uint16 _srcChainId,
bytes memory _srcAddress,
uint256 _nonce,
uint256 _srcPoolId,
uint256 _dstPoolId,
uint256 _dstGasForCall,
address _to,
Pool.SwapObj memory _s,
bytes memory _payload
try pool.swapRemote(_srcChainId, _srcPoolId, _to, _s) returns (uint256 amountLD) {
if (Address.isContract(_to) && _payload.length > 0) {
cachedSwapLookup[_srcChainId][_srcAddress][_nonce] = CachedSwap(pool.token(), amountLD, _to, _payload);
emit CachedSwapSaved(_srcChainId, _srcAddress, _nonce, pool.token(), amountLD, _to, _payload, reason);
}
}
revertLookup[_srcChainId][_srcAddress][_nonce] = abi.encode(
TYPE_SWAP_REMOTE_RETRY,
_srcPoolId,
_dstPoolId,
_dstGasForCall,
_to,
_s,
_payload
);
emit Revert(TYPE_SWAP_REMOTE_RETRY, _srcChainId, _srcAddress, _nonce);
function swapRemote(
uint16 _srcChainId,
bytes memory _srcAddress,
uint256 _nonce,
uint256 _srcPoolId,
uint256 _dstPoolId,
uint256 _dstGasForCall,
address _to,
Pool.SwapObj memory _s,
bytes memory _payload
}
function _swapRemote(
uint16 _srcChainId,
bytes memory _srcAddress,
uint256 _nonce,
uint256 _srcPoolId,
uint256 _dstPoolId,
uint256 _dstGasForCall,
address _to,
Pool.SwapObj memory _s,
bytes memory _payload
try pool.swapRemote(_srcChainId, _srcPoolId, _to, _s) returns (uint256 amountLD) {
if (Address.isContract(_to) && _payload.length > 0) {
cachedSwapLookup[_srcChainId][_srcAddress][_nonce] = CachedSwap(pool.token(), amountLD, _to, _payload);
emit CachedSwapSaved(_srcChainId, _srcAddress, _nonce, pool.token(), amountLD, _to, _payload, reason);
}
}
revertLookup[_srcChainId][_srcAddress][_nonce] = abi.encode(
TYPE_SWAP_REMOTE_RETRY,
_srcPoolId,
_dstPoolId,
_dstGasForCall,
_to,
_s,
_payload
);
emit Revert(TYPE_SWAP_REMOTE_RETRY, _srcChainId, _srcAddress, _nonce);
try IStargateReceiver(_to).sgReceive{gas: _dstGasForCall}(_srcChainId, _srcAddress, _nonce, pool.token(), amountLD, _payload) {
} catch (bytes memory reason) {
} catch {
}
| 11,615,531 |
./partial_match/1/0xc231EA5C3F934b3a9C502e50fDf66fAb5B179CD4/sources/Aptozeum.sol | See {ERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}; Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for `sender`'s tokens of at least `amount`./ | function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "APZ: transfer amount exceeds allowance"));
return true;
}
| 2,603,770 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import {Decimal} from "../external/Decimal.sol";
import {Constants} from "../Constants.sol";
import {OracleRef} from "./../refs/OracleRef.sol";
import {TribeRoles} from "./../core/TribeRoles.sol";
import {RateLimited} from "./../utils/RateLimited.sol";
import {IPCVDeposit, PCVDeposit} from "./../pcv/PCVDeposit.sol";
import {INonCustodialPSM} from "./INonCustodialPSM.sol";
import {GlobalRateLimitedMinter} from "./../utils/GlobalRateLimitedMinter.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
/// @notice Peg Stability Module that holds no funds.
/// On a mint, it transfers all proceeds to a PCV Deposit
/// When funds are needed for a redemption, they are simply pulled from the PCV Deposit
contract NonCustodialPSM is
OracleRef,
RateLimited,
ReentrancyGuard,
INonCustodialPSM
{
using Decimal for Decimal.D256;
using SafeCast for *;
using SafeERC20 for IERC20;
/// @notice the fee in basis points for selling an asset into VOLT
uint256 public override mintFeeBasisPoints;
/// @notice the fee in basis points for buying the asset for VOLT
uint256 public override redeemFeeBasisPoints;
/// @notice the PCV deposit target to deposit and withdraw from
IPCVDeposit public override pcvDeposit;
/// @notice the token this PSM will exchange for VOLT
/// Must be a stable token pegged to $1
IERC20 public immutable override underlyingToken;
/// @notice Rate Limited Minter contract that will be called when VOLT needs to be minted
GlobalRateLimitedMinter public override rateLimitedMinter;
/// @notice the max mint and redeem fee in basis points
/// Governance cannot change the maximum fee
uint256 public immutable override MAX_FEE = 300;
/// @notice boolean switch that indicates whether redeeming is paused
bool public redeemPaused;
/// @notice boolean switch that indicates whether minting is paused
bool public mintPaused;
/// @notice struct for passing constructor parameters related to OracleRef
struct OracleParams {
address coreAddress;
address oracleAddress;
address backupOracle;
int256 decimalsNormalizer;
}
/// @notice struct for passing constructor parameters related to MultiRateLimited
struct RateLimitedParams {
uint256 maxRateLimitPerSecond;
uint256 rateLimitPerSecond;
uint256 bufferCap;
}
/// @notice struct for passing constructor parameters related to the non custodial PSM
struct PSMParams {
uint256 mintFeeBasisPoints;
uint256 redeemFeeBasisPoints;
IERC20 underlyingToken;
IPCVDeposit pcvDeposit;
GlobalRateLimitedMinter rateLimitedMinter;
}
/// @notice construct the non custodial PSM. Structs are used to prevent stack too deep errors
/// @param params oracle ref constructor data
/// @param rateLimitedParams rate limited constructor data
/// @param psmParams non custodial PSM constructor data
constructor(
OracleParams memory params,
RateLimitedParams memory rateLimitedParams,
PSMParams memory psmParams
)
OracleRef(
params.coreAddress,
params.oracleAddress,
params.backupOracle,
params.decimalsNormalizer,
true /// hardcode doInvert to true to allow swaps to work correctly
)
/// rate limited replenishable passes false as the last param as there can be no partial actions
RateLimited(
rateLimitedParams.maxRateLimitPerSecond,
rateLimitedParams.rateLimitPerSecond,
rateLimitedParams.bufferCap,
false
)
{
underlyingToken = psmParams.underlyingToken;
_setGlobalRateLimitedMinter(psmParams.rateLimitedMinter);
_setMintFee(psmParams.mintFeeBasisPoints);
_setRedeemFee(psmParams.redeemFeeBasisPoints);
_setPCVDeposit(psmParams.pcvDeposit);
}
// ----------- Mint & Redeem pausing modifiers -----------
/// @notice modifier that allows execution when redemptions are not paused
modifier whileRedemptionsNotPaused() {
require(!redeemPaused, "PegStabilityModule: Redeem paused");
_;
}
/// @notice modifier that allows execution when minting is not paused
modifier whileMintingNotPaused() {
require(!mintPaused, "PegStabilityModule: Minting paused");
_;
}
// ----------- Governor & Guardian only pausing api -----------
/// @notice set secondary pausable methods to paused
function pauseRedeem() external onlyGuardianOrGovernor {
redeemPaused = true;
emit RedemptionsPaused(msg.sender);
}
/// @notice set secondary pausable methods to unpaused
function unpauseRedeem() external onlyGuardianOrGovernor {
redeemPaused = false;
emit RedemptionsUnpaused(msg.sender);
}
/// @notice set secondary pausable methods to paused
function pauseMint() external onlyGuardianOrGovernor {
mintPaused = true;
emit MintingPaused(msg.sender);
}
/// @notice set secondary pausable methods to unpaused
function unpauseMint() external onlyGuardianOrGovernor {
mintPaused = false;
emit MintingUnpaused(msg.sender);
}
// ----------- Governor, psm admin and parameter admin only state changing api -----------
/// @notice set the mint fee vs oracle price in basis point terms
/// @param newMintFeeBasisPoints the new fee in basis points for minting
function setMintFee(uint256 newMintFeeBasisPoints)
external
override
hasAnyOfTwoRoles(TribeRoles.GOVERNOR, TribeRoles.PARAMETER_ADMIN)
{
_setMintFee(newMintFeeBasisPoints);
}
/// @notice set the redemption fee vs oracle price in basis point terms
/// @param newRedeemFeeBasisPoints the new fee in basis points for redemptions
function setRedeemFee(uint256 newRedeemFeeBasisPoints)
external
override
hasAnyOfTwoRoles(TribeRoles.GOVERNOR, TribeRoles.PARAMETER_ADMIN)
{
_setRedeemFee(newRedeemFeeBasisPoints);
}
/// @notice set the target for sending all PCV
/// @param newTarget new PCV Deposit target for this PSM
function setPCVDeposit(IPCVDeposit newTarget)
external
override
hasAnyOfTwoRoles(TribeRoles.GOVERNOR, TribeRoles.PSM_ADMIN_ROLE)
{
_setPCVDeposit(newTarget);
}
/// @notice set the target to call for VOLT minting
/// @param newMinter new Global Rate Limited Minter for this PSM
function setGlobalRateLimitedMinter(GlobalRateLimitedMinter newMinter)
external
override
hasAnyOfTwoRoles(TribeRoles.GOVERNOR, TribeRoles.PSM_ADMIN_ROLE)
{
_setGlobalRateLimitedMinter(newMinter);
}
// ----------- PCV Controller only state changing api -----------
/// @notice withdraw ERC20 from the contract
/// @param token address of the ERC20 to send
/// @param to address destination of the ERC20
/// @param amount quantity of ERC20 to send
function withdrawERC20(
address token,
address to,
uint256 amount
) external override onlyPCVController {
IERC20(token).safeTransfer(to, amount);
emit WithdrawERC20(msg.sender, token, to, amount);
}
// ----------- Public State Changing API -----------
/// @notice function to redeem VOLT for an underlying asset
/// We do not burn VOLT; this allows the contract's balance of VOLT to be used before the buffer is used
/// In practice, this helps prevent artificial cycling of mint-burn cycles and prevents DOS attacks.
/// This function will deplete the buffer based on the amount of VOLT that is being redeemed.
/// @param to the destination address for proceeds
/// @param amountVoltIn the amount of VOLT to sell
/// @param minAmountOut the minimum amount out otherwise the TX will fail
function redeem(
address to,
uint256 amountVoltIn,
uint256 minAmountOut
)
external
virtual
override
nonReentrant
whenNotPaused
whileRedemptionsNotPaused
returns (uint256 amountOut)
{
_depleteBuffer(amountVoltIn); /// deplete buffer first to save gas on buffer exhaustion sad path
updateOracle();
amountOut = _getRedeemAmountOut(amountVoltIn);
require(
amountOut >= minAmountOut,
"PegStabilityModule: Redeem not enough out"
);
IERC20(volt()).safeTransferFrom(
msg.sender,
address(this),
amountVoltIn
);
pcvDeposit.withdraw(to, amountOut);
emit Redeem(to, amountVoltIn, amountOut);
}
/// @notice function to buy VOLT for an underlying asset that is pegged to $1
/// We first transfer any contract-owned VOLT, then mint the remaining if necessary
/// This function will replenish the buffer based on the amount of VOLT that is being sent out.
/// @param to the destination address for proceeds
/// @param amountIn the amount of external asset to sell to the PSM
/// @param minVoltAmountOut the minimum amount of VOLT out otherwise the TX will fail
function mint(
address to,
uint256 amountIn,
uint256 minVoltAmountOut
)
external
virtual
override
nonReentrant
whenNotPaused
whileMintingNotPaused
returns (uint256 amountVoltOut)
{
updateOracle();
amountVoltOut = _getMintAmountOut(amountIn);
require(
amountVoltOut >= minVoltAmountOut,
"PegStabilityModule: Mint not enough out"
);
underlyingToken.safeTransferFrom(
msg.sender,
address(pcvDeposit),
amountIn
);
pcvDeposit.deposit();
uint256 amountFeiToTransfer = Math.min(
volt().balanceOf(address(this)),
amountVoltOut
);
uint256 amountFeiToMint = amountVoltOut - amountFeiToTransfer;
if (amountFeiToTransfer != 0) {
IERC20(volt()).safeTransfer(to, amountFeiToTransfer);
}
if (amountFeiToMint != 0) {
rateLimitedMinter.mintVolt(to, amountFeiToMint);
}
_replenishBuffer(amountVoltOut);
emit Mint(to, amountIn, amountVoltOut);
}
// ----------- Public View-Only API ----------
/// @notice calculate the amount of VOLT out for a given `amountIn` of underlying
/// First get oracle price of token
/// Then figure out how many dollars that amount in is worth by multiplying price * amount.
/// ensure decimals are normalized if on underlying they are not 18
/// @param amountIn the amount of external asset to sell to the PSM
/// @return amountVoltOut the amount of VOLT received for the amountIn of external asset
function getMintAmountOut(uint256 amountIn)
public
view
override
returns (uint256 amountVoltOut)
{
amountVoltOut = _getMintAmountOut(amountIn);
}
/// @notice calculate the amount of underlying out for a given `amountVoltIn` of VOLT
/// First get oracle price of token
/// Then figure out how many dollars that amount in is worth by multiplying price * amount.
/// ensure decimals are normalized if on underlying they are not 18
/// @param amountVoltIn the amount of VOLT to redeem
/// @return amountTokenOut the amount of the external asset received in exchange for the amount of VOLT redeemed
function getRedeemAmountOut(uint256 amountVoltIn)
public
view
override
returns (uint256 amountTokenOut)
{
amountTokenOut = _getRedeemAmountOut(amountVoltIn);
}
/// @notice getter to return the maximum amount of VOLT that could be purchased at once
/// @return the maximum amount of VOLT available for purchase at once through this PSM
function getMaxMintAmountOut() external view override returns (uint256) {
return
volt().balanceOf(address(this)) +
rateLimitedMinter.individualBuffer(address(this));
}
// ----------- Internal Methods -----------
/// @notice helper function to get mint amount out based on current market prices
/// @dev will revert if price is outside of bounds and price bound PSM is being used
/// @param amountIn the amount of stable asset in
/// @return amountVoltOut the amount of VOLT received for the amountIn of stable assets
function _getMintAmountOut(uint256 amountIn)
internal
view
virtual
returns (uint256 amountVoltOut)
{
Decimal.D256 memory price = readOracle();
_validatePriceRange(price);
Decimal.D256 memory adjustedAmountIn = price.mul(amountIn);
amountVoltOut = adjustedAmountIn
.mul(Constants.BASIS_POINTS_GRANULARITY - mintFeeBasisPoints)
.div(Constants.BASIS_POINTS_GRANULARITY)
.asUint256();
}
/// @notice helper function to get redeem amount out based on current market prices
/// @dev will revert if price is outside of bounds and price bound PSM is being used
/// @param amountVoltIn the amount of VOLT to redeem
/// @return amountTokenOut the amount of the external asset received in exchange for the amount of VOLT redeemed
function _getRedeemAmountOut(uint256 amountVoltIn)
internal
view
virtual
returns (uint256 amountTokenOut)
{
Decimal.D256 memory price = readOracle();
_validatePriceRange(price);
/// get amount of VOLT being provided being redeemed after fees
Decimal.D256 memory adjustedAmountIn = Decimal.from(
(amountVoltIn *
(Constants.BASIS_POINTS_GRANULARITY - redeemFeeBasisPoints)) /
Constants.BASIS_POINTS_GRANULARITY
);
/// now turn the VOLT into the underlying token amounts
/// amount VOLT in / VOLT you receive for $1 = how much stable token to pay out
amountTokenOut = adjustedAmountIn.div(price).asUint256();
}
// ----------- Helper methods to change state -----------
/// @notice set the global rate limited minter this PSM calls to mint VOLT
/// @param newMinter the new minter contract that this PSM will reference
function _setGlobalRateLimitedMinter(GlobalRateLimitedMinter newMinter)
internal
{
require(
address(newMinter) != address(0),
"PegStabilityModule: Invalid new GlobalRateLimitedMinter"
);
GlobalRateLimitedMinter oldMinter = rateLimitedMinter;
rateLimitedMinter = newMinter;
emit GlobalRateLimitedMinterUpdate(oldMinter, newMinter);
}
/// @notice set the mint fee vs oracle price in basis point terms
/// @param newMintFeeBasisPoints the new fee for minting in basis points
function _setMintFee(uint256 newMintFeeBasisPoints) internal {
require(
newMintFeeBasisPoints <= MAX_FEE,
"PegStabilityModule: Mint fee exceeds max fee"
);
uint256 _oldMintFee = mintFeeBasisPoints;
mintFeeBasisPoints = newMintFeeBasisPoints;
emit MintFeeUpdate(_oldMintFee, newMintFeeBasisPoints);
}
/// @notice internal helper function to set the redemption fee
/// @param newRedeemFeeBasisPoints the new fee for redemptions in basis points
function _setRedeemFee(uint256 newRedeemFeeBasisPoints) internal {
require(
newRedeemFeeBasisPoints <= MAX_FEE,
"PegStabilityModule: Redeem fee exceeds max fee"
);
uint256 _oldRedeemFee = redeemFeeBasisPoints;
redeemFeeBasisPoints = newRedeemFeeBasisPoints;
emit RedeemFeeUpdate(_oldRedeemFee, newRedeemFeeBasisPoints);
}
/// @notice helper function to set the PCV deposit
/// @param newPCVDeposit the new PCV deposit that this PSM will pull assets from and deposit assets into
function _setPCVDeposit(IPCVDeposit newPCVDeposit) internal {
require(
address(newPCVDeposit) != address(0),
"PegStabilityModule: Invalid new PCVDeposit"
);
require(
newPCVDeposit.balanceReportedIn() == address(underlyingToken),
"PegStabilityModule: Underlying token mismatch"
);
IPCVDeposit oldTarget = pcvDeposit;
pcvDeposit = newPCVDeposit;
emit PCVDepositUpdate(oldTarget, newPCVDeposit);
}
// ----------- Hooks -----------
/// @notice overriden function in the price bound PSM
function _validatePriceRange(Decimal.D256 memory price)
internal
view
virtual
{}
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[email protected]>
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.8.4;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 private constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero() internal pure returns (D256 memory) {
return D256({value: 0});
}
function one() internal pure returns (D256 memory) {
return D256({value: BASE});
}
function from(uint256 a) internal pure returns (D256 memory) {
return D256({value: a.mul(BASE)});
}
function ratio(uint256 a, uint256 b) internal pure returns (D256 memory) {
return D256({value: getPartial(a, BASE, b)});
}
// ============ Self Functions ============
function add(D256 memory self, uint256 b)
internal
pure
returns (D256 memory)
{
return D256({value: self.value.add(b.mul(BASE))});
}
function sub(D256 memory self, uint256 b)
internal
pure
returns (D256 memory)
{
return D256({value: self.value.sub(b.mul(BASE))});
}
function sub(
D256 memory self,
uint256 b,
string memory reason
) internal pure returns (D256 memory) {
return D256({value: self.value.sub(b.mul(BASE), reason)});
}
function mul(D256 memory self, uint256 b)
internal
pure
returns (D256 memory)
{
return D256({value: self.value.mul(b)});
}
function div(D256 memory self, uint256 b)
internal
pure
returns (D256 memory)
{
return D256({value: self.value.div(b)});
}
function pow(D256 memory self, uint256 b)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({value: self.value});
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(D256 memory self, D256 memory b)
internal
pure
returns (D256 memory)
{
return D256({value: self.value.add(b.value)});
}
function sub(D256 memory self, D256 memory b)
internal
pure
returns (D256 memory)
{
return D256({value: self.value.sub(b.value)});
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
) internal pure returns (D256 memory) {
return D256({value: self.value.sub(b.value, reason)});
}
function mul(D256 memory self, D256 memory b)
internal
pure
returns (D256 memory)
{
return D256({value: getPartial(self.value, b.value, BASE)});
}
function div(D256 memory self, D256 memory b)
internal
pure
returns (D256 memory)
{
return D256({value: getPartial(self.value, BASE, b.value)});
}
function equals(D256 memory self, D256 memory b)
internal
pure
returns (bool)
{
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b)
internal
pure
returns (bool)
{
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b)
internal
pure
returns (bool)
{
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b)
internal
pure
returns (bool)
{
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b)
internal
pure
returns (bool)
{
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
) private pure returns (uint256) {
return target.mul(numerator).div(denominator);
}
function compareTo(D256 memory a, D256 memory b)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import {IWETH} from "@uniswap/v2-periphery/contracts/interfaces/IWETH.sol";
library Constants {
/// @notice the denominator for basis points granularity (10,000)
uint256 public constant BASIS_POINTS_GRANULARITY = 10_000;
/// @notice the denominator for basis points granularity (10,000) expressed as an int data type
int256 public constant BP_INT = int256(BASIS_POINTS_GRANULARITY);
uint256 public constant ONE_YEAR = 365.25 days;
int256 public constant ONE_YEAR_INT = int256(ONE_YEAR);
/// @notice WETH9 address
IWETH public constant WETH =
IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
/// @notice USD stand-in address
address public constant USD = 0x1111111111111111111111111111111111111111;
/// @notice Wei per ETH, i.e. 10**18
uint256 public constant ETH_GRANULARITY = 1e18;
/// @notice number of decimals in ETH, 18
uint256 public constant ETH_DECIMALS = 18;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IOracleRef.sol";
import "./CoreRef.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/// @title Reference to an Oracle
/// @author Fei Protocol
/// @notice defines some utilities around interacting with the referenced oracle
abstract contract OracleRef is IOracleRef, CoreRef {
using Decimal for Decimal.D256;
using SafeCast for int256;
/// @notice the oracle reference by the contract
IOracle public override oracle;
/// @notice the backup oracle reference by the contract
IOracle public override backupOracle;
/// @notice number of decimals to scale oracle price by, i.e. multiplying by 10^(decimalsNormalizer)
int256 public override decimalsNormalizer;
bool public override doInvert;
/// @notice OracleRef constructor
/// @param _core Fei Core to reference
/// @param _oracle oracle to reference
/// @param _backupOracle backup oracle to reference
/// @param _decimalsNormalizer number of decimals to normalize the oracle feed if necessary
/// @param _doInvert invert the oracle price if this flag is on
constructor(
address _core,
address _oracle,
address _backupOracle,
int256 _decimalsNormalizer,
bool _doInvert
) CoreRef(_core) {
_setOracle(_oracle);
if (_backupOracle != address(0) && _backupOracle != _oracle) {
_setBackupOracle(_backupOracle);
}
_setDoInvert(_doInvert);
_setDecimalsNormalizer(_decimalsNormalizer);
}
/// @notice sets the referenced oracle
/// @param newOracle the new oracle to reference
function setOracle(address newOracle) external override onlyGovernor {
_setOracle(newOracle);
}
/// @notice sets the flag for whether to invert or not
/// @param newDoInvert the new flag for whether to invert
function setDoInvert(bool newDoInvert) external override onlyGovernor {
_setDoInvert(newDoInvert);
}
/// @notice sets the new decimalsNormalizer
/// @param newDecimalsNormalizer the new decimalsNormalizer
function setDecimalsNormalizer(int256 newDecimalsNormalizer)
external
override
onlyGovernor
{
_setDecimalsNormalizer(newDecimalsNormalizer);
}
/// @notice sets the referenced backup oracle
/// @param newBackupOracle the new backup oracle to reference
function setBackupOracle(address newBackupOracle)
external
override
onlyGovernorOrAdmin
{
_setBackupOracle(newBackupOracle);
}
/// @notice invert a peg price
/// @param price the peg price to invert
/// @return the inverted peg as a Decimal
/// @dev the inverted peg would be X per FEI
function invert(Decimal.D256 memory price)
public
pure
override
returns (Decimal.D256 memory)
{
return Decimal.one().div(price);
}
/// @notice updates the referenced oracle
function updateOracle() public override {
oracle.update();
}
/// @notice the peg price of the referenced oracle
/// @return the peg as a Decimal
/// @dev the peg is defined as FEI per X with X being ETH, dollars, etc
function readOracle() public view override returns (Decimal.D256 memory) {
(Decimal.D256 memory _peg, bool valid) = oracle.read();
if (!valid && address(backupOracle) != address(0)) {
(_peg, valid) = backupOracle.read();
}
require(valid, "OracleRef: oracle invalid");
// Scale the oracle price by token decimals delta if necessary
uint256 scalingFactor;
if (decimalsNormalizer < 0) {
scalingFactor = 10**(-1 * decimalsNormalizer).toUint256();
_peg = _peg.div(scalingFactor);
} else {
scalingFactor = 10**decimalsNormalizer.toUint256();
_peg = _peg.mul(scalingFactor);
}
// Invert the oracle price if necessary
if (doInvert) {
_peg = invert(_peg);
}
return _peg;
}
function _setOracle(address newOracle) internal {
require(newOracle != address(0), "OracleRef: zero address");
address oldOracle = address(oracle);
oracle = IOracle(newOracle);
emit OracleUpdate(oldOracle, newOracle);
}
// Supports zero address if no backup
function _setBackupOracle(address newBackupOracle) internal {
address oldBackupOracle = address(backupOracle);
backupOracle = IOracle(newBackupOracle);
emit BackupOracleUpdate(oldBackupOracle, newBackupOracle);
}
function _setDoInvert(bool newDoInvert) internal {
bool oldDoInvert = doInvert;
doInvert = newDoInvert;
if (oldDoInvert != newDoInvert) {
_setDecimalsNormalizer(-1 * decimalsNormalizer);
}
emit InvertUpdate(oldDoInvert, newDoInvert);
}
function _setDecimalsNormalizer(int256 newDecimalsNormalizer) internal {
int256 oldDecimalsNormalizer = decimalsNormalizer;
decimalsNormalizer = newDecimalsNormalizer;
emit DecimalsNormalizerUpdate(
oldDecimalsNormalizer,
newDecimalsNormalizer
);
}
function _setDecimalsNormalizerFromToken(address token) internal {
int256 feiDecimals = 18;
int256 _decimalsNormalizer = feiDecimals -
int256(uint256(IERC20Metadata(token).decimals()));
if (doInvert) {
_decimalsNormalizer = -1 * _decimalsNormalizer;
}
_setDecimalsNormalizer(_decimalsNormalizer);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/**
@title Tribe DAO ACL Roles
@notice Holds a complete list of all roles which can be held by contracts inside Tribe DAO.
Roles are broken up into 3 categories:
* Major Roles - the most powerful roles in the Tribe DAO which should be carefully managed.
* Admin Roles - roles with management capability over critical functionality. Should only be held by automated or optimistic mechanisms
* Minor Roles - operational roles. May be held or managed by shorter optimistic timelocks or trusted multisigs.
*/
library TribeRoles {
/*///////////////////////////////////////////////////////////////
Major Roles
//////////////////////////////////////////////////////////////*/
/// @notice the ultimate role of Tribe. Controls all other roles and protocol functionality.
bytes32 internal constant GOVERNOR = keccak256("GOVERN_ROLE");
/// @notice the protector role of Tribe. Admin of pause, veto, revoke, and minor roles
bytes32 internal constant GUARDIAN = keccak256("GUARDIAN_ROLE");
/// @notice the role which can arbitrarily move PCV in any size from any contract
bytes32 internal constant PCV_CONTROLLER = keccak256("PCV_CONTROLLER_ROLE");
/// @notice can mint FEI arbitrarily
bytes32 internal constant MINTER = keccak256("MINTER_ROLE");
/*///////////////////////////////////////////////////////////////
Admin Roles
//////////////////////////////////////////////////////////////*/
/// @notice can manage the majority of Tribe protocol parameters. Sets boundaries for MINOR_PARAM_ROLE.
bytes32 internal constant PARAMETER_ADMIN = keccak256("PARAMETER_ADMIN");
/// @notice manages the Collateralization Oracle as well as other protocol oracles.
bytes32 internal constant ORACLE_ADMIN = keccak256("ORACLE_ADMIN_ROLE");
/// @notice manages TribalChief incentives and related functionality.
bytes32 internal constant TRIBAL_CHIEF_ADMIN =
keccak256("TRIBAL_CHIEF_ADMIN_ROLE");
/// @notice admin of PCVGuardian
bytes32 internal constant PCV_GUARDIAN_ADMIN =
keccak256("PCV_GUARDIAN_ADMIN_ROLE");
/// @notice admin of all Minor Roles
bytes32 internal constant MINOR_ROLE_ADMIN = keccak256("MINOR_ROLE_ADMIN");
/// @notice admin of the Fuse protocol
bytes32 internal constant FUSE_ADMIN = keccak256("FUSE_ADMIN");
/// @notice capable of vetoing DAO votes or optimistic timelocks
bytes32 internal constant VETO_ADMIN = keccak256("VETO_ADMIN");
/// @notice capable of setting FEI Minters within global rate limits and caps
bytes32 internal constant MINTER_ADMIN = keccak256("MINTER_ADMIN");
/// @notice manages the constituents of Optimistic Timelocks, including Proposers and Executors
bytes32 internal constant OPTIMISTIC_ADMIN = keccak256("OPTIMISTIC_ADMIN");
/*///////////////////////////////////////////////////////////////
Minor Roles
//////////////////////////////////////////////////////////////*/
/// @notice capable of poking existing LBP auctions to exchange tokens.
bytes32 internal constant LBP_SWAP_ROLE = keccak256("SWAP_ADMIN_ROLE");
/// @notice capable of engaging with Votium for voting incentives.
bytes32 internal constant VOTIUM_ROLE = keccak256("VOTIUM_ADMIN_ROLE");
/// @notice capable of changing parameters within non-critical ranges
bytes32 internal constant MINOR_PARAM_ROLE = keccak256("MINOR_PARAM_ROLE");
/// @notice capable of adding an address to multi rate limited
bytes32 internal constant ADD_MINTER_ROLE = keccak256("ADD_MINTER_ROLE");
/// @notice capable of changing PCV Deposit and Global Rate Limited Minter in the PSM
bytes32 internal constant PSM_ADMIN_ROLE = keccak256("PSM_ADMIN_ROLE");
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../refs/CoreRef.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
/// @title abstract contract for putting a rate limit on how fast a contract can perform an action e.g. Minting
/// @author Fei Protocol
abstract contract RateLimited is CoreRef {
/// @notice maximum rate limit per second governance can set for this contract
uint256 public immutable MAX_RATE_LIMIT_PER_SECOND;
/// @notice the rate per second for this contract
uint256 public rateLimitPerSecond;
/// @notice the last time the buffer was used by the contract
uint256 public lastBufferUsedTime;
/// @notice the cap of the buffer that can be used at once
uint256 public bufferCap;
/// @notice a flag for whether to allow partial actions to complete if the buffer is less than amount
bool public doPartialAction;
/// @notice the buffer at the timestamp of lastBufferUsedTime
uint256 public bufferStored;
event BufferUsed(uint256 amountUsed, uint256 bufferRemaining);
event BufferCapUpdate(uint256 oldBufferCap, uint256 newBufferCap);
event RateLimitPerSecondUpdate(
uint256 oldRateLimitPerSecond,
uint256 newRateLimitPerSecond
);
constructor(
uint256 _maxRateLimitPerSecond,
uint256 _rateLimitPerSecond,
uint256 _bufferCap,
bool _doPartialAction
) {
lastBufferUsedTime = block.timestamp;
_setBufferCap(_bufferCap);
bufferStored = _bufferCap;
require(
_rateLimitPerSecond <= _maxRateLimitPerSecond,
"RateLimited: rateLimitPerSecond too high"
);
_setRateLimitPerSecond(_rateLimitPerSecond);
MAX_RATE_LIMIT_PER_SECOND = _maxRateLimitPerSecond;
doPartialAction = _doPartialAction;
}
/// @notice set the rate limit per second
function setRateLimitPerSecond(uint256 newRateLimitPerSecond)
external
virtual
onlyGovernorOrAdmin
{
require(
newRateLimitPerSecond <= MAX_RATE_LIMIT_PER_SECOND,
"RateLimited: rateLimitPerSecond too high"
);
_updateBufferStored();
_setRateLimitPerSecond(newRateLimitPerSecond);
}
/// @notice set the buffer cap
function setBufferCap(uint256 newBufferCap)
external
virtual
onlyGovernorOrAdmin
{
_setBufferCap(newBufferCap);
}
/// @notice the amount of action used before hitting limit
/// @dev replenishes at rateLimitPerSecond per second up to bufferCap
function buffer() public view returns (uint256) {
uint256 elapsed = block.timestamp - lastBufferUsedTime;
return
Math.min(bufferStored + (rateLimitPerSecond * elapsed), bufferCap);
}
/**
@notice the method that enforces the rate limit. Decreases buffer by "amount".
If buffer is <= amount either
1. Does a partial mint by the amount remaining in the buffer or
2. Reverts
Depending on whether doPartialAction is true or false
*/
function _depleteBuffer(uint256 amount) internal virtual returns (uint256) {
uint256 newBuffer = buffer();
uint256 usedAmount = amount;
if (doPartialAction && usedAmount > newBuffer) {
usedAmount = newBuffer;
}
require(newBuffer != 0, "RateLimited: no rate limit buffer");
require(usedAmount <= newBuffer, "RateLimited: rate limit hit");
bufferStored = newBuffer - usedAmount;
lastBufferUsedTime = block.timestamp;
emit BufferUsed(usedAmount, bufferStored);
return usedAmount;
}
/// @notice function to replenish buffer
/// @param amount to increase buffer by if under buffer cap
function _replenishBuffer(uint256 amount) internal {
uint256 newBuffer = buffer();
uint256 _bufferCap = bufferCap; /// gas opti, save an SLOAD
/// cannot replenish any further if already at buffer cap
if (newBuffer == _bufferCap) {
return;
}
/// ensure that bufferStored cannot be gt buffer cap
bufferStored = Math.min(newBuffer + amount, _bufferCap);
}
function _setRateLimitPerSecond(uint256 newRateLimitPerSecond) internal {
uint256 oldRateLimitPerSecond = rateLimitPerSecond;
rateLimitPerSecond = newRateLimitPerSecond;
emit RateLimitPerSecondUpdate(
oldRateLimitPerSecond,
newRateLimitPerSecond
);
}
function _setBufferCap(uint256 newBufferCap) internal {
_updateBufferStored();
uint256 oldBufferCap = bufferCap;
bufferCap = newBufferCap;
emit BufferCapUpdate(oldBufferCap, newBufferCap);
}
function _resetBuffer() internal {
bufferStored = bufferCap;
}
function _updateBufferStored() internal {
bufferStored = buffer();
lastBufferUsedTime = block.timestamp;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../refs/CoreRef.sol";
import "./IPCVDeposit.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @title abstract contract for withdrawing ERC-20 tokens using a PCV Controller
/// @author Fei Protocol
abstract contract PCVDeposit is IPCVDeposit, CoreRef {
using SafeERC20 for IERC20;
/// @notice withdraw ERC20 from the contract
/// @param token address of the ERC20 to send
/// @param to address destination of the ERC20
/// @param amount quantity of ERC20 to send
function withdrawERC20(
address token,
address to,
uint256 amount
) public virtual override onlyPCVController {
_withdrawERC20(token, to, amount);
}
function _withdrawERC20(
address token,
address to,
uint256 amount
) internal {
IERC20(token).safeTransfer(to, amount);
emit WithdrawERC20(msg.sender, token, to, amount);
}
/// @notice withdraw ETH from the contract
/// @param to address to send ETH
/// @param amountOut amount of ETH to send
function withdrawETH(address payable to, uint256 amountOut)
external
virtual
override
onlyPCVController
{
Address.sendValue(to, amountOut);
emit WithdrawETH(msg.sender, to, amountOut);
}
function balance() public view virtual override returns (uint256);
function resistantBalanceAndVolt()
public
view
virtual
override
returns (uint256, uint256)
{
return (balance(), 0);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IPCVDeposit} from "../pcv/IPCVDeposit.sol";
import {GlobalRateLimitedMinter} from "../utils/GlobalRateLimitedMinter.sol";
/**
* @title Fei Peg Stability Module
* @author Fei Protocol
* @notice The Fei PSM is a contract which pulls reserve assets from PCV Deposits in order to exchange FEI at $1 of underlying assets with a fee.
* `mint()` - buy FEI for $1 of underlying tokens
* `redeem()` - sell FEI back for $1 of the same
*
*
* The contract is a
* OracleRef - to determine price of underlying, and
* RateLimitedReplenishable - to stop infinite mints and related DOS issues
*
* Inspired by MakerDAO PSM, code written without reference
*/
interface INonCustodialPSM {
// ----------- Public State Changing API -----------
/// @notice mint `amountFeiOut` FEI to address `to` for `amountIn` underlying tokens
/// @dev see getMintAmountOut() to pre-calculate amount out
function mint(
address to,
uint256 amountIn,
uint256 minAmountOut
) external returns (uint256 amountFeiOut);
/// @notice redeem `amountFeiIn` FEI for `amountOut` underlying tokens and send to address `to`
/// @dev see getRedeemAmountOut() to pre-calculate amount out
function redeem(
address to,
uint256 amountFeiIn,
uint256 minAmountOut
) external returns (uint256 amountOut);
// ----------- Governor or Admin Only State Changing API -----------
/// @notice set the mint fee vs oracle price in basis point terms
function setMintFee(uint256 newMintFeeBasisPoints) external;
/// @notice set the redemption fee vs oracle price in basis point terms
function setRedeemFee(uint256 newRedeemFeeBasisPoints) external;
/// @notice set the target for sending surplus reserves
function setPCVDeposit(IPCVDeposit newTarget) external;
/// @notice set the target to call for FEI minting
function setGlobalRateLimitedMinter(GlobalRateLimitedMinter newMinter)
external;
/// @notice withdraw ERC20 from the contract
function withdrawERC20(
address token,
address to,
uint256 amount
) external;
// ----------- Getters -----------
/// @notice calculate the amount of FEI out for a given `amountIn` of underlying
function getMintAmountOut(uint256 amountIn)
external
view
returns (uint256 amountFeiOut);
/// @notice calculate the amount of underlying out for a given `amountFeiIn` of FEI
function getRedeemAmountOut(uint256 amountFeiIn)
external
view
returns (uint256 amountOut);
/// @notice the maximum mint amount out
function getMaxMintAmountOut() external view returns (uint256);
/// @notice the mint fee vs oracle price in basis point terms
function mintFeeBasisPoints() external view returns (uint256);
/// @notice the redemption fee vs oracle price in basis point terms
function redeemFeeBasisPoints() external view returns (uint256);
/// @notice the underlying token exchanged for FEI
function underlyingToken() external view returns (IERC20);
/// @notice the PCV deposit target to deposit and withdraw from
function pcvDeposit() external view returns (IPCVDeposit);
/// @notice Rate Limited Minter contract that will be called when FEI needs to be minted
function rateLimitedMinter()
external
view
returns (GlobalRateLimitedMinter);
/// @notice the max mint and redeem fee in basis points
function MAX_FEE() external view returns (uint256);
// ----------- Events -----------
/// @notice event emitted when a new max fee is set
event MaxFeeUpdate(uint256 oldMaxFee, uint256 newMaxFee);
/// @notice event emitted when a new mint fee is set
event MintFeeUpdate(uint256 oldMintFee, uint256 newMintFee);
/// @notice event emitted when a new redeem fee is set
event RedeemFeeUpdate(uint256 oldRedeemFee, uint256 newRedeemFee);
/// @notice event emitted when reservesThreshold is updated
event ReservesThresholdUpdate(
uint256 oldReservesThreshold,
uint256 newReservesThreshold
);
/// @notice event emitted when surplus target is updated
event PCVDepositUpdate(IPCVDeposit oldTarget, IPCVDeposit newTarget);
/// @notice event emitted upon a redemption
event Redeem(address to, uint256 amountFeiIn, uint256 amountAssetOut);
/// @notice event emitted when fei gets minted
event Mint(address to, uint256 amountIn, uint256 amountFeiOut);
/// @notice event emitted when ERC20 tokens get withdrawn
event WithdrawERC20(
address indexed _caller,
address indexed _token,
address indexed _to,
uint256 _amount
);
/// @notice event emitted when global rate limited minter is updated
event GlobalRateLimitedMinterUpdate(
GlobalRateLimitedMinter oldMinter,
GlobalRateLimitedMinter newMinter
);
/// @notice event that is emitted when redemptions are paused
event RedemptionsPaused(address account);
/// @notice event that is emitted when redemptions are unpaused
event RedemptionsUnpaused(address account);
/// @notice event that is emitted when minting is paused
event MintingPaused(address account);
/// @notice event that is emitted when minting is unpaused
event MintingUnpaused(address account);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import {MultiRateLimited} from "./MultiRateLimited.sol";
import {IGlobalRateLimitedMinter} from "./IGlobalRateLimitedMinter.sol";
import {CoreRef} from "./../refs/CoreRef.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
/// @notice global contract to handle rate limited minting of VOLT on a global level
/// allows whitelisted minters to call in and specify the address to mint VOLT to within
/// that contract's limits
contract GlobalRateLimitedMinter is MultiRateLimited, IGlobalRateLimitedMinter {
/// @param coreAddress address of the core contract
/// @param _globalMaxRateLimitPerSecond maximum amount of VOLT that can replenish per second ever, this amount cannot be changed by governance
/// @param _perAddressRateLimitMaximum maximum rate limit per second per address
/// @param _maxRateLimitPerSecondPerAddress maximum rate limit per second per address in multi rate limited
/// @param _maxBufferCap maximum buffer cap in multi rate limited contract
/// @param _globalBufferCap maximum global buffer cap
constructor(
address coreAddress,
uint256 _globalMaxRateLimitPerSecond,
uint256 _perAddressRateLimitMaximum,
uint256 _maxRateLimitPerSecondPerAddress,
uint256 _maxBufferCap,
uint256 _globalBufferCap
)
CoreRef(coreAddress)
MultiRateLimited(
_globalMaxRateLimitPerSecond,
_perAddressRateLimitMaximum,
_maxRateLimitPerSecondPerAddress,
_maxBufferCap,
_globalBufferCap
)
{}
/// @notice mint VOLT to the target address and deplete the buffer
/// pausable and depletes the msg.sender's buffer
/// @param to the recipient address of the minted VOLT
/// @param amount the amount of VOLT to mint
function mintVolt(address to, uint256 amount)
external
virtual
override
whenNotPaused
{
_depleteIndividualBuffer(msg.sender, amount);
_mintVolt(to, amount);
}
/// @notice mint VOLT to the target address and deplete the whole rate limited
/// minter's buffer, pausable and completely depletes the msg.sender's buffer
/// @param to the recipient address of the minted VOLT
/// mints all VOLT that msg.sender has in the buffer
function mintMaxAllowableVolt(address to)
external
virtual
override
whenNotPaused
{
uint256 amount = Math.min(individualBuffer(msg.sender), buffer());
_depleteIndividualBuffer(msg.sender, amount);
_mintVolt(to, amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// 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 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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;
}
}
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../oracle/IOracle.sol";
/// @title OracleRef interface
/// @author Fei Protocol
interface IOracleRef {
// ----------- Events -----------
event OracleUpdate(address indexed oldOracle, address indexed newOracle);
event InvertUpdate(bool oldDoInvert, bool newDoInvert);
event DecimalsNormalizerUpdate(
int256 oldDecimalsNormalizer,
int256 newDecimalsNormalizer
);
event BackupOracleUpdate(
address indexed oldBackupOracle,
address indexed newBackupOracle
);
// ----------- State changing API -----------
function updateOracle() external;
// ----------- Governor only state changing API -----------
function setOracle(address newOracle) external;
function setBackupOracle(address newBackupOracle) external;
function setDecimalsNormalizer(int256 newDecimalsNormalizer) external;
function setDoInvert(bool newDoInvert) external;
// ----------- Getters -----------
function oracle() external view returns (IOracle);
function backupOracle() external view returns (IOracle);
function doInvert() external view returns (bool);
function decimalsNormalizer() external view returns (int256);
function readOracle() external view returns (Decimal.D256 memory);
function invert(Decimal.D256 calldata price)
external
pure
returns (Decimal.D256 memory);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./ICoreRef.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
/// @title A Reference to Core
/// @author Fei Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable {
ICore private immutable _core;
IVolt private immutable _volt;
IERC20 private immutable _vcon;
/// @notice a role used with a subset of governor permissions for this contract only
bytes32 public override CONTRACT_ADMIN_ROLE;
constructor(address coreAddress) {
_core = ICore(coreAddress);
_volt = ICore(coreAddress).volt();
_vcon = ICore(coreAddress).vcon();
_setContractAdminRole(ICore(coreAddress).GOVERN_ROLE());
}
function _initialize() internal {} // no-op for backward compatibility
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernorOrAdmin() {
require(
_core.isGovernor(msg.sender) || isContractAdmin(msg.sender),
"CoreRef: Caller is not a governor or contract admin"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) || _core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier onlyGovernorOrGuardianOrAdmin() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender) ||
isContractAdmin(msg.sender),
"CoreRef: Caller is not governor or guardian or admin"
);
_;
}
// Named onlyTribeRole to prevent collision with OZ onlyRole modifier
modifier onlyTribeRole(bytes32 role) {
require(_core.hasRole(role, msg.sender), "UNAUTHORIZED");
_;
}
// Modifiers to allow any combination of roles
modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) {
require(
_core.hasRole(role1, msg.sender) ||
_core.hasRole(role2, msg.sender),
"UNAUTHORIZED"
);
_;
}
modifier hasAnyOfThreeRoles(
bytes32 role1,
bytes32 role2,
bytes32 role3
) {
require(
_core.hasRole(role1, msg.sender) ||
_core.hasRole(role2, msg.sender) ||
_core.hasRole(role3, msg.sender),
"UNAUTHORIZED"
);
_;
}
modifier hasAnyOfFourRoles(
bytes32 role1,
bytes32 role2,
bytes32 role3,
bytes32 role4
) {
require(
_core.hasRole(role1, msg.sender) ||
_core.hasRole(role2, msg.sender) ||
_core.hasRole(role3, msg.sender) ||
_core.hasRole(role4, msg.sender),
"UNAUTHORIZED"
);
_;
}
modifier hasAnyOfFiveRoles(
bytes32 role1,
bytes32 role2,
bytes32 role3,
bytes32 role4,
bytes32 role5
) {
require(
_core.hasRole(role1, msg.sender) ||
_core.hasRole(role2, msg.sender) ||
_core.hasRole(role3, msg.sender) ||
_core.hasRole(role4, msg.sender) ||
_core.hasRole(role5, msg.sender),
"UNAUTHORIZED"
);
_;
}
modifier onlyVolt() {
require(msg.sender == address(_volt), "CoreRef: Caller is not VOLT");
_;
}
/// @notice sets a new admin role for this contract
function setContractAdminRole(bytes32 newContractAdminRole)
external
override
onlyGovernor
{
_setContractAdminRole(newContractAdminRole);
}
/// @notice returns whether a given address has the admin role for this contract
function isContractAdmin(address _admin)
public
view
override
returns (bool)
{
return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Fei contract referenced by Core
/// @return IFei implementation address
function volt() public view override returns (IVolt) {
return _volt;
}
/// @notice address of the Tribe contract referenced by Core
/// @return IERC20 implementation address
function vcon() public view override returns (IERC20) {
return _vcon;
}
/// @notice volt balance of contract
/// @return volt amount held
function voltBalance() public view override returns (uint256) {
return _volt.balanceOf(address(this));
}
/// @notice vcon balance of contract
/// @return vcon amount held
function vconBalance() public view override returns (uint256) {
return _vcon.balanceOf(address(this));
}
function _burnVoltHeld() internal {
_volt.burn(voltBalance());
}
function _mintVolt(address to, uint256 amount) internal virtual {
if (amount != 0) {
_volt.mint(to, amount);
}
}
function _setContractAdminRole(bytes32 newContractAdminRole) internal {
bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE;
CONTRACT_ADMIN_ROLE = newContractAdminRole;
emit ContractAdminRoleUpdate(
oldContractAdminRole,
newContractAdminRole
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../external/Decimal.sol";
/// @title generic oracle interface for Fei Protocol
/// @author Fei Protocol
interface IOracle {
// ----------- Events -----------
event Update(uint256 _peg);
// ----------- State changing API -----------
function update() external;
// ----------- Getters -----------
function read() external view returns (Decimal.D256 memory, bool);
function isOutdated() external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../core/ICore.sol";
/// @title CoreRef interface
/// @author Fei Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed oldCore, address indexed newCore);
event ContractAdminRoleUpdate(
bytes32 indexed oldContractAdminRole,
bytes32 indexed newContractAdminRole
);
// ----------- Governor only state changing api -----------
function setContractAdminRole(bytes32 newContractAdminRole) external;
// ----------- Governor or Guardian only state changing api -----------
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function volt() external view returns (IVolt);
function vcon() external view returns (IERC20);
function voltBalance() external view returns (uint256);
function vconBalance() external view returns (uint256);
function CONTRACT_ADMIN_ROLE() external view returns (bytes32);
function isContractAdmin(address admin) external view returns (bool);
}
// 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-3.0-or-later
pragma solidity ^0.8.4;
import {IPermissions} from "./IPermissions.sol";
import {IVolt, IERC20} from "../volt/IVolt.sol";
/// @title Core Interface
/// @author Fei Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event VoltUpdate(IERC20 indexed _volt);
event VconUpdate(IERC20 indexed _vcon);
// ----------- Getters -----------
function volt() external view returns (IVolt);
function vcon() external view returns (IERC20);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./IPermissionsRead.sol";
/// @title Permissions interface
/// @author Fei Protocol
interface IPermissions is IAccessControl, IPermissionsRead {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function GUARDIAN_ROLE() external view returns (bytes32);
function GOVERN_ROLE() external view returns (bytes32);
function BURNER_ROLE() external view returns (bytes32);
function MINTER_ROLE() external view returns (bytes32);
function PCV_CONTROLLER_ROLE() external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title FEI stablecoin interface
/// @author Fei Protocol
interface IVolt is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title Permissions Read interface
/// @author Fei Protocol
interface IPermissionsRead {
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// 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: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IPCVDepositBalances.sol";
/// @title a PCV Deposit interface
/// @author Fei Protocol
interface IPCVDeposit is IPCVDepositBalances {
// ----------- Events -----------
event Deposit(address indexed _from, uint256 _amount);
event Withdrawal(
address indexed _caller,
address indexed _to,
uint256 _amount
);
event WithdrawERC20(
address indexed _caller,
address indexed _token,
address indexed _to,
uint256 _amount
);
event WithdrawETH(
address indexed _caller,
address indexed _to,
uint256 _amount
);
// ----------- State changing api -----------
function deposit() external;
// ----------- PCV Controller only state changing api -----------
function withdraw(address to, uint256 amount) external;
function withdrawERC20(
address token,
address to,
uint256 amount
) external;
function withdrawETH(address payable to, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title a PCV Deposit interface for only balance getters
/// @author Fei Protocol
interface IPCVDepositBalances {
// ----------- Getters -----------
/// @notice gets the effective balance of "balanceReportedIn" token if the deposit were fully withdrawn
function balance() external view returns (uint256);
/// @notice gets the token address in which this deposit returns its balance
function balanceReportedIn() external view returns (address);
/// @notice gets the resistant token balance and protocol owned fei of this deposit
function resistantBalanceAndVolt() external view returns (uint256, 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: GPL-3.0-or-later
pragma solidity ^0.8.4;
import {CoreRef} from "../refs/CoreRef.sol";
import {TribeRoles} from "./../core/TribeRoles.sol";
import {RateLimited} from "./RateLimited.sol";
import {IMultiRateLimited} from "./IMultiRateLimited.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
/// @title abstract contract for putting a rate limit on how fast an address can perform an action e.g. Minting
/// there are two buffers, one buffer which is each individual addresses's current buffer,
/// and then there is a global buffer which is the buffer that each individual address must respect as well
/// @author Elliot Friedman, Fei Protocol
/// this contract was made abstract so that other contracts that already construct an instance of CoreRef
/// do not collide with this one
abstract contract MultiRateLimited is RateLimited, IMultiRateLimited {
using SafeCast for *;
/// @notice the struct containing all information per rate limited address
struct RateLimitData {
uint32 lastBufferUsedTime;
uint112 bufferCap;
uint112 bufferStored;
uint112 rateLimitPerSecond;
}
/// @notice rate limited address information
mapping(address => RateLimitData) public rateLimitPerAddress;
/// @notice max rate limit per second allowable by non governor per contract
uint256 public individualMaxRateLimitPerSecond;
/// @notice max buffer cap allowable by non governor per contract
uint256 public individualMaxBufferCap;
/// @param _maxRateLimitPerSecond maximum amount of fei that can replenish per second ever, this amount cannot be changed by governance
/// @param _rateLimitPerSecond maximum rate limit per second per address
/// @param _individualMaxRateLimitPerSecond maximum rate limit per second per address in multi rate limited
/// @param _individualMaxBufferCap maximum buffer cap in multi rate limited
/// @param _globalBufferCap maximum global buffer cap
constructor(
uint256 _maxRateLimitPerSecond,
uint256 _rateLimitPerSecond,
uint256 _individualMaxRateLimitPerSecond,
uint256 _individualMaxBufferCap,
uint256 _globalBufferCap
)
RateLimited(
_maxRateLimitPerSecond,
_rateLimitPerSecond,
_globalBufferCap,
false
)
{
require(
_individualMaxBufferCap < _globalBufferCap,
"MultiRateLimited: max buffer cap invalid"
);
individualMaxRateLimitPerSecond = _individualMaxRateLimitPerSecond;
individualMaxBufferCap = _individualMaxBufferCap;
}
modifier addressIsRegistered(address rateLimitedAddress) {
require(
rateLimitPerAddress[rateLimitedAddress].lastBufferUsedTime != 0,
"MultiRateLimited: rate limit address does not exist"
);
_;
}
// ----------- Governor and Admin only state changing api -----------
/// @notice update the ADD_MINTER_ROLE rate limit per second
/// @param newRateLimitPerSecond new maximum rate limit per second for add minter role
function updateMaxRateLimitPerSecond(uint256 newRateLimitPerSecond)
external
virtual
override
onlyGovernor
{
require(
newRateLimitPerSecond <= MAX_RATE_LIMIT_PER_SECOND,
"MultiRateLimited: exceeds global max rate limit per second"
);
uint256 oldMaxRateLimitPerSecond = individualMaxRateLimitPerSecond;
individualMaxRateLimitPerSecond = newRateLimitPerSecond;
emit MultiMaxRateLimitPerSecondUpdate(
oldMaxRateLimitPerSecond,
newRateLimitPerSecond
);
}
/// @notice update the ADD_MINTER_ROLE max buffer cap
/// @param newBufferCap new buffer cap for ADD_MINTER_ROLE added addresses
function updateMaxBufferCap(uint256 newBufferCap)
external
virtual
override
onlyGovernor
{
require(
newBufferCap <= bufferCap,
"MultiRateLimited: exceeds global buffer cap"
);
uint256 oldBufferCap = individualMaxBufferCap;
individualMaxBufferCap = newBufferCap;
emit MultiBufferCapUpdate(oldBufferCap, newBufferCap);
}
/// @notice add an authorized rateLimitedAddress contract
/// @param rateLimitedAddress the new address to add as a rateLimitedAddress
/// @param _rateLimitPerSecond the rate limit per second for this rateLimitedAddress
/// @param _bufferCap the buffer cap for this rateLimitedAddress
function addAddress(
address rateLimitedAddress,
uint112 _rateLimitPerSecond,
uint112 _bufferCap
) external virtual override onlyGovernor {
_addAddress(rateLimitedAddress, _rateLimitPerSecond, _bufferCap);
}
/// @notice add an authorized rateLimitedAddress contract
/// @param rateLimitedAddress the address whose buffer and rate limit per second will be set
/// @param _rateLimitPerSecond the new rate limit per second for this rateLimitedAddress
/// @param _bufferCap the new buffer cap for this rateLimitedAddress
function updateAddress(
address rateLimitedAddress,
uint112 _rateLimitPerSecond,
uint112 _bufferCap
)
external
virtual
override
addressIsRegistered(rateLimitedAddress)
hasAnyOfTwoRoles(TribeRoles.ADD_MINTER_ROLE, TribeRoles.GOVERNOR)
{
if (core().hasRole(TribeRoles.ADD_MINTER_ROLE, msg.sender)) {
require(
_rateLimitPerSecond <= individualMaxRateLimitPerSecond,
"MultiRateLimited: rate limit per second exceeds non governor allowable amount"
);
require(
_bufferCap <= individualMaxBufferCap,
"MultiRateLimited: max buffer cap exceeds non governor allowable amount"
);
}
require(
_bufferCap <= bufferCap,
"MultiRateLimited: buffercap too high"
);
_updateAddress(rateLimitedAddress, _rateLimitPerSecond, _bufferCap);
}
/// @notice add an authorized rateLimitedAddress contract
/// @param rateLimitedAddress the new address to add as a rateLimitedAddress
/// gives the newly added contract the maximum allowable rate limit per second and buffer cap
function addAddressWithCaps(address rateLimitedAddress)
external
virtual
override
onlyTribeRole(TribeRoles.ADD_MINTER_ROLE)
{
_addAddress(
rateLimitedAddress,
uint112(individualMaxRateLimitPerSecond),
uint112(individualMaxBufferCap)
);
}
/// @notice remove an authorized rateLimitedAddress contract
/// @param rateLimitedAddress the address to remove from the whitelist of addresses
function removeAddress(address rateLimitedAddress)
external
virtual
override
addressIsRegistered(rateLimitedAddress)
onlyGuardianOrGovernor
{
uint256 oldRateLimitPerSecond = rateLimitPerAddress[rateLimitedAddress]
.rateLimitPerSecond;
delete rateLimitPerAddress[rateLimitedAddress];
emit IndividualRateLimitPerSecondUpdate(
rateLimitedAddress,
oldRateLimitPerSecond,
0
);
}
// ----------- Getters -----------
/// @notice the amount of action used before hitting limit
/// @dev replenishes at rateLimitPerSecond per second up to bufferCap
/// @param rateLimitedAddress the address whose buffer will be returned
/// @return the buffer of the specified rate limited address
function individualBuffer(address rateLimitedAddress)
public
view
override
returns (uint112)
{
RateLimitData memory rateLimitData = rateLimitPerAddress[
rateLimitedAddress
];
uint256 elapsed = block.timestamp - rateLimitData.lastBufferUsedTime;
return
uint112(
Math.min(
rateLimitData.bufferStored +
(rateLimitData.rateLimitPerSecond * elapsed),
rateLimitData.bufferCap
)
);
}
/// @notice the rate per second for each address
function getRateLimitPerSecond(address limiter)
external
view
override
returns (uint256)
{
return rateLimitPerAddress[limiter].rateLimitPerSecond;
}
/// @notice the last time the buffer was used by each address
function getLastBufferUsedTime(address limiter)
external
view
override
returns (uint256)
{
return rateLimitPerAddress[limiter].lastBufferUsedTime;
}
/// @notice the cap of the buffer that can be used at once
function getBufferCap(address limiter)
external
view
override
returns (uint256)
{
return rateLimitPerAddress[limiter].bufferCap;
}
// ----------- Helper Methods -----------
function _updateAddress(
address rateLimitedAddress,
uint112 _rateLimitPerSecond,
uint112 _bufferCap
) internal {
RateLimitData storage rateLimitData = rateLimitPerAddress[
rateLimitedAddress
];
require(
rateLimitData.lastBufferUsedTime != 0,
"MultiRateLimited: rate limit address does not exist"
);
require(
_rateLimitPerSecond <= MAX_RATE_LIMIT_PER_SECOND,
"MultiRateLimited: rateLimitPerSecond too high"
);
uint112 oldRateLimitPerSecond = rateLimitData.rateLimitPerSecond;
rateLimitData.lastBufferUsedTime = block.timestamp.toUint32();
rateLimitData.bufferCap = _bufferCap;
rateLimitData.rateLimitPerSecond = _rateLimitPerSecond;
rateLimitData.bufferStored = _bufferCap;
emit IndividualRateLimitPerSecondUpdate(
rateLimitedAddress,
oldRateLimitPerSecond,
_rateLimitPerSecond
);
}
/// @param rateLimitedAddress the new address to add as a rateLimitedAddress
/// @param _rateLimitPerSecond the rate limit per second for this rateLimitedAddress
/// @param _bufferCap the buffer cap for this rateLimitedAddress
function _addAddress(
address rateLimitedAddress,
uint112 _rateLimitPerSecond,
uint112 _bufferCap
) internal {
require(
_bufferCap <= bufferCap,
"MultiRateLimited: new buffercap too high"
);
require(
rateLimitPerAddress[rateLimitedAddress].lastBufferUsedTime == 0,
"MultiRateLimited: address already added"
);
require(
_rateLimitPerSecond <= MAX_RATE_LIMIT_PER_SECOND,
"MultiRateLimited: rateLimitPerSecond too high"
);
RateLimitData memory rateLimitData = RateLimitData({
lastBufferUsedTime: block.timestamp.toUint32(),
bufferCap: _bufferCap,
rateLimitPerSecond: _rateLimitPerSecond,
bufferStored: _bufferCap
});
rateLimitPerAddress[rateLimitedAddress] = rateLimitData;
emit IndividualRateLimitPerSecondUpdate(
rateLimitedAddress,
0,
_rateLimitPerSecond
);
}
/// @notice the method that enforces the rate limit. Decreases buffer by "amount".
/// @param rateLimitedAddress the address whose buffer will be depleted
/// @param amount the amount to remove from the rateLimitedAddress's buffer
function _depleteIndividualBuffer(
address rateLimitedAddress,
uint256 amount
) internal returns (uint256) {
_depleteBuffer(amount);
uint256 newBuffer = individualBuffer(rateLimitedAddress);
require(newBuffer != 0, "MultiRateLimited: no rate limit buffer");
require(amount <= newBuffer, "MultiRateLimited: rate limit hit");
rateLimitPerAddress[rateLimitedAddress].bufferStored = uint112(
newBuffer - amount
);
rateLimitPerAddress[rateLimitedAddress].lastBufferUsedTime = block
.timestamp
.toUint32();
emit IndividualBufferUsed(
rateLimitedAddress,
amount,
newBuffer - amount
);
return amount;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IMultiRateLimited.sol";
/// @notice global contract to handle rate limited minting of VOLT on a global level
/// allows whitelisted minters to call in and specify the address to mint VOLT to within
/// the calling contract's limits
interface IGlobalRateLimitedMinter is IMultiRateLimited {
/// @notice function that all VOLT minters call to mint VOLT
/// pausable and depletes the msg.sender's buffer
/// @param to the recipient address of the minted VOLT
/// @param amount the amount of VOLT to mint
function mintVolt(address to, uint256 amount) external;
/// @notice mint VOLT to the target address and deplete the whole rate limited
/// minter's buffer, pausable and completely depletes the msg.sender's buffer
/// @param to the recipient address of the minted VOLT
/// mints all VOLT that msg.sender has in the buffer
function mintMaxAllowableVolt(address to) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title interface for putting a rate limit on how fast a contract can perform an action, e.g. Minting
/// @author Fei Protocol
interface IMultiRateLimited {
// ----------- Events -----------
/// @notice emitted when a buffer is eaten into
event IndividualBufferUsed(
address rateLimitedAddress,
uint256 amountUsed,
uint256 bufferRemaining
);
/// @notice emitted when rate limit is updated
event IndividualRateLimitPerSecondUpdate(
address rateLimitedAddress,
uint256 oldRateLimitPerSecond,
uint256 newRateLimitPerSecond
);
/// @notice emitted when the non gov buffer cap max is updated
event MultiBufferCapUpdate(uint256 oldBufferCap, uint256 newBufferCap);
/// @notice emitted when the non gov buffer rate limit per second max is updated
event MultiMaxRateLimitPerSecondUpdate(
uint256 oldMaxRateLimitPerSecond,
uint256 newMaxRateLimitPerSecond
);
// ----------- View API -----------
/// @notice the rate per second for each address
function getRateLimitPerSecond(address) external view returns (uint256);
/// @notice the last time the buffer was used by each address
function getLastBufferUsedTime(address) external view returns (uint256);
/// @notice the cap of the buffer that can be used at once
function getBufferCap(address) external view returns (uint256);
/// @notice the amount of action that can be used before hitting limit
/// @dev replenishes at rateLimitPerSecond per second up to bufferCap
function individualBuffer(address) external view returns (uint112);
// ----------- Governance State Changing API -----------
/// @notice update the non gov max rate limit per second
function updateMaxRateLimitPerSecond(uint256 newMaxRateLimitPerSecond)
external;
/// @notice update the non gov max buffer cap
function updateMaxBufferCap(uint256 newBufferCap) external;
/// @notice add an authorized contract, its per second replenishment and buffer set to the non governor caps
function addAddressWithCaps(address) external;
/// @notice add an authorized contract, its per second replenishment and buffer
function addAddress(
address,
uint112,
uint112
) external;
/// @notice update an authorized contract
function updateAddress(
address,
uint112,
uint112
) external;
/// @notice remove an authorized contract
function removeAddress(address) external;
} | internal helper function to set the redemption fee newRedeemFeeBasisPoints the new fee for redemptions in basis points | function _setRedeemFee(uint256 newRedeemFeeBasisPoints) internal {
require(
newRedeemFeeBasisPoints <= MAX_FEE,
"PegStabilityModule: Redeem fee exceeds max fee"
);
uint256 _oldRedeemFee = redeemFeeBasisPoints;
redeemFeeBasisPoints = newRedeemFeeBasisPoints;
emit RedeemFeeUpdate(_oldRedeemFee, newRedeemFeeBasisPoints);
}
| 6,870,172 |
./full_match/1/0xB0A1Cd3b31A8e3bbBaba15fEDdB88ABD932a677d/sources/contracts/mixins/shared/SendValueWithFallbackWithdraw.sol | Removing old unused variables in an upgrade safe way. Emitted when escrowed funds are withdrawn to FETH. user The account which has withdrawn ETH. amount The amount of ETH which has been withdrawn./ Attempt to send a user or contract ETH. If it fails store the amount owned for later withdrawal in FETH. This may fail when sending ETH to a contract that is non-receivable or exceeds the gas limit specified./ Store the funds that failed to send for the user in the FETH token | function _sendValueWithFallbackWithdraw(address payable user, uint256 amount, uint256 gasLimit) internal {
if (amount == 0) {
return;
}
if (!success) {
emit WithdrawalToFETH(user, amount);
}
}
| 8,357,220 |
// SPDX-License-Identifier: Unlicensed
pragma solidity >=0.7.0 <0.8.0;
pragma abicoder v2;
import "../Utils/CloneFactory.sol";
import "./EIP1167_BiconomyQuestion.sol";
/***
* @dev Make sure that msg.sender is changes to msgSender() in accordance with Biconomy Mexa SDK
*/
contract EIP1167_BiconomyFactory is CloneFactory
{
address public immutable admin; /// @dev May change this to array/mapping to allow bunch of admins.
address public implementation; /// @dev Market implementation contract.
address[] public questionAddresses;
event newQuestionCreated(address indexed _question, string _description, uint256 _bettingEndTime, uint256 _eventEndTime, uint256 _blockNumber);
/// @dev To check if a market is valid or not.
modifier validParams(string memory _question, string[] memory _options, uint256 _bettingEndTime, uint256 _eventEndTime)
{
require(_options.length > 1 && _options.length < 6, "Number of options must lie between 2 and 5 (inclusive)");
require(keccak256(abi.encodePacked(_question)) != keccak256(""), "Empty questions not allowed");
for(uint8 i = 0; i < (_options.length); ++i)
{
require(keccak256(abi.encodePacked(_options[i])) != keccak256(""), "Empty options not allowed");
}
/// @dev This condition states that gap between market creation time and betting end time must be grater than a day.
require((_bettingEndTime > block.timestamp + 1 days) && (_eventEndTime > block.timestamp + 1 days), "Timelimit(s) not valid");
require(_bettingEndTime <= _eventEndTime, "Event end time can't be smaller than the betting end time !");
_;
}
/// @dev Sets the original Market contract during deployment of MarketFactory contract
constructor(address _implementation)
{
admin = msg.sender;
implementation = _implementation;
}
/// @dev Set's implementation (Market) contract
function setImplementation(address _implementation) external
{
require(msg.sender == admin, "Only admin can change the implementation contract");
implementation = _implementation;
}
function createQuestion(string calldata _description, string[] calldata _options, uint256 _bettingEndTime, uint256 _eventEndTime) external validParams(_description, _options, _bettingEndTime, _eventEndTime)
{
address newQuestion = createClone(implementation);
EIP1167_BiconomyQuestion(newQuestion).init(admin, _description, _options, _bettingEndTime, _eventEndTime);
questionAddresses.push(address(newQuestion));
emit newQuestionCreated(address(newQuestion), _description, _bettingEndTime, _eventEndTime, block.number);
}
/// @dev This function is not covered by Biconomy. Hence, may not be required to call this function from factory contract.
function stake(address payable _market, uint256 _optionId) external payable
{
/// @dev Check if this works.
EIP1167_BiconomyQuestion(_market).stake(msg.sender, _optionId).send(msg.value, "Transaction failed from factory contract !");
}
function changeStake(address _market, uint256 _fromOptionId, uint256 _toOptionId, uint256 _amount) external
{
///@dev Add msgSender()
EIP1167_BiconomyQuestion(_market).changeStake(msgSender(), _fromOptionId, _toOptionId, _amount);
}
/// @dev This function is not covered by Biconomy. Hence, may not be required to call this function from factory contract.
function stakeForReporting(address payable _market, uint256 _optionId) external
{
EIP1167_BiconomyQuestion(_market).stake(_optionId).send(msg.value, "Transaction failed from factory contract !");
require(_market.send(msg.value), "Transaction failed from factory contract !");
}
function redeemStakedPayout(address _market) external
{
EIP1167_BiconomyQuestion(_market).redeemStakedPayout(msgSender());
}
function redeemReportingPayout(address _market) external
{
EIP1167_BiconomyQuestion(_market).redeemReportingPayout(msgSender());
}
/// @dev Is this function necessary as the addresses are public in the first place.
function giveQuestionAddresses() public view returns (address[] memory)
{
return questionAddresses;
}
} | Is this function necessary as the addresses are public in the first place. | function giveQuestionAddresses() public view returns (address[] memory)
{
return questionAddresses;
}
| 928,165 |
pragma solidity ^0.4.19;
contract TicTacToe {
//X player code
uint8 constant X = 1;
//O player code
uint8 constant O = 2;
//empty board field symbol
uint8 constant EMPTY = 0;
//player entry fee in wei (winner reward is 2 x ENTRY_FEE)
uint256 public constant ENTRY_FEE = 1;
// Waiting - after the game is created, only one player is int the game
// Ready - both players are int the game, game is progressing
// Finished - after we announce the winner player
enum GameStatus { Waiting, Ready, Finished }
// Game object
struct Game {
//only serves as label for waiting room
string name;
//current game status
GameStatus status;
//represents 3x3 board
//at the beginning each field should be EMPTY
uint8[9] board;
//symbol of player which should make his move
uint8 turn;
//provides info about which player(address) has what symbol
mapping(uint8 => address) players;
}
//all contract games
Game[] public games;
//should only be broadcasted when new game is created
event GameCreated(uint256 gameId, string name, uint8 turn);
//should be broadcasted after each move(except for last)
event BoardState(uint256 indexed gameId, uint8[9] board, uint8 turn);
//should be broadcasted if somebody has won or is draw
//winner address should be 0 if it's a draw
event GameResult(uint256 indexed gameId, address winner);
modifier inGame(uint256 _gameId) {
require(games.length > _gameId);
Game storage game = games[_gameId];
require(game.status == GameStatus.Ready);
require(game.players[X] == msg.sender || game.players[O] == msg.sender);
_;
}
//Utility method for frontend so it can retrieve all games from array
//should return number of elements in game array
function getGamesCount() public view returns(uint256 count) {
return games.length;
}
//Utility method for frontend so it can retrieve latest game board
// should return board array
function getBoard(uint256 _gameId) external view returns (uint8[9]) {
Game memory game = games[_gameId];
return game.board;
}
//Method that returns player address associated with given symbol
function getPlayerAddress(uint256 _gameId, uint8 _symbol) public view returns(address player) {
require(games.length > _gameId);
Game storage game = games[_gameId];
return game.players[_symbol];
}
//first player creates game giving only the game label
//method should check if there is enough of ether sent
//caller should be set as player X and set to be first
//broadcasts GameCreated event
function createGame(string _name) payable external {
require(msg.value == 1);
Game memory game = Game(_name, GameStatus.Waiting, getEmptyBoard(), X);
uint256 id = games.push(game) - 1;
games[id].players[X] = msg.sender;
GameCreated(id, _name, game.turn);
}
//second player joins game by giving game id
//method should check if enough ether is sent
//method should set caller as player O
//method should change game status to ready
//method should broadcast BoardState event to notify player X
function joinGame(uint256 _gameId) payable external {
require(msg.value == 1);
require(games.length > _gameId);
Game storage game = games[_gameId];
game.players[O] = msg.sender;
game.status = GameStatus.Ready;
BoardState(_gameId, game.board, game.turn);
}
//method for making current player move
//if it's a winning move or draw, broadcast GameResult event and returns
//in case of winning move, 2xENTRY_FEE should be transferred to winner address
//in case of draw, each player should get his ENTRY_FEE back
//updates next player in game object
//saves current player symbol on board at given position
//broadcasts BoardState event
function move(uint256 _gameId, uint8 position) external inGame(_gameId) {
Game storage game = games[_gameId];
require(game.board[position] == EMPTY);
require(game.players[game.turn] == msg.sender);
game.board[position] = game.turn;
if (winnerExists(game.board, game.turn)) {
address winner = game.players[game.turn];
winner.transfer(2 * ENTRY_FEE);
game.status = GameStatus.Finished;
GameResult(_gameId, winner);
return;
}
if (isDraw(game.board)) {
game.status = GameStatus.Finished;
game.players[X].transfer(ENTRY_FEE);
game.players[O].transfer(ENTRY_FEE);
GameResult(_gameId, 0);
}
game.turn = getNextPlayer(game.turn);
BoardState(_gameId, game.board, game.turn);
}
//utility function to help you with determine if given symbol has won
//true if given symbol has won, false otherwise
function winnerExists(uint8[9] board, uint8 symbol) private pure returns (bool finished) {
uint8 horizontal_count = 0;
uint8 vertical_count = 0;
uint8 right_to_left_count = 0;
uint8 left_to_right_count = 0;
uint8 board_size = 3;
for (uint8 x = 0; x < board_size; x++) {
horizontal_count = vertical_count = 0;
for (uint8 y = 0; y < board_size; y++) {
// "0,1,2", "3,4,5", "6,7,8"
if (board[x * board_size + y] == symbol) {
horizontal_count++;
}
if (board[y * board_size + x] == symbol) {
vertical_count++;
}
}
// Check horizontal and vertical combination
if (horizontal_count == board_size || vertical_count == board_size) {
return true;
}
// diagonal "0,4,8"
if (board[x * board_size + x] == symbol) {
right_to_left_count++;
}
// diagonal "2,4,6"
if (board[(board_size - 1) * (x+1)] == symbol) {
left_to_right_count++;
}
}
if (right_to_left_count == board_size || left_to_right_count == board_size) {
return true;
}
return false;
}
function isDraw(uint8[9] board) private pure returns (bool draw) {
for (uint8 x = 0; x < board.length; x++) {
if (board[x] == EMPTY) {
return false;
}
}
return true;
}
function getEmptyBoard() private pure returns (uint8[9]) {
return [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY];
}
function getNextPlayer(uint8 _turn) private pure returns (uint8) {
if (_turn == X) {
return O;
} else {
return X;
}
}
}
| method for making current player moveif it's a winning move or draw, broadcast GameResult event and returnsin case of winning move, 2xENTRY_FEE should be transferred to winner addressin case of draw, each player should get his ENTRY_FEE backupdates next player in game objectsaves current player symbol on board at given positionbroadcasts BoardState event | function move(uint256 _gameId, uint8 position) external inGame(_gameId) {
Game storage game = games[_gameId];
require(game.board[position] == EMPTY);
require(game.players[game.turn] == msg.sender);
game.board[position] = game.turn;
if (winnerExists(game.board, game.turn)) {
address winner = game.players[game.turn];
winner.transfer(2 * ENTRY_FEE);
game.status = GameStatus.Finished;
GameResult(_gameId, winner);
return;
}
if (isDraw(game.board)) {
game.status = GameStatus.Finished;
game.players[X].transfer(ENTRY_FEE);
game.players[O].transfer(ENTRY_FEE);
GameResult(_gameId, 0);
}
game.turn = getNextPlayer(game.turn);
BoardState(_gameId, game.board, game.turn);
}
| 12,904,366 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./utils/HasNoEther.sol";
contract JamMarketplace is HasNoEther, Pausable, ReentrancyGuard {
using SafeMath for uint256;
// Represents an auction on an NFT
struct Auction {
address seller;
uint128 price;
address erc20Address; // erc20Address, address(0) if place a price with (wei)
address nftAddress;
uint256 tokenId;
uint64 startedAt;
}
uint256 withdrawDuration = 14 days;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// The total amount of royalty cut which cannot be reclaimed by the owner of the contract
mapping(address => uint256) private _totalRoyaltyCut;
// Map from an NFT to its corresponding auction.
mapping(address => mapping(uint256 => Auction)) public auctions;
// mapping royaltyCut amount for each (address, erc20Address) pair,
// erc20Address = address(0) mean it value is wei
mapping(address => mapping(address => uint256)) private royaltyCuts;
mapping(address => mapping(address => uint256)) private lastWithdraws;
event AuctionCreated(
address indexed nftAddress,
uint256 indexed tokenId,
uint256 price,
address seller,
address erc20Address
);
event AuctionSuccessful(
address indexed nftAddress,
uint256 indexed tokenId,
uint256 price,
address winner
);
event AuctionCancelled(address indexed nftAddress, uint256 indexed tokenId);
// Modifiers to check that inputs can be safely stored with a certain
// number of bits. We use constants and multiple modifiers to save gas.
modifier canBeStoredWith64Bits(uint256 _value) {
require(
_value <= type(uint64).max,
"JamMarketplace: cannot be stored with 64 bits"
);
_;
}
modifier canBeStoredWith128Bits(uint256 _value) {
require(
_value < type(uint128).max,
"JamMarketplace: cannot be stored with 128 bits"
);
_;
}
constructor(uint256 _ownerCut) {
require(
_ownerCut <= 10000,
"JamMarketplace: owner cut cannot exceed 100%"
);
ownerCut = _ownerCut;
}
function updateOwnerCut(uint256 _ownerCut) public onlyOwner {
require(
_ownerCut <= 10000,
"JamMarketplace: owner cut cannot exceed 100%"
);
ownerCut = _ownerCut;
}
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return (_price * ownerCut) / 10000;
}
function _isOnAuction(Auction storage _auction)
internal
view
returns (bool)
{
return (_auction.startedAt > 0);
}
function _getNftContract(address _nftAddress)
internal
pure
returns (IERC721)
{
IERC721 candidateContract = IERC721(_nftAddress);
return candidateContract;
}
function _supportIERC2981(address _nftAddress)
internal
view
returns (bool)
{
bool success;
success = ERC165Checker.supportsERC165(_nftAddress);
if (success) {
success = IERC165(_nftAddress).supportsInterface(
type(IERC2981).interfaceId
);
}
return success;
}
function _getERC2981(address _nftAddress) internal pure returns (IERC2981) {
IERC2981 candidateContract = IERC2981(_nftAddress);
return candidateContract;
}
function _getERC20Contract(address _erc20Address)
internal
pure
returns (IERC20)
{
IERC20 candidateContract = IERC20(_erc20Address);
return candidateContract;
}
function _owns(
address _nftAddress,
address _claimant,
uint256 _tokenId
) internal view returns (bool) {
IERC721 _nftContract = _getNftContract(_nftAddress);
return (_nftContract.ownerOf(_tokenId) == _claimant);
}
function _transfer(
address _nftAddress,
address _receiver,
uint256 _tokenId
) internal {
IERC721 _nftContract = _getNftContract(_nftAddress);
// It will throw if transfer fails
_nftContract.transferFrom(address(this), _receiver, _tokenId);
}
function _addAuction(
address _nftAddress,
uint256 _tokenId,
Auction memory _auction,
address _seller
) internal {
auctions[_nftAddress][_tokenId] = _auction;
emit AuctionCreated(
_nftAddress,
_tokenId,
uint256(_auction.price),
_seller,
address(_auction.erc20Address)
);
}
function _escrow(
address _nftAddress,
address _owner,
uint256 _tokenId
) internal {
IERC721 _nftContract = _getNftContract(_nftAddress);
// It will throw if transfer fails
_nftContract.transferFrom(_owner, address(this), _tokenId);
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(address _nftAddress, uint256 _tokenId) internal {
delete auctions[_nftAddress][_tokenId];
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(
address _nftAddress,
uint256 _tokenId,
address _seller
) internal {
_removeAuction(_nftAddress, _tokenId);
_transfer(_nftAddress, _seller, _tokenId);
emit AuctionCancelled(_nftAddress, _tokenId);
}
function getAuction(address _nftAddress, uint256 _tokenId)
external
view
returns (
address seller,
uint256 price,
address erc20Address,
uint256 startedAt
)
{
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
return (
_auction.seller,
_auction.price,
_auction.erc20Address,
_auction.startedAt
);
}
function getWithdrawInfo(address[] memory _contractAddress)
external
view
returns (
address[] memory contractAddress,
uint256[] memory balances,
uint256[] memory lastWithdraw
)
{
uint256[] memory _balances = new uint256[](_contractAddress.length);
uint256[] memory _lastWithdraw = new uint256[](_contractAddress.length);
for (uint256 i = 0; i < _contractAddress.length; i += 1) {
address ad = _contractAddress[i];
uint256 balance = royaltyCuts[msg.sender][ad];
_balances[i] = balance;
uint256 lw = lastWithdraws[msg.sender][ad];
_lastWithdraw[i] = lw;
}
return (_contractAddress, balances, lastWithdraw);
}
/// @dev Create an auction.
/// @param _nftAddress - Address of the NFT.
/// @param _tokenId - ID of the NFT.
/// @param _price - Price of erc20 address.
/// @param _erc20Address - Address of price need to be list on.
function createAuction(
address _nftAddress,
uint256 _tokenId,
uint256 _price,
address _erc20Address
) external whenNotPaused canBeStoredWith128Bits(_price) {
address _seller = msg.sender;
require(
_owns(_nftAddress, _seller, _tokenId),
"JamMarketplace: only owner can create auction"
);
_escrow(_nftAddress, _seller, _tokenId);
Auction memory _auction = Auction(
_seller,
uint128(_price),
_erc20Address,
_nftAddress,
_tokenId,
uint64(block.timestamp)
);
_addAuction(_nftAddress, _tokenId, _auction, _seller);
}
/// @dev Cancels an auction.
/// @param _nftAddress - Address of the NFT.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuction(address _nftAddress, uint256 _tokenId) external {
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
require(
msg.sender == _auction.seller,
"JamMarketplace: only seller can cancel auction"
);
_cancelAuction(_nftAddress, _tokenId, _auction.seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _nftAddress - Address of the NFT.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(address _nftAddress, uint256 _tokenId)
external
whenPaused
onlyOwner
{
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
_cancelAuction(_nftAddress, _tokenId, _auction.seller);
}
function buy(address _nftAddress, uint256 _tokenId)
external
payable
whenNotPaused
{
Auction memory auction = auctions[_nftAddress][_tokenId];
require(
auction.erc20Address == address(0),
"JamMarketplace: cannot buy this item with native token"
);
// _bid will throw if the bid or funds transfer fails
_buy(_nftAddress, _tokenId, msg.value);
_transfer(_nftAddress, msg.sender, _tokenId);
}
function buyByERC20(
address _nftAddress,
uint256 _tokenId,
uint256 _maxPrice
) external whenNotPaused nonReentrant {
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(
_auction.erc20Address != address(0),
"JamMarketplace: can only be paid with native token"
);
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
uint256 _price = _auction.price;
require(_price <= _maxPrice, "JamMarketplace: item price is too high");
uint256 tokenId = _tokenId;
address _erc20Address = _auction.erc20Address;
IERC20 erc20Contract = _getERC20Contract(_erc20Address);
uint256 _allowance = erc20Contract.allowance(msg.sender, address(this));
require(_allowance >= _price, "JamMarketplace: not enough allowance");
address _seller = _auction.seller;
uint256 _auctioneerCut = _computeCut(_price);
uint256 _sellerProceeds = _price - _auctioneerCut;
bool success = erc20Contract.transferFrom(
msg.sender,
address(this),
_price
);
require(success, "JamMarketplace: not enough balance");
erc20Contract.transfer(_seller, _sellerProceeds);
if (_supportIERC2981(_nftAddress)) {
IERC2981 royaltyContract = _getERC2981(_nftAddress);
(address firstOwner, uint256 amount) = royaltyContract.royaltyInfo(
tokenId,
_auctioneerCut
);
require(
amount < _auctioneerCut,
"JamMarketplace: royalty amount must be less than auctioneer cut"
);
_totalRoyaltyCut[_erc20Address] = _totalRoyaltyCut[_erc20Address]
.add(amount);
royaltyCuts[firstOwner][_erc20Address] = royaltyCuts[firstOwner][
_erc20Address
].add(amount);
}
_transfer(_nftAddress, msg.sender, _tokenId);
_removeAuction(_nftAddress, _tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _buy(
address _nftAddress,
uint256 _tokenId,
uint256 _bidAmount
) internal returns (uint256) {
// Get a reference to the auction struct
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
uint256 _price = _auction.price;
require(
_bidAmount >= _price,
"JamMarketplace: bid amount cannot be less than price"
);
address _seller = _auction.seller;
_removeAuction(_nftAddress, _tokenId);
if (_price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 _auctioneerCut = _computeCut(_price);
uint256 _sellerProceeds = _price - _auctioneerCut;
payable(_seller).transfer(_sellerProceeds);
if (_supportIERC2981(_nftAddress)) {
IERC2981 royaltyContract = _getERC2981(_nftAddress);
(address firstOwner, uint256 amount) = royaltyContract
.royaltyInfo(_tokenId, _auctioneerCut);
require(
amount < _auctioneerCut,
"JamMarketplace: royalty amount must be less than auctioneer cut"
);
_totalRoyaltyCut[address(0)] = _totalRoyaltyCut[address(0)].add(
amount
);
royaltyCuts[firstOwner][address(0)] = royaltyCuts[firstOwner][
address(0)
].add(amount);
}
}
if (_bidAmount > _price) {
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 _bidExcess = _bidAmount - _price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
payable(msg.sender).transfer(_bidExcess);
}
// Tell the world!
emit AuctionSuccessful(_nftAddress, _tokenId, _price, msg.sender);
return _price;
}
function withdraw(address _erc20Address) public {
uint256 lastWithdraw = lastWithdraws[msg.sender][_erc20Address];
require(
lastWithdraw + withdrawDuration <= block.timestamp,
"JamMarketplace: only withdraw after 14 days before previous withdraw"
);
uint256 royaltyCut = royaltyCuts[msg.sender][_erc20Address];
require(royaltyCut > 0, "JamMarketplace: no royalty cut to withdraw");
royaltyCuts[msg.sender][_erc20Address] = 0;
_totalRoyaltyCut[_erc20Address] = _totalRoyaltyCut[_erc20Address].sub(
royaltyCut
);
lastWithdraws[msg.sender][_erc20Address] = block.timestamp;
if (_erc20Address == address(0)) {
payable(msg.sender).transfer(royaltyCut);
} else {
IERC20 erc20Contract = _getERC20Contract(_erc20Address);
bool success = erc20Contract.transfer(msg.sender, royaltyCut);
require(success, "JamMarketplace: transfer failed");
}
}
// function reclaimEther() external override onlyOwner {
// (bool success, ) = payable(owner()).call{
// value: address(this).balance.sub(_totalRoyaltyCut[address(0)])
// }("");
// require(success, "JamMarketplace: reclaim Ether failed");
// }
function reclaimERC20(address _erc20Address) external onlyOwner {
IERC20 erc20Contract = _getERC20Contract(_erc20Address);
erc20Contract.transfer(
owner(),
erc20Contract.balanceOf(address(this)).sub(
_totalRoyaltyCut[_erc20Address]
)
);
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}
| Computes the price and transfers winnings. Does NOT transfer ownership of token. Get a reference to the auction struct Calculate the auctioneer's cut. (NOTE: _computeCut() is guaranteed to return a value <= price, so this subtraction can't go negative.) Calculate any excess funds included with the bid. If the excess is anything worth worrying about, transfer it back to bidder. NOTE: We checked above that the bid amount is greater than or equal to the price so this cannot underflow. Return the funds. Similar to the previous transfer, this is not susceptible to a re-entry attack because the auction is removed before any transfers occur. | function _buy(
address _nftAddress,
uint256 _tokenId,
uint256 _bidAmount
) internal returns (uint256) {
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
uint256 _price = _auction.price;
require(
_bidAmount >= _price,
"JamMarketplace: bid amount cannot be less than price"
);
address _seller = _auction.seller;
_removeAuction(_nftAddress, _tokenId);
if (_price > 0) {
uint256 _auctioneerCut = _computeCut(_price);
uint256 _sellerProceeds = _price - _auctioneerCut;
payable(_seller).transfer(_sellerProceeds);
if (_supportIERC2981(_nftAddress)) {
IERC2981 royaltyContract = _getERC2981(_nftAddress);
(address firstOwner, uint256 amount) = royaltyContract
.royaltyInfo(_tokenId, _auctioneerCut);
require(
amount < _auctioneerCut,
"JamMarketplace: royalty amount must be less than auctioneer cut"
);
_totalRoyaltyCut[address(0)] = _totalRoyaltyCut[address(0)].add(
amount
);
royaltyCuts[firstOwner][address(0)] = royaltyCuts[firstOwner][
address(0)
].add(amount);
}
}
if (_bidAmount > _price) {
uint256 _bidExcess = _bidAmount - _price;
payable(msg.sender).transfer(_bidExcess);
}
return _price;
}
| 7,327,342 |
./full_match/5/0x999512dC124371E6B9ff43CE8D1AF83252F0C851/sources/lib/joe-v2/src/libraries/math/SafeCast.sol | Returns x on uint168 and check that it does not overflow x The value as an uint256 return y The value as an uint168/ | function safe168(uint256 x) internal pure returns (uint168 y) {
if ((y = uint168(x)) != x) revert SafeCast__Exceeds168Bits();
}
| 1,894,144 |
./partial_match/1/0xE5824256d4D08a09164bC127ccD22E58A2135522/sources/wPGO_Presale.sol | Withdraw the wPGO Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached, sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw the amount they contributed./ | function safeWithdrawalWPGO() public afterDeadline {
if (beneficiary == msg.sender && presaleClosed) {
tokenReward.transfer(msg.sender, tokenBalance);
tokenBalance = 0;
}
}
| 4,213,746 |
pragma solidity ^ 0.5.11;
contract PoWHr{
// scaleFactor is used to convert Ether into bonds and vice-versa: they're of different
// orders of magnitude, hence the need to bridge between the two.
uint256 constant scaleFactor = 0x10000000000000000;
int constant crr_n = 1;
int constant crr_d = 2;
int constant public price_coeff = -0x1337FA66607BADA55;
// Typical values that we have to declare.
string constant public name = "Bond";
string constant public symbol = "BOND";
uint8 constant public decimals = 12;
// Array between each address and their number of bonds.
mapping(address => uint256) public hodlBonds;
// For calculating resolves minted
mapping(address => uint256) public avgFactor_ethSpent;
// For calculating hodl multiplier that factors into resolves minted
mapping(address => uint256) public avgFactor_buyInTimeSum;
// Array between each address and their number of resolves being staked.
mapping(address => uint256) public resolveWeight;
// Array between each address and how much Ether has been paid out to it.
// Note that this is scaled by the scaleFactor variable.
mapping(address => int256) public payouts;
// Variable tracking how many bonds are in existence overall.
uint256 public _totalSupply;
// The total number of resolves being staked in this contract
uint256 public dissolvingResolves;
// The total number of resolves burned for a return of ETH(withdraw) or Bonds(reinvest)
uint256 public dissolved;
// The ethereum locked up into bonds
uint public reserves;
// Easing in the fee. Make the fee reasonable as the contract is scaling to the size of the ecosystem
uint256 public buySum;
uint256 public sellSum;
// For calculating the hodl multiplier. Weighted average release time
uint public avgFactor_releaseWeight;
uint public avgFactor_releaseTimeSum;
// base time on when the contract was created
uint public genesis;
// Aggregate sum of all payouts.
// Note that this is scaled by the scaleFactor variable.
int256 totalPayouts;
// Variable tracking how much Ether each token is currently worth.
// Note that this is scaled by the scaleFactor variable.
uint256 earningsPerResolve;
uint remainderForDividends;
//The resolve token contract
ResolveToken public resolveToken;
constructor() public{
genesis = now;
resolveToken = new ResolveToken( address(this) );
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function getResolveContract() public view returns(address){ return address(resolveToken); }
// Returns the number of bonds currently held by _owner.
function balanceOf(address _owner) public view returns (uint256 balance) {
return hodlBonds[_owner];
}
function fluxFee(uint paidAmount) public view returns (uint fee) {
if (dissolvingResolves == 0)
return 0;
uint totalResolveSupply = resolveToken.totalSupply() - dissolved;
return paidAmount * dissolvingResolves / totalResolveSupply * sellSum / buySum;
}
// Converts the Ether accrued as resolveEarnings back into bonds without having to
// withdraw it first. Saves on gas and potential price spike loss.
event Reinvest( address indexed addr, uint256 reinvested, uint256 dissolved, uint256 bonds, uint256 resolveTax);
function reinvestEarnings(uint amountFromEarnings) public returns(uint,uint){
// Retrieve the resolveEarnings associated with the address the request came from.
uint totalEarnings = resolveEarnings(msg.sender);
require(amountFromEarnings <= totalEarnings, "the amount exceeds total earnings");
uint oldWeight = resolveWeight[msg.sender];
resolveWeight[msg.sender] = oldWeight * (totalEarnings - amountFromEarnings) / totalEarnings;
uint weightDiff = oldWeight - resolveWeight[msg.sender];
dissolved += weightDiff;
dissolvingResolves -= weightDiff;
// For maintaing payout invariance
int resolvePayoutDiff = (int256) (earningsPerResolve * weightDiff);
payouts[msg.sender] += resolvePayoutDiff;
totalPayouts += resolvePayoutDiff;
// Assign balance to a new variable.
uint value_ = (uint) (amountFromEarnings);
// If your resolveEarnings are worth less than 1 szabo, abort.
if (value_ < 0.000001 ether)
revert();
// msg.sender is the address of the caller.
address sender = msg.sender;
// Calculate the fee
uint fee = fluxFee(value_);
// The amount of Ether used to purchase new bonds for the caller
uint numEther = value_ - fee;
buySum += numEther;
reserves += numEther;
//resolve reward tracking stuff
uint currentTime = NOW();
avgFactor_ethSpent[msg.sender] += numEther;
avgFactor_buyInTimeSum[msg.sender] += currentTime * scaleFactor * numEther;
// The number of bonds which can be purchased for numEther.
uint createdBonds = calculateBondsFromReinvest(numEther, amountFromEarnings);
// the variable storing the amount to be paid to stakers
uint resolveFee;
// Check if we have bonds in existence
if (_totalSupply > 0 && fee > 0) {
resolveFee = fee * scaleFactor;
// Fee is distributed to all existing resolve stakers before the new bonds are purchased.
// rewardPerResolve is the amount(ETH) gained per resolve token from this purchase.
uint rewardPerResolve = dividendDivide(resolveFee);
// The Ether value per token is increased proportionally.
earningsPerResolve += rewardPerResolve;
}
// Add the createdBonds to the total supply.
_totalSupply += createdBonds;
// Assign the bonds to the balance of the buyer.
hodlBonds[sender] += createdBonds;
emit Reinvest(msg.sender, value_, weightDiff, createdBonds, resolveFee);
return (createdBonds, weightDiff);
}
function dividendDivide(uint N) internal returns(uint){
uint quotient = N/dissolvingResolves;
remainderForDividends += N - quotient * dissolvingResolves;
if( remainderForDividends > dissolvingResolves ){
uint divs = remainderForDividends;
remainderForDividends = 0;
uint rQuotient = divs/dissolvingResolves;
earningsPerResolve += rQuotient;
remainderForDividends += divs - rQuotient * dissolvingResolves;
}
return quotient;
}
// Sells your bonds for Ether
function sellAllBonds() public {
sell( balanceOf(msg.sender) );
}
function sellBonds(uint amount) public returns(uint,uint){
uint balance = balanceOf(msg.sender);
require(balance >= amount, "Amount is more than balance");
uint returned_eth;
uint returned_resolves;
(returned_eth, returned_resolves) = sell(amount);
return (returned_eth, returned_resolves);
}
// Big red exit button to pull all of a holder's Ethereum value from the contract
function getMeOutOfHere() public {
sellAllBonds();
withdraw( resolveEarnings(msg.sender) );
}
// Gatekeeper function to check if the amount of Ether being sent isn't too small
function fund() payable public returns(uint){
uint bought;
if (msg.value > 0.000001 ether) {
bought = buy();
} else {
revert();
}
return bought;
}
// Function that returns the (dynamic) pricing for buys, sells and fee
function pricing(uint scale) public view returns (uint buyPrice, uint sellPrice, uint fee) {
uint buy_eth = scaleFactor * getPriceForBonds( scale, true) / ( scaleFactor - fluxFee(scaleFactor) ) ;
uint sell_eth = getPriceForBonds(scale, false);
sell_eth -= fluxFee(sell_eth);
return ( buy_eth, sell_eth, fluxFee(scale) );
}
// For calculating the price
function getPriceForBonds(uint256 bonds, bool upDown) public view returns (uint256 price) {
uint reserveAmount = reserve();
if(upDown){
uint x = fixedExp((fixedLog(_totalSupply + bonds) - price_coeff) * crr_d/crr_n);
return x - reserveAmount;
}else{
uint x = fixedExp((fixedLog(_totalSupply - bonds) - price_coeff) * crr_d/crr_n);
return reserveAmount - x;
}
}
// Calculate the current resolveEarnings associated with the caller address. This is the net result
// of multiplying the number of resolves held by their current value in Ether and subtracting the
// Ether that has already been paid out.
function resolveEarnings(address _owner) public view returns (uint256 amount) {
return (uint256) ((int256)(earningsPerResolve * resolveWeight[_owner]) - payouts[_owner]) / scaleFactor;
}
event Buy( address indexed addr, uint256 spent, uint256 bonds, uint256 resolveTax);
function buy() internal returns(uint){
// Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it.
if ( msg.value < 0.000001 ether )
revert();
// Calculate the fee
uint fee = fluxFee(msg.value);
// The amount of Ether used to purchase new bonds for the caller.
uint numEther = msg.value - fee;
buySum += numEther;
reserves += numEther;
//resolve reward tracking stuff
uint currentTime = NOW();
avgFactor_ethSpent[msg.sender] += numEther;
avgFactor_buyInTimeSum[msg.sender] += currentTime * scaleFactor * numEther;
// The number of bonds which can be purchased for numEther.
uint createdBonds = getBondsForEther(numEther);
// Add the createdBonds to the total supply.
_totalSupply += createdBonds;
// Assign the bonds to the balance of the buyer.
hodlBonds[msg.sender] += createdBonds;
// Check if we have bonds in existence
uint resolveFee;
if (_totalSupply > 0 && fee > 0) {
resolveFee = fee * scaleFactor;
// Fee is distributed to all existing resolve holders before the new bonds are purchased.
// rewardPerResolve is the amount gained per resolve token from this purchase.
uint rewardPerResolve = dividendDivide(resolveFee);
// The Ether value per resolve is increased proportionally.
earningsPerResolve += rewardPerResolve;
}
emit Buy( msg.sender, msg.value, createdBonds, resolveFee);
return createdBonds;
}
function NOW() public view returns(uint time){
return now - genesis;
}
function avgHodl() public view returns(uint hodlTime){
return avgFactor_releaseTimeSum / avgFactor_releaseWeight / scaleFactor;
}
function getReturnsForBonds(address addr, uint bondsReleased) public view returns(uint etherValue, uint mintedResolves, uint new_releaseTimeSum, uint new_releaseWeight, uint initialInput_ETH){
uint output_ETH = getEtherForBonds(bondsReleased);
uint input_ETH = avgFactor_ethSpent[addr] * bondsReleased / hodlBonds[addr];
// hodl multiplier. because if you don't hodl at all, you shouldn't be rewarded resolves.
// and the multiplier you get for hodling needs to be relative to the average hodl
uint buyInTime = avgFactor_buyInTimeSum[addr] / avgFactor_ethSpent[addr];
uint cashoutTime = NOW()*scaleFactor - buyInTime;
uint releaseTimeSum = avgFactor_releaseTimeSum + cashoutTime*input_ETH/scaleFactor/*to give new life more weight--->*/*buyInTime;
uint releaseWeight = avgFactor_releaseWeight + input_ETH/*to give new life more weight--->*/*buyInTime/scaleFactor;
uint avgCashoutTime = releaseTimeSum/releaseWeight;
return (output_ETH, input_ETH * cashoutTime / avgCashoutTime * input_ETH / output_ETH, releaseTimeSum, releaseWeight, input_ETH);
}
event Sell( address indexed addr, uint256 bondsSold, uint256 cashout, uint256 resolves, uint256 resolveTax, uint256 initialCash);
function sell(uint256 amount) internal returns(uint eth, uint resolves){
// Calculate the amount of Ether & Resolves that the holder's bonds sell for at the current sell price.
uint numEthersBeforeFee;
uint mintedResolves;
uint releaseTimeSum;
uint releaseWeight;
uint initialInput_ETH;
(numEthersBeforeFee,mintedResolves,releaseTimeSum,releaseWeight,initialInput_ETH) = getReturnsForBonds(msg.sender, amount);
// magic distribution
resolveToken.mint(msg.sender, mintedResolves);
// update weighted average cashout time
avgFactor_releaseTimeSum = releaseTimeSum;
avgFactor_releaseWeight = releaseWeight;
// reduce the amount of "eth spent" based on the percentage of bonds being sold back into the contract
avgFactor_ethSpent[msg.sender] -= initialInput_ETH;
// reduce the "buyInTime" sum that's used for average buy in time
avgFactor_buyInTimeSum[msg.sender] = avgFactor_buyInTimeSum[msg.sender] * (hodlBonds[msg.sender] - amount) / hodlBonds[msg.sender];
// calculate the fee
uint fee = fluxFee(numEthersBeforeFee);
// Net Ether for the seller after the fee has been subtracted.
uint numEthers = numEthersBeforeFee - fee;
//updating the numerator of the fee-easing factor
sellSum += initialInput_ETH;
// Burn the bonds which were just sold from the total supply.
_totalSupply -= amount;
// Remove the bonds from the balance of the buyer.
hodlBonds[msg.sender] -= amount;
// Check if we have bonds in existence
uint resolveFee;
if (_totalSupply > 0 && dissolvingResolves > 0){
// Scale the Ether taken as the selling fee by the scaleFactor variable.
resolveFee = fee * scaleFactor;
// Fee is distributed to all remaining resolve holders.
// rewardPerResolve is the amount gained per resolve thanks to this sell.
uint rewardPerResolve = dividendDivide(resolveFee);
// The Ether value per resolve is increased proportionally.
earningsPerResolve += rewardPerResolve;
}
// Send the ethereum to the address that requested the sell.
reserves -= numEthers;
msg.sender.transfer(numEthers);
emit Sell( msg.sender, amount, numEthers, mintedResolves, resolveFee, initialInput_ETH);
return (numEthers, mintedResolves);
}
// Dynamic value of Ether in reserve, according to the CRR requirement.
function reserve() internal view returns (uint256 amount) {
return SafeMath.sub(reserves - msg.value, (uint256) ((int256) (earningsPerResolve * dissolvingResolves) - totalPayouts) / scaleFactor );
}
// Calculates the number of bonds that can be bought for a given amount of Ether, according to the
// dynamic reserve and _totalSupply values (derived from the buy and sell prices).
function getBondsForEther(uint256 ethervalue) public view returns (uint256 bonds) {
return SafeMath.sub(fixedExp( fixedLog( reserve() + ethervalue ) * crr_n/crr_d + price_coeff ) , _totalSupply);
}
// Semantically similar to getBondsForEther, but subtracts the callers balance from the amount of Ether returned for conversion.
function calculateBondsFromReinvest(uint256 ethervalue, uint256 subvalue) public view returns (uint256 bondTokens) {
return SafeMath.sub(fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff) , _totalSupply);
}
// Converts a number bonds into an Ether value.
function getEtherForBonds(uint256 bondTokens) public view returns (uint256 ethervalue) {
// How much reserve Ether do we have left in the contract?
uint reserveAmount = reserve();
// If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault.
if (bondTokens == _totalSupply)
return reserveAmount;
// If there would be excess Ether left after the transaction this is called within, return the Ether
// corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found
// at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator
// and denominator altered to 1 and 2 respectively.
uint x = fixedExp( (fixedLog(_totalSupply-bondTokens)-price_coeff) * crr_d/crr_n);
return SafeMath.sub(reserveAmount, x);
}
// You don't care about these, but if you really do they're hex values for
// co-efficients used to simulate approximations of the log and exp functions.
int256 constant one = 0x10000000000000000;
uint256 constant sqrt2 = 0x16a09e667f3bcc908;
uint256 constant sqrtdot5 = 0x0b504f333f9de6484;
int256 constant ln2 = 0x0b17217f7d1cf79ac;
int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8;
int256 constant c1 = 0x1ffffffffff9dac9b;
int256 constant c3 = 0x0aaaaaaac16877908;
int256 constant c5 = 0x0666664e5e9fa0c99;
int256 constant c7 = 0x049254026a7630acf;
int256 constant c9 = 0x038bd75ed37753d68;
int256 constant c11 = 0x03284a0c14610924f;
// The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11
// approximates the function log(1+x)-log(1-x)
// Hence R(s) = log((1+s)/(1-s)) = log(a)
function fixedLog(uint256 a) internal pure returns (int256 log) {
int32 scale = 0;
while (a > sqrt2) {
a /= 2;
scale++;
}
while (a <= sqrtdot5) {
a *= 2;
scale--;
}
int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one);
int z = (s*s) / one;
return scale * ln2 +
(s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one))
/one))/one))/one))/one))/one);
}
int256 constant c2 = 0x02aaaaaaaaa015db0;
int256 constant c4 = -0x000b60b60808399d1;
int256 constant c6 = 0x0000455956bccdd06;
int256 constant c8 = -0x000001b893ad04b3a;
// The polynomial R = 2 + c2*x^2 + c4*x^4 + ...
// approximates the function x*(exp(x)+1)/(exp(x)-1)
// Hence exp(x) = (R(x)+x)/(R(x)-x)
function fixedExp(int256 a) internal pure returns (uint256 exp) {
int256 scale = (a + (ln2_64dot5)) / ln2 - 64;
a -= scale*ln2;
int256 z = (a*a) / one;
int256 R = ((int256)(2) * one) +
(z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one);
exp = (uint256) (((R + a) * one) / (R - a));
if (scale >= 0)
exp <<= scale;
else
exp >>= -scale;
return exp;
}
// This allows you to buy bonds by sending Ether directly to the smart contract
// without including any transaction data (useful for, say, mobile wallet apps).
function () payable external {
// msg.value is the amount of Ether sent by the transaction.
if (msg.value > 0) {
fund();
} else {
withdraw( resolveEarnings(msg.sender) );
}
}
// Allow contract to accept resolve tokens
event StakeResolves( address indexed addr, uint256 amountStaked, bytes _data );
function tokenFallback(address from, uint value, bytes calldata _data) external{
if(msg.sender == address(resolveToken) ){
resolveWeight[from] += value;
dissolvingResolves += value;
// Update the payout array so that the "resolve shareholder" cannot claim resolveEarnings on previous staked resolves.
int payoutDiff = (int256) (earningsPerResolve * value);
// Then we update the payouts array for the "resolve shareholder" with this amount
payouts[from] += payoutDiff;
emit StakeResolves(from, value, _data);
}else{
revert("no want");
}
}
// Withdraws resolveEarnings held by the caller sending the transaction, updates
// the requisite global variables, and transfers Ether back to the caller.
event Withdraw( address indexed addr, uint256 earnings, uint256 dissolve );
function withdraw(uint amount) public returns(uint){
// Retrieve the resolveEarnings associated with the address the request came from.
uint totalEarnings = resolveEarnings(msg.sender);
require(amount <= totalEarnings, "the amount exceeds total earnings");
uint oldWeight = resolveWeight[msg.sender];
resolveWeight[msg.sender] = oldWeight * (totalEarnings - amount) / totalEarnings;
uint weightDiff = oldWeight - resolveWeight[msg.sender];
dissolved += weightDiff;
dissolvingResolves -= weightDiff;
//something about invariance
int resolvePayoutDiff = (int256) (earningsPerResolve * weightDiff);
payouts[msg.sender] += resolvePayoutDiff;
// Increase the total amount that's been paid out to maintain invariance.
totalPayouts += resolvePayoutDiff;
// Send the resolveEarnings to the address that requested the withdraw.
msg.sender.transfer(amount);
emit Withdraw( msg.sender, amount, weightDiff);
return weightDiff;
}
event PullResolves( address indexed addr, uint256 pulledResolves, uint256 forfeiture);
function pullResolves(uint amount) public{
require(amount <= resolveWeight[msg.sender], "that amount is too large");
require(amount != dissolvingResolves, "you can't forfeit the last amount");
//something about invariance
uint forfeitedEarnings = amount * earningsPerResolve;
// Update the payout array so that the "resolve shareholder" cannot claim resolveEarnings on previous staked resolves.
// Then we update the payouts array for the "resolve shareholder" with this amount
payouts[msg.sender] -= (int256) (earningsPerResolve * amount);
resolveWeight[msg.sender] -= amount;
dissolvingResolves -= amount;
// The Ether value per token is increased proportionally.
earningsPerResolve += dividendDivide( forfeitedEarnings );
resolveToken.transfer(msg.sender, amount);
emit PullResolves( msg.sender, amount, forfeitedEarnings / scaleFactor);
}
event BondTransfer(address from, address to, uint amount);
function bondTransfer( address to, uint amount ) public{
//attack someone's resolve potential by sending them some love
address sender = msg.sender;
uint totalBonds = hodlBonds[sender];
require(amount <= totalBonds, "amount exceeds hodlBonds");
uint ethSpent = avgFactor_ethSpent[sender] * amount / totalBonds;
uint buyInTimeSum = avgFactor_buyInTimeSum[sender] * amount / totalBonds;
avgFactor_ethSpent[sender] -= ethSpent;
avgFactor_buyInTimeSum[sender] -= buyInTimeSum;
hodlBonds[sender] -= amount;
avgFactor_ethSpent[to] += ethSpent;
avgFactor_buyInTimeSum[to] += buyInTimeSum;
hodlBonds[to] += amount;
emit BondTransfer(sender, to, amount);
}
}
contract ERC223ReceivingContract{
function tokenFallback(address _from, uint _value, bytes calldata _data) external;
}
contract ResolveToken{
address pyramid;
constructor(address _pyramid) public{
pyramid = _pyramid;
}
modifier pyramidOnly{
require(msg.sender == pyramid);
_;
}
event Transfer(
address indexed from,
address indexed to,
uint256 amount,
bytes data
);
event Mint(
address indexed addr,
uint256 amount
);
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) approvals;
string public name = "Resolve";
string public symbol = "PoWHr";
uint8 constant public decimals = 18;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function mint(address _address, uint _value) public pyramidOnly(){
balances[_address] += _value;
_totalSupply += _value;
emit Mint(_address, _value);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes memory _data) public returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}else{
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value) public returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)){
return transferToContract(_to, _value, empty);
}else{
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) public view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
if(length>0) {
return true;
}else {
return false;
}
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes memory _data) private returns (bool success) {
moveTokens(msg.sender,_to,_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes memory _data) private returns (bool success) {
moveTokens(msg.sender, _to, _value);
ERC223ReceivingContract reciever = ERC223ReceivingContract(_to);
reciever.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function moveTokens(address _from, address _to, uint _amount) private{
balances[_from] -= _amount;
balances[_to] += _amount;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
function allowance(address src, address guy) public view returns (uint) {
return approvals[src][guy];
}
function transferFrom(address src, address dst, uint wad) public returns (bool){
require(approvals[src][msg.sender] >= wad, "That amount is not approved");
require(balances[src] >= wad, "That amount is not available from this wallet");
if (src != msg.sender) {
approvals[src][msg.sender] -= wad;
}
moveTokens(src,dst,wad);
bytes memory empty;
emit Transfer(src, dst, wad, empty);
return true;
}
function approve(address guy, uint wad) public returns (bool) {
approvals[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
event Approval(address indexed src, address indexed guy, uint wad);
}
/**
* @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;
}
} | attack someone's resolve potential by sending them some love | function bondTransfer( address to, uint amount ) public{
address sender = msg.sender;
uint totalBonds = hodlBonds[sender];
require(amount <= totalBonds, "amount exceeds hodlBonds");
uint ethSpent = avgFactor_ethSpent[sender] * amount / totalBonds;
uint buyInTimeSum = avgFactor_buyInTimeSum[sender] * amount / totalBonds;
avgFactor_ethSpent[sender] -= ethSpent;
avgFactor_buyInTimeSum[sender] -= buyInTimeSum;
hodlBonds[sender] -= amount;
avgFactor_ethSpent[to] += ethSpent;
avgFactor_buyInTimeSum[to] += buyInTimeSum;
hodlBonds[to] += amount;
emit BondTransfer(sender, to, amount);
}
| 12,792,480 |
./full_match/1/0xa4Bad5d040d4464EC5CE130987731F2f428c9307/sources/contracts/EnokiGeyser.sol | Unstakes a certain amount of previously deposited tokens. User also receives their alotted number of distribution tokens. stakes Mushrooms to unstake. data Not used./ | function unstake(uint256[] calldata stakes, bytes calldata data) external {
_unstake(stakes);
}
| 8,357,525 |
./full_match/80001/0xACFdf4f909b7A52B184a5A70DCb7f038f5f29674/sources/contracts/relayer/loe-relayer/loe-feat-eip2771/contracts/contracts/nftstake/LoeNftStaking.sol | the stake function needs an approval/ | function stake(address tokenAddress, uint256 tokenId, uint256 amount) external {
address msgSender = _msgSender();
_stake(msgSender, tokenAddress, tokenId, amount);
IERC1155(tokenAddress).safeTransferFrom(msgSender, address(this), tokenId, amount, "");
}
| 5,600,288 |
./full_match/137/0x1e3fCa63502a7AaA6841788301Eae4AC67CF691D/sources/scripts/Learning_Projects/CheeseTouch.sol | See {IERC721-approve}./ | function approve(address to, uint256 tokenId) public virtual override {
address owner = CheeseTouch.ownerOf(tokenId);
require(to != owner, "CheeseTouch: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"CheeseTouch: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
| 4,755,532 |
pragma solidity ^0.4.21;
contract ERC20_Interface {
function totalSupply() public constant returns (uint256);
function balanceOf(address tokenOwner) public constant returns (uint256 balance);
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
contract ERC20_ReceivingInterface {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
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;
}
}
contract 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;
}
}
contract SoraToken is ERC20_Interface, Ownable, SafeMath {
string public constant symbol = "XOR";
string public constant name = "Sora";
uint8 public constant decimals = 18;
uint256 internal constant _totalSupply = 161803398874989484820458683437;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
function totalSupply() public constant returns (uint256) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function SoraToken() public {
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function() public payable {
revert();
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint256 tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint256 tokens) public returns (bool success) {
balances[from] = sub(balances[from], tokens);
allowed[from][msg.sender] = sub(allowed[from][msg.sender], tokens);
balances[to] = add(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint256 tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ERC20_ReceivingInterface(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) {
return ERC20_Interface(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint256 balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = sub(balances[msg.sender], tokens);
balances[to] = add(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
} | ------------------------------------------------------------------------ Transfer `tokens` from the `from` account to the `to` account The calling account must already have sufficient tokens approve(...)-d for spending from the `from` account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------ | function transferFrom(address from, address to, uint256 tokens) public returns (bool success) {
balances[from] = sub(balances[from], tokens);
allowed[from][msg.sender] = sub(allowed[from][msg.sender], tokens);
balances[to] = add(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
| 6,893,023 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "./interfaces/IPWPegger.sol";
import "./interfaces/lib/PWConfig.sol";
import "./interfaces/dependencies/IEACAggregatorProxy.sol";
enum EAction {
Up,
Down
}
contract PWPegger is IPWPegger {
PWConfig private pwconfig;
bool statusPause;
uint round;
modifier onlyAdmin() {
require(msg.sender == pwconfig.admin, "Error: must be admin EOA or multisig only");
_;
}
modifier onlyKeeper() {
require(msg.sender == pwconfig.admin || msg.sender == pwconfig.keeper,
"Error: must be admin or keeper EOA/multisig only");
_;
}
modifier onlyNotPaused() {
require(!statusPause, "PWPeggerMock in on Pause now");
_;
}
constructor(PWConfig memory _pwconfig) {
uint _dec = _pwconfig.decimals;
require(
_dec > 0 && (
_pwconfig.frontrunth % _dec +
_pwconfig.volatilityth % _dec +
_pwconfig.emergencyth % _dec == 0
) &&
_pwconfig.frontrunth > 0 &&
_pwconfig.volatilityth > _pwconfig.frontrunth &&
_pwconfig.emergencyth > _pwconfig.volatilityth,
"Error: wrong config parameters. Check th params and decimals"
);
require(msg.sender != _pwconfig.admin, "Error: deployer cannot be an admin");
pwconfig = _pwconfig;
statusPause = false;
round = 0;
}
function updAdmin(address _newAdmin) external override onlyAdmin() {
pwconfig.admin = _newAdmin;
}
function updKeeper(address _newKeeper) external override onlyAdmin() {
pwconfig.keeper = _newKeeper;
}
function updCurrentDONRef(address _newPricedonRef) external override onlyAdmin() {
pwconfig.pricedonRef = _newPricedonRef;
}
function updPathwayDONRef(address _newPwpegdonRef) external override onlyAdmin() {
pwconfig.pwpegdonRef = _newPwpegdonRef;
}
function updCorrectorUpProxyRef(address _newCorrectorup) external override onlyAdmin() {
pwconfig.correctorup = _newCorrectorup;
}
function updCorrectorDownProxyRef(address _newCorrectordown) external override onlyAdmin() {
pwconfig.correctordown = _newCorrectordown;
}
function updVaultRef(address _newVault) external override onlyAdmin() {
pwconfig.vault = _newVault;
}
function setPauseOn() external override onlyKeeper() onlyNotPaused() {
statusPause = true;
}
function setPauseOff() external override onlyAdmin() {
statusPause = false;
}
function getPauseStatus() external override view returns (bool) {
return statusPause;
}
function updPoolRef(address _pool) external override onlyAdmin() {
pwconfig.pool = _pool;
}
function updTokenRef(address _token) external override onlyAdmin() {
pwconfig.token = _token;
}
function updEmergencyTh(uint _newEmergencyth) external override onlyAdmin() {
pwconfig.emergencyth = _newEmergencyth;
}
function updVolatilityTh(uint _newVolatilityth) external override onlyAdmin() {
pwconfig.volatilityth = _newVolatilityth;
}
function updFrontRunProtectionTh(uint _newFrontrunth) external override onlyAdmin() {
pwconfig.frontrunth = _newFrontrunth;
}
function _checkThConditionsOrRaiseException(uint _currPrice, uint _pwPrice) view internal {
if (_currPrice >= _pwPrice) {
require(_currPrice - _pwPrice < pwconfig.emergencyth,
"Th Emergency Error: current price is much higher than pwPrice");
require(_currPrice - _pwPrice >= pwconfig.volatilityth,
"Th Volatility Error: current price is not enough higher than pwPrice");
} else {
require(_pwPrice - _currPrice < pwconfig.emergencyth,
"Th Emergency Error: pwPrice price is much higher than current");
require(_pwPrice - _currPrice >= pwconfig.volatilityth,
"Th Volatility Error: pwPrice price is not enough higher than current");
}
}
function _checkThFrontrunOrRaiseException(uint _currPrice, uint _keeperPrice) view internal {
// additional logic to prevent frontrun attack can be added here: VRF check as an example
if (_currPrice >= _keeperPrice) {
require(_currPrice - _keeperPrice <= pwconfig.frontrunth,
"Th FrontRun Error: current price is much higher than keeperPrice");
} else {
require(_keeperPrice - _currPrice <= pwconfig.emergencyth,
"Th Emergency Error: current price is much higher than keeperPrice");
}
}
// those functions are reading and convert data to the correct decimals for price data
function _readDONPrice(address _refDON) view internal returns (uint) {
IEACAggregatorProxy priceFeed = IEACAggregatorProxy(_refDON);
(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = priceFeed.latestRoundData();
uint decimals = priceFeed.decimals();
require(decimals >= 0 && answer > 0, 'DON Error: price data and decimals must be higher than 0');
uint n = 10**pwconfig.decimals;
uint d = 10**decimals;
return (uint(answer)*n/d);
}
function _computeLPCount2Calibrator(uint _g, uint _p1, uint _p2, uint _lps) view internal returns (uint) {
require(_p2 > _p1 && _p1 > 0 && _g > 0 && _lps > 0, "Error: computeLP2Calibrator wrong input args");
// g*P1 + u = g’*P2 + u’, where P1 is a price of g in u; u == u' =>
// => dg = g’ - g or dg = g*(P1/P2 - 1) => mdg = g*(1 - P1/P2)
uint n = 10**pwconfig.decimals;
uint mdg = _g*(n - _p1*n/_p2)/n;
uint hasToBeExtractedG = mdg/2;
uint hasToBeExtractedLPShare = n*hasToBeExtractedG/_g;
return _lps*hasToBeExtractedLPShare/n; //_lps has its own decimals
}
function _computeGUpRatio(
address _refPool,
address _refToken,
EAction _type,
uint _currentPrice,
uint _pegPrice
) view internal returns (uint g, uint p1, uint p2) {
}
function callIntervention(uint _keeperCurrentPrice) external override onlyKeeper() onlyNotPaused() {
require(_keeperCurrentPrice > 0, 'Call Error: _keeperCurrentPrice must be higher than 0');
uint cPrice = _readDONPrice(pwconfig.pricedonRef);
uint pPrice = _readDONPrice(pwconfig.pwpegdonRef);
_checkThConditionsOrRaiseException(cPrice, pPrice);
_checkThFrontrunOrRaiseException(cPrice, _keeperCurrentPrice);
EAction act = pPrice > cPrice ? EAction.Up : EAction.Down;
// what to do: up or down
// how many LPs
// execute:
round = round + 1;
console.log("callIntervention a PWPegger with _keeperCurrentPrice:", _keeperCurrentPrice);
}
function getPWConfig() external override view returns (PWConfig memory) {
return pwconfig;
}
function getLastRoundNumber() external override view returns (uint) {
return round;
}
}
| gP1 + u = g’P2 + u’, where P1 is a price of g in u; u == u' => => dg = g’ - g or dg = g(P1/P2 - 1) => mdg = g(1 - P1/P2) | function _computeLPCount2Calibrator(uint _g, uint _p1, uint _p2, uint _lps) view internal returns (uint) {
require(_p2 > _p1 && _p1 > 0 && _g > 0 && _lps > 0, "Error: computeLP2Calibrator wrong input args");
uint n = 10**pwconfig.decimals;
uint mdg = _g*(n - _p1*n/_p2)/n;
uint hasToBeExtractedG = mdg/2;
uint hasToBeExtractedLPShare = n*hasToBeExtractedG/_g;
}
| 1,778,843 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
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 Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IController {
function addSet(address _setToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isSet(address _setToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IIntegrationRegistry {
function addIntegration(address _module, string memory _id, address _wrapper) external;
function getIntegrationAdapter(address _module, string memory _id) external view returns(address);
function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address);
function isValidIntegration(address _module, string memory _id) external view returns(bool);
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IModule
* @author Set Protocol
*
* Interface for interacting with Modules.
*/
interface IModule {
/**
* Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function removeModule() external;
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { ISetToken } from "./ISetToken.sol";
interface INAVIssuanceHook {
function invokePreIssueHook(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
address _sender,
address _to
)
external;
function invokePreRedeemHook(
ISetToken _setToken,
uint256 _redeemQuantity,
address _sender,
address _to
)
external;
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IPriceOracle
* @author Set Protocol
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { ISetToken } from "../interfaces/ISetToken.sol";
interface ISetValuer {
function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256);
}
/*
Copyright 2018 Set 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.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title IWETH
* @author Set Protocol
*
* Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal
* functionality.
*/
interface IWETH is IERC20{
function deposit()
external
payable;
function withdraw(
uint256 wad
)
external;
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title ExplicitERC20
* @author Set Protocol
*
* Utility functions for ERC20 transfers that require the explicit amount to be transferred.
*/
library ExplicitERC20 {
using SafeMath for uint256;
/**
* When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity".
* Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)
*
* @param _token ERC20 token to approve
* @param _from The account to transfer tokens from
* @param _to The account to transfer tokens to
* @param _quantity The quantity to transfer
*/
function transferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _quantity
)
internal
{
// Call specified ERC20 contract to transfer tokens (via proxy).
if (_quantity > 0) {
uint256 existingBalance = _token.balanceOf(_to);
SafeERC20.safeTransferFrom(
_token,
_from,
_to,
_quantity
);
uint256 newBalance = _token.balanceOf(_to);
// Verify transfer quantity is reflected in balance
require(
newBalance == existingBalance.add(_quantity),
"Invalid post transfer balance"
);
}
}
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
/**
* @title Invoke
* @author Set Protocol
*
* A collection of common utility functions for interacting with the SetToken's invoke function
*/
library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the SetToken to set approvals of the ERC20 token to a spender.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the SetToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ISetToken _setToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_setToken.invoke(_token, 0, callData);
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_setToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
* The new SetToken balance must equal the existing balance less the quantity transferred
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the SetToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken));
Invoke.invokeTransfer(_setToken, _token, _to, _quantity);
// Get new balance of transferred token for SetToken
uint256 newBalance = IERC20(_token).balanceOf(address(_setToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the SetToken to unwrap the passed quantity of WETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_setToken.invoke(_weth, 0, callData);
}
/**
* Instructs the SetToken to wrap the passed quantity of ETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_setToken.invoke(_weth, _quantity, callData);
}
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol";
import { IController } from "../../interfaces/IController.sol";
import { IModule } from "../../interfaces/IModule.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { Invoke } from "./Invoke.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { ResourceIdentifier } from "./ResourceIdentifier.sol";
/**
* @title ModuleBase
* @author Set Protocol
*
* Abstract class that houses common Module-related state and functions.
*/
abstract contract ModuleBase is IModule {
using PreciseUnitMath for uint256;
using Invoke for ISetToken;
using ResourceIdentifier for IController;
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
/* ============ Modifiers ============ */
modifier onlyManagerAndValidSet(ISetToken _setToken) {
require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager");
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
_;
}
modifier onlySetManager(ISetToken _setToken, address _caller) {
require(isSetManager(_setToken, _caller), "Must be the SetToken manager");
_;
}
modifier onlyValidAndInitializedSet(ISetToken _setToken) {
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
_;
}
/**
* Throws if the sender is not a SetToken's module or module not enabled
*/
modifier onlyModule(ISetToken _setToken) {
require(
_setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
_;
}
/**
* Utilized during module initializations to check that the module is in pending state
* and that the SetToken is valid
*/
modifier onlyValidAndPendingSet(ISetToken _setToken) {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
_;
}
/* ============ Constructor ============ */
/**
* Set state variables and map asset pairs to their oracles
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public {
controller = _controller;
}
/* ============ Internal Functions ============ */
/**
* Transfers tokens from an address (that has set allowance on the module).
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal {
ExplicitERC20.transferFrom(_token, _from, _to, _quantity);
}
/**
* Gets the integration for the module with the passed in name. Validates that the address is not empty
*/
function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
/**
* Gets the integration for the module with the passed in hash. Validates that the address is not empty
*/
function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) {
address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash(
address(this),
_integrationHash
);
require(adapter != address(0), "Must be valid adapter");
return adapter;
}
/**
* Gets the total fee for this module of the passed in index (fee % * quantity)
*/
function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) {
uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex);
return _quantity.preciseMul(feePercentage);
}
/**
* Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient
*/
function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal {
if (_feeQuantity > 0) {
_setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity);
}
}
/**
* Returns true if the module is in process of initialization on the SetToken
*/
function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) {
return _setToken.isPendingModule(address(this));
}
/**
* Returns true if the address is the SetToken's manager
*/
function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) {
return _setToken.manager() == _toCheck;
}
/**
* Returns true if SetToken must be enabled on the controller
* and module is registered on the SetToken
*/
function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) {
return controller.isSet(address(_setToken)) &&
_setToken.isInitializedModule(address(this));
}
/**
* Hashes the string and returns a bytes32 value
*/
function getNameHash(string memory _name) internal pure returns(bytes32) {
return keccak256(bytes(_name));
}
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
/**
* @title Position
* @author Set Protocol
*
* Collection of helper functions for handling and updating SetToken Positions
*
* CHANGELOG:
* - Updated editExternalPosition to work when no external position is associated with module
*/
library Position {
using SafeCast for uint256;
using SafeMath for uint256;
using SafeCast for int256;
using SignedSafeMath for int256;
using PreciseUnitMath for uint256;
/* ============ Helper ============ */
/**
* Returns whether the SetToken has a default position for a given component (if the real unit is > 0)
*/
function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) > 0;
}
/**
* Returns whether the SetToken has an external position for a given component (if # of position modules is > 0)
*/
function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getExternalPositionModules(_component).length > 0;
}
/**
* Returns whether the SetToken component default position real unit is greater than or equal to units passed in.
*/
function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
}
/**
* Returns whether the SetToken component external position is greater than or equal to the real units passed in.
*/
function hasSufficientExternalUnits(
ISetToken _setToken,
address _component,
address _positionModule,
uint256 _unit
)
internal
view
returns(bool)
{
return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
}
/**
* If the position does not exist, create a new Position and add to the SetToken. If it already exists,
* then set the position units. If the new units is 0, remove the position. Handles adding/removing of
* components where needed (in light of potential external positions).
*
* @param _setToken Address of SetToken being modified
* @param _component Address of the component
* @param _newUnit Quantity of Position units - must be >= 0
*/
function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_setToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not exist
if (!hasExternalPosition(_setToken, _component)) {
_setToken.addComponent(_component);
}
} else if (isPositionFound && _newUnit == 0) {
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_setToken, _component)) {
_setToken.removeComponent(_component);
}
}
_setToken.editDefaultPositionUnit(_component, _newUnit.toInt256());
}
/**
* Update an external position and remove and external positions or components if necessary. The logic flows as follows:
* 1) If component is not already added then add component and external position.
* 2) If component is added but no existing external position using the passed module exists then add the external position.
* 3) If the existing position is being added to then just update the unit and data
* 4) If the position is being closed and no other external positions or default positions are associated with the component
* then untrack the component and remove external position.
* 5) If the position is being closed and other existing positions still exist for the component then just remove the
* external position.
*
* @param _setToken SetToken being updated
* @param _component Component position being updated
* @param _module Module external position is associated with
* @param _newUnit Position units of new external position
* @param _data Arbitrary data associated with the position
*/
function editExternalPosition(
ISetToken _setToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (_newUnit != 0) {
if (!_setToken.isComponent(_component)) {
_setToken.addComponent(_component);
_setToken.addExternalPositionModule(_component, _module);
} else if (!_setToken.isExternalPositionModule(_component, _module)) {
_setToken.addExternalPositionModule(_component, _module);
}
_setToken.editExternalPositionUnit(_component, _module, _newUnit);
_setToken.editExternalPositionData(_component, _module, _data);
} else {
require(_data.length == 0, "Passed data must be null");
// If no default or external position remaining then remove component from components array
if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) {
address[] memory positionModules = _setToken.getExternalPositionModules(_component);
if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {
require(positionModules[0] == _module, "External positions must be 0 to remove component");
_setToken.removeComponent(_component);
}
_setToken.removeExternalPositionModule(_component, _module);
}
}
}
/**
* Get total notional amount of Default position
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _positionUnit Quantity of Position units
*
* @return Total notional amount of units
*/
function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
return _setTokenSupply.preciseMul(_positionUnit);
}
/**
* Get position unit from total notional amount
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _totalNotional Total notional amount of component prior to
* @return Default position unit
*/
function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_setTokenSupply);
}
/**
* Get the total tracked balance - total supply * position unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @return Notional tracked balance
*/
function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) {
int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component);
return _setToken.totalSupply().preciseMul(positionUnit.toUint256());
}
/**
* Calculates the new default position unit and performs the edit with the new unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @param _setTotalSupply Current SetToken supply
* @param _componentPreviousBalance Pre-action component balance
* @return Current component balance
* @return Previous position unit
* @return New position unit
*/
function calculateAndEditDefaultPosition(
ISetToken _setToken,
address _component,
uint256 _setTotalSupply,
uint256 _componentPreviousBalance
)
internal
returns(uint256, uint256, uint256)
{
uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken));
uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256();
uint256 newTokenUnit;
if (currentBalance > 0) {
newTokenUnit = calculateDefaultEditPositionUnit(
_setTotalSupply,
_componentPreviousBalance,
currentBalance,
positionUnit
);
} else {
newTokenUnit = 0;
}
editDefaultPosition(_setToken, _component, newTokenUnit);
return (currentBalance, positionUnit, newTokenUnit);
}
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _preTotalNotional Total notional amount of component prior to executing action
* @param _postTotalNotional Total notional amount of component after the executing action
* @param _prePositionUnit Position unit of SetToken prior to executing action
* @return New position unit
*/
function calculateDefaultEditPositionUnit(
uint256 _setTokenSupply,
uint256 _preTotalNotional,
uint256 _postTotalNotional,
uint256 _prePositionUnit
)
internal
pure
returns (uint256)
{
// If pre action total notional amount is greater then subtract post action total notional and calculate new position units
uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply));
return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply);
}
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IController } from "../../interfaces/IController.sol";
import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol";
import { IPriceOracle } from "../../interfaces/IPriceOracle.sol";
import { ISetValuer } from "../../interfaces/ISetValuer.sol";
/**
* @title ResourceIdentifier
* @author Set Protocol
*
* A collection of utility functions to fetch information related to Resource contracts in the system
*/
library ResourceIdentifier {
// IntegrationRegistry will always be resource ID 0 in the system
uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0;
// PriceOracle will always be resource ID 1 in the system
uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1;
// SetValuer resource will always be resource ID 2 in the system
uint256 constant internal SET_VALUER_RESOURCE_ID = 2;
/* ============ Internal ============ */
/**
* Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on
* the Controller
*/
function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) {
return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID));
}
/**
* Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller
*/
function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
/**
* Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller
*/
function getSetValuer(IController _controller) internal view returns (ISetValuer) {
return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID));
}
}
/*
Copyright 2020 Set 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { IController } from "../../interfaces/IController.sol";
import { INAVIssuanceHook } from "../../interfaces/INAVIssuanceHook.sol";
import { Invoke } from "../lib/Invoke.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { IWETH } from "../../interfaces/external/IWETH.sol";
import { ModuleBase } from "../lib/ModuleBase.sol";
import { Position } from "../lib/Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { ResourceIdentifier } from "../lib/ResourceIdentifier.sol";
/**
* @title NavIssuanceModule
* @author Set Protocol
*
* Module that enables issuance and redemption with any valid ERC20 token or ETH if allowed by the manager. Sender receives
* a proportional amount of SetTokens on issuance or ERC20 token on redemption based on the calculated net asset value using
* oracle prices. Manager is able to enforce a premium / discount on issuance / redemption to avoid arbitrage and front
* running when relying on oracle prices. Managers can charge a fee (denominated in reserve asset).
*/
contract NavIssuanceModule is ModuleBase, ReentrancyGuard {
using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
using PreciseUnitMath for int256;
using ResourceIdentifier for IController;
using SafeMath for uint256;
using SafeCast for int256;
using SafeCast for uint256;
using SignedSafeMath for int256;
/* ============ Events ============ */
event SetTokenNAVIssued(
ISetToken indexed _setToken,
address _issuer,
address _to,
address _reserveAsset,
address _hookContract,
uint256 _setTokenQuantity,
uint256 _managerFee,
uint256 _premium
);
event SetTokenNAVRedeemed(
ISetToken indexed _setToken,
address _redeemer,
address _to,
address _reserveAsset,
address _hookContract,
uint256 _setTokenQuantity,
uint256 _managerFee,
uint256 _premium
);
event ReserveAssetAdded(
ISetToken indexed _setToken,
address _newReserveAsset
);
event ReserveAssetRemoved(
ISetToken indexed _setToken,
address _removedReserveAsset
);
event PremiumEdited(
ISetToken indexed _setToken,
uint256 _newPremium
);
event ManagerFeeEdited(
ISetToken indexed _setToken,
uint256 _newManagerFee,
uint256 _index
);
event FeeRecipientEdited(
ISetToken indexed _setToken,
address _feeRecipient
);
/* ============ Structs ============ */
struct NAVIssuanceSettings {
INAVIssuanceHook managerIssuanceHook; // Issuance hook configurations
INAVIssuanceHook managerRedemptionHook; // Redemption hook configurations
address[] reserveAssets; // Allowed reserve assets - Must have a price enabled with the price oracle
address feeRecipient; // Manager fee recipient
uint256[2] managerFees; // Manager fees. 0 index is issue and 1 index is redeem fee (0.01% = 1e14, 1% = 1e16)
uint256 maxManagerFee; // Maximum fee manager is allowed to set for issue and redeem
uint256 premiumPercentage; // Premium percentage (0.01% = 1e14, 1% = 1e16). This premium is a buffer around oracle
// prices paid by user to the SetToken, which prevents arbitrage and oracle front running
uint256 maxPremiumPercentage; // Maximum premium percentage manager is allowed to set (configured by manager)
uint256 minSetTokenSupply; // Minimum SetToken supply required for issuance and redemption
// to prevent dramatic inflationary changes to the SetToken's position multiplier
}
struct ActionInfo {
uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity
// During redeem, represents post-premium value
uint256 protocolFees; // Total protocol fees (direct + manager revenue share)
uint256 managerFee; // Total manager fee paid in reserve asset
uint256 netFlowQuantity; // When issuing, quantity of reserve asset sent to SetToken
// When redeeming, quantity of reserve asset sent to redeemer
uint256 setTokenQuantity; // When issuing, quantity of SetTokens minted to mintee
// When redeeming, quantity of SetToken redeemed
uint256 previousSetTokenSupply; // SetToken supply prior to issue/redeem action
uint256 newSetTokenSupply; // SetToken supply after issue/redeem action
int256 newPositionMultiplier; // SetToken position multiplier after issue/redeem
uint256 newReservePositionUnit; // SetToken reserve asset position unit after issue/redeem
}
/* ============ State Variables ============ */
// Wrapped ETH address
IWETH public immutable weth;
// Mapping of SetToken to NAV issuance settings struct
mapping(ISetToken => NAVIssuanceSettings) public navIssuanceSettings;
// Mapping to efficiently check a SetToken's reserve asset validity
// SetToken => reserveAsset => isReserveAsset
mapping(ISetToken => mapping(address => bool)) public isReserveAsset;
/* ============ Constants ============ */
// 0 index stores the manager fee in managerFees array, percentage charged on issue (denominated in reserve asset)
uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0;
// 1 index stores the manager fee percentage in managerFees array, charged on redeem
uint256 constant internal MANAGER_REDEEM_FEE_INDEX = 1;
// 0 index stores the manager revenue share protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0;
// 1 index stores the manager revenue share protocol fee % on the controller, charged in the redeem function
uint256 constant internal PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX = 1;
// 2 index stores the direct protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2;
// 3 index stores the direct protocol fee % on the controller, charged in the redeem function
uint256 constant internal PROTOCOL_REDEEM_DIRECT_FEE_INDEX = 3;
/* ============ Constructor ============ */
/**
* @param _controller Address of controller contract
* @param _weth Address of wrapped eth
*/
constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) {
weth = _weth;
}
/* ============ External Functions ============ */
/**
* Deposits the allowed reserve asset into the SetToken and mints the appropriate % of Net Asset Value of the SetToken
* to the specified _to address.
*
* @param _setToken Instance of the SetToken contract
* @param _reserveAsset Address of the reserve asset to issue with
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
* @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance
* @param _to Address to mint SetToken to
*/
function issue(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
uint256 _minSetTokenReceiveQuantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, _reserveAsset, _reserveAssetQuantity);
_callPreIssueHooks(_setToken, _reserveAsset, _reserveAssetQuantity, msg.sender, _to);
ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, _reserveAsset, _reserveAssetQuantity);
_validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo);
_transferCollateralAndHandleFees(_setToken, IERC20(_reserveAsset), issueInfo);
_handleIssueStateUpdates(_setToken, _reserveAsset, _to, issueInfo);
}
/**
* Wraps ETH and deposits WETH if allowed into the SetToken and mints the appropriate % of Net Asset Value of the SetToken
* to the specified _to address.
*
* @param _setToken Instance of the SetToken contract
* @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance
* @param _to Address to mint SetToken to
*/
function issueWithEther(
ISetToken _setToken,
uint256 _minSetTokenReceiveQuantity,
address _to
)
external
payable
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
weth.deposit{ value: msg.value }();
_validateCommon(_setToken, address(weth), msg.value);
_callPreIssueHooks(_setToken, address(weth), msg.value, msg.sender, _to);
ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, address(weth), msg.value);
_validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo);
_transferWETHAndHandleFees(_setToken, issueInfo);
_handleIssueStateUpdates(_setToken, address(weth), _to, issueInfo);
}
/**
* Redeems a SetToken into a valid reserve asset representing the appropriate % of Net Asset Value of the SetToken
* to the specified _to address. Only valid if there are available reserve units on the SetToken.
*
* @param _setToken Instance of the SetToken contract
* @param _reserveAsset Address of the reserve asset to redeem with
* @param _setTokenQuantity Quantity of SetTokens to redeem
* @param _minReserveReceiveQuantity Min quantity of reserve asset to receive
* @param _to Address to redeem reserve asset to
*/
function redeem(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity,
uint256 _minReserveReceiveQuantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, _reserveAsset, _setTokenQuantity);
_callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to);
ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, _reserveAsset, _setTokenQuantity);
_validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo);
_setToken.burn(msg.sender, _setTokenQuantity);
// Instruct the SetToken to transfer the reserve asset back to the user
_setToken.strictInvokeTransfer(
_reserveAsset,
_to,
redeemInfo.netFlowQuantity
);
_handleRedemptionFees(_setToken, _reserveAsset, redeemInfo);
_handleRedeemStateUpdates(_setToken, _reserveAsset, _to, redeemInfo);
}
/**
* Redeems a SetToken into Ether (if WETH is valid) representing the appropriate % of Net Asset Value of the SetToken
* to the specified _to address. Only valid if there are available WETH units on the SetToken.
*
* @param _setToken Instance of the SetToken contract
* @param _setTokenQuantity Quantity of SetTokens to redeem
* @param _minReserveReceiveQuantity Min quantity of reserve asset to receive
* @param _to Address to redeem reserve asset to
*/
function redeemIntoEther(
ISetToken _setToken,
uint256 _setTokenQuantity,
uint256 _minReserveReceiveQuantity,
address payable _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, address(weth), _setTokenQuantity);
_callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to);
ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, address(weth), _setTokenQuantity);
_validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo);
_setToken.burn(msg.sender, _setTokenQuantity);
// Instruct the SetToken to transfer WETH from SetToken to module
_setToken.strictInvokeTransfer(
address(weth),
address(this),
redeemInfo.netFlowQuantity
);
weth.withdraw(redeemInfo.netFlowQuantity);
_to.transfer(redeemInfo.netFlowQuantity);
_handleRedemptionFees(_setToken, address(weth), redeemInfo);
_handleRedeemStateUpdates(_setToken, address(weth), _to, redeemInfo);
}
/**
* SET MANAGER ONLY. Add an allowed reserve asset
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset to add
*/
function addReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) {
require(!isReserveAsset[_setToken][_reserveAsset], "Reserve asset already exists");
navIssuanceSettings[_setToken].reserveAssets.push(_reserveAsset);
isReserveAsset[_setToken][_reserveAsset] = true;
emit ReserveAssetAdded(_setToken, _reserveAsset);
}
/**
* SET MANAGER ONLY. Remove a reserve asset
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset to remove
*/
function removeReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) {
require(isReserveAsset[_setToken][_reserveAsset], "Reserve asset does not exist");
navIssuanceSettings[_setToken].reserveAssets = navIssuanceSettings[_setToken].reserveAssets.remove(_reserveAsset);
delete isReserveAsset[_setToken][_reserveAsset];
emit ReserveAssetRemoved(_setToken, _reserveAsset);
}
/**
* SET MANAGER ONLY. Edit the premium percentage
*
* @param _setToken Instance of the SetToken
* @param _premiumPercentage Premium percentage in 10e16 (e.g. 10e16 = 1%)
*/
function editPremium(ISetToken _setToken, uint256 _premiumPercentage) external onlyManagerAndValidSet(_setToken) {
require(_premiumPercentage <= navIssuanceSettings[_setToken].maxPremiumPercentage, "Premium must be less than maximum allowed");
navIssuanceSettings[_setToken].premiumPercentage = _premiumPercentage;
emit PremiumEdited(_setToken, _premiumPercentage);
}
/**
* SET MANAGER ONLY. Edit manager fee
*
* @param _setToken Instance of the SetToken
* @param _managerFeePercentage Manager fee percentage in 10e16 (e.g. 10e16 = 1%)
* @param _managerFeeIndex Manager fee index. 0 index is issue fee, 1 index is redeem fee
*/
function editManagerFee(
ISetToken _setToken,
uint256 _managerFeePercentage,
uint256 _managerFeeIndex
)
external
onlyManagerAndValidSet(_setToken)
{
require(_managerFeePercentage <= navIssuanceSettings[_setToken].maxManagerFee, "Manager fee must be less than maximum allowed");
navIssuanceSettings[_setToken].managerFees[_managerFeeIndex] = _managerFeePercentage;
emit ManagerFeeEdited(_setToken, _managerFeePercentage, _managerFeeIndex);
}
/**
* SET MANAGER ONLY. Edit the manager fee recipient
*
* @param _setToken Instance of the SetToken
* @param _managerFeeRecipient Manager fee recipient
*/
function editFeeRecipient(ISetToken _setToken, address _managerFeeRecipient) external onlyManagerAndValidSet(_setToken) {
require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address");
navIssuanceSettings[_setToken].feeRecipient = _managerFeeRecipient;
emit FeeRecipientEdited(_setToken, _managerFeeRecipient);
}
/**
* SET MANAGER ONLY. Initializes this module to the SetToken with hooks, allowed reserve assets,
* fees and issuance premium. Only callable by the SetToken's manager. Hook addresses are optional.
* Address(0) means that no hook will be called.
*
* @param _setToken Instance of the SetToken to issue
* @param _navIssuanceSettings NAVIssuanceSettings struct defining parameters
*/
function initialize(
ISetToken _setToken,
NAVIssuanceSettings memory _navIssuanceSettings
)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_navIssuanceSettings.reserveAssets.length > 0, "Reserve assets must be greater than 0");
require(_navIssuanceSettings.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%");
require(_navIssuanceSettings.maxPremiumPercentage < PreciseUnitMath.preciseUnit(), "Max premium percentage must be less than 100%");
require(_navIssuanceSettings.managerFees[0] <= _navIssuanceSettings.maxManagerFee, "Manager issue fee must be less than max");
require(_navIssuanceSettings.managerFees[1] <= _navIssuanceSettings.maxManagerFee, "Manager redeem fee must be less than max");
require(_navIssuanceSettings.premiumPercentage <= _navIssuanceSettings.maxPremiumPercentage, "Premium must be less than max");
require(_navIssuanceSettings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
// Initial mint of Set cannot use NAVIssuance since minSetTokenSupply must be > 0
require(_navIssuanceSettings.minSetTokenSupply > 0, "Min SetToken supply must be greater than 0");
for (uint256 i = 0; i < _navIssuanceSettings.reserveAssets.length; i++) {
require(!isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]], "Reserve assets must be unique");
isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]] = true;
}
navIssuanceSettings[_setToken] = _navIssuanceSettings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Issuance settings and
* reserve asset states are deleted.
*/
function removeModule() external override {
ISetToken setToken = ISetToken(msg.sender);
for (uint256 i = 0; i < navIssuanceSettings[setToken].reserveAssets.length; i++) {
delete isReserveAsset[setToken][navIssuanceSettings[setToken].reserveAssets[i]];
}
delete navIssuanceSettings[setToken];
}
receive() external payable {}
/* ============ External Getter Functions ============ */
function getReserveAssets(ISetToken _setToken) external view returns (address[] memory) {
return navIssuanceSettings[_setToken].reserveAssets;
}
function getIssuePremium(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (uint256)
{
return _getIssuePremium(_setToken, _reserveAsset, _reserveAssetQuantity);
}
function getRedeemPremium(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (uint256)
{
return _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity);
}
function getManagerFee(ISetToken _setToken, uint256 _managerFeeIndex) external view returns (uint256) {
return navIssuanceSettings[_setToken].managerFees[_managerFeeIndex];
}
/**
* Get the expected SetTokens minted to recipient on issuance
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
*
* @return uint256 Expected SetTokens to be minted to recipient
*/
function getExpectedSetTokenIssueQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (uint256)
{
(,, uint256 netReserveFlow) = _getFees(
_setToken,
_reserveAssetQuantity,
PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_ISSUE_DIRECT_FEE_INDEX,
MANAGER_ISSUE_FEE_INDEX
);
uint256 setTotalSupply = _setToken.totalSupply();
return _getSetTokenMintQuantity(
_setToken,
_reserveAsset,
netReserveFlow,
setTotalSupply
);
}
/**
* Get the expected reserve asset to be redeemed
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _setTokenQuantity Quantity of SetTokens to redeem
*
* @return uint256 Expected reserve asset quantity redeemed
*/
function getExpectedReserveRedeemQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (uint256)
{
uint256 preFeeReserveQuantity = _getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(,, uint256 netReserveFlows) = _getFees(
_setToken,
preFeeReserveQuantity,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
return netReserveFlows;
}
/**
* Checks if issue is valid
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
*
* @return bool Returns true if issue is valid
*/
function isIssueValid(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (bool)
{
uint256 setTotalSupply = _setToken.totalSupply();
return _reserveAssetQuantity != 0
&& isReserveAsset[_setToken][_reserveAsset]
&& setTotalSupply >= navIssuanceSettings[_setToken].minSetTokenSupply;
}
/**
* Checks if redeem is valid
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _setTokenQuantity Quantity of SetTokens to redeem
*
* @return bool Returns true if redeem is valid
*/
function isRedeemValid(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (bool)
{
uint256 setTotalSupply = _setToken.totalSupply();
if (
_setTokenQuantity == 0
|| !isReserveAsset[_setToken][_reserveAsset]
|| setTotalSupply < navIssuanceSettings[_setToken].minSetTokenSupply.add(_setTokenQuantity)
) {
return false;
} else {
uint256 totalRedeemValue =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(,, uint256 expectedRedeemQuantity) = _getFees(
_setToken,
totalRedeemValue,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
return existingUnit.preciseMul(setTotalSupply) >= expectedRedeemQuantity;
}
}
/* ============ Internal Functions ============ */
function _validateCommon(ISetToken _setToken, address _reserveAsset, uint256 _quantity) internal view {
require(_quantity > 0, "Quantity must be > 0");
require(isReserveAsset[_setToken][_reserveAsset], "Must be valid reserve asset");
}
function _validateIssuanceInfo(ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, ActionInfo memory _issueInfo) internal view {
// Check that total supply is greater than min supply needed for issuance
// Note: A min supply amount is needed to avoid division by 0 when SetToken supply is 0
require(
_issueInfo.previousSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply,
"Supply must be greater than minimum to enable issuance"
);
require(_issueInfo.setTokenQuantity >= _minSetTokenReceiveQuantity, "Must be greater than min SetToken");
}
function _validateRedemptionInfo(
ISetToken _setToken,
uint256 _minReserveReceiveQuantity,
uint256 _setTokenQuantity,
ActionInfo memory _redeemInfo
)
internal
view
{
// Check that new supply is more than min supply needed for redemption
// Note: A min supply amount is needed to avoid division by 0 when redeeming SetToken to 0
require(
_redeemInfo.newSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply,
"Supply must be greater than minimum to enable redemption"
);
require(_redeemInfo.netFlowQuantity >= _minReserveReceiveQuantity, "Must be greater than min receive reserve quantity");
}
function _createIssuanceInfo(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
internal
view
returns (ActionInfo memory)
{
ActionInfo memory issueInfo;
issueInfo.previousSetTokenSupply = _setToken.totalSupply();
issueInfo.preFeeReserveQuantity = _reserveAssetQuantity;
(issueInfo.protocolFees, issueInfo.managerFee, issueInfo.netFlowQuantity) = _getFees(
_setToken,
issueInfo.preFeeReserveQuantity,
PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_ISSUE_DIRECT_FEE_INDEX,
MANAGER_ISSUE_FEE_INDEX
);
issueInfo.setTokenQuantity = _getSetTokenMintQuantity(
_setToken,
_reserveAsset,
issueInfo.netFlowQuantity,
issueInfo.previousSetTokenSupply
);
(issueInfo.newSetTokenSupply, issueInfo.newPositionMultiplier) = _getIssuePositionMultiplier(_setToken, issueInfo);
issueInfo.newReservePositionUnit = _getIssuePositionUnit(_setToken, _reserveAsset, issueInfo);
return issueInfo;
}
function _createRedemptionInfo(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
internal
view
returns (ActionInfo memory)
{
ActionInfo memory redeemInfo;
redeemInfo.setTokenQuantity = _setTokenQuantity;
redeemInfo.preFeeReserveQuantity =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(redeemInfo.protocolFees, redeemInfo.managerFee, redeemInfo.netFlowQuantity) = _getFees(
_setToken,
redeemInfo.preFeeReserveQuantity,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
redeemInfo.previousSetTokenSupply = _setToken.totalSupply();
(redeemInfo.newSetTokenSupply, redeemInfo.newPositionMultiplier) = _getRedeemPositionMultiplier(_setToken, _setTokenQuantity, redeemInfo);
redeemInfo.newReservePositionUnit = _getRedeemPositionUnit(_setToken, _reserveAsset, redeemInfo);
return redeemInfo;
}
/**
* Transfer reserve asset from user to SetToken and fees from user to appropriate fee recipients
*/
function _transferCollateralAndHandleFees(ISetToken _setToken, IERC20 _reserveAsset, ActionInfo memory _issueInfo) internal {
transferFrom(_reserveAsset, msg.sender, address(_setToken), _issueInfo.netFlowQuantity);
if (_issueInfo.protocolFees > 0) {
transferFrom(_reserveAsset, msg.sender, controller.feeRecipient(), _issueInfo.protocolFees);
}
if (_issueInfo.managerFee > 0) {
transferFrom(_reserveAsset, msg.sender, navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee);
}
}
/**
* Transfer WETH from module to SetToken and fees from module to appropriate fee recipients
*/
function _transferWETHAndHandleFees(ISetToken _setToken, ActionInfo memory _issueInfo) internal {
weth.transfer(address(_setToken), _issueInfo.netFlowQuantity);
if (_issueInfo.protocolFees > 0) {
weth.transfer(controller.feeRecipient(), _issueInfo.protocolFees);
}
if (_issueInfo.managerFee > 0) {
weth.transfer(navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee);
}
}
function _handleIssueStateUpdates(
ISetToken _setToken,
address _reserveAsset,
address _to,
ActionInfo memory _issueInfo
)
internal
{
_setToken.editPositionMultiplier(_issueInfo.newPositionMultiplier);
_setToken.editDefaultPosition(_reserveAsset, _issueInfo.newReservePositionUnit);
_setToken.mint(_to, _issueInfo.setTokenQuantity);
emit SetTokenNAVIssued(
_setToken,
msg.sender,
_to,
_reserveAsset,
address(navIssuanceSettings[_setToken].managerIssuanceHook),
_issueInfo.setTokenQuantity,
_issueInfo.managerFee,
_issueInfo.protocolFees
);
}
function _handleRedeemStateUpdates(
ISetToken _setToken,
address _reserveAsset,
address _to,
ActionInfo memory _redeemInfo
)
internal
{
_setToken.editPositionMultiplier(_redeemInfo.newPositionMultiplier);
_setToken.editDefaultPosition(_reserveAsset, _redeemInfo.newReservePositionUnit);
emit SetTokenNAVRedeemed(
_setToken,
msg.sender,
_to,
_reserveAsset,
address(navIssuanceSettings[_setToken].managerRedemptionHook),
_redeemInfo.setTokenQuantity,
_redeemInfo.managerFee,
_redeemInfo.protocolFees
);
}
function _handleRedemptionFees(ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo) internal {
// Instruct the SetToken to transfer protocol fee to fee recipient if there is a fee
payProtocolFeeFromSetToken(_setToken, _reserveAsset, _redeemInfo.protocolFees);
// Instruct the SetToken to transfer manager fee to manager fee recipient if there is a fee
if (_redeemInfo.managerFee > 0) {
_setToken.strictInvokeTransfer(
_reserveAsset,
navIssuanceSettings[_setToken].feeRecipient,
_redeemInfo.managerFee
);
}
}
/**
* Returns the issue premium percentage. Virtual function that can be overridden in future versions of the module
* and can contain arbitrary logic to calculate the issuance premium.
*/
function _getIssuePremium(
ISetToken _setToken,
address /* _reserveAsset */,
uint256 /* _reserveAssetQuantity */
)
virtual
internal
view
returns (uint256)
{
return navIssuanceSettings[_setToken].premiumPercentage;
}
/**
* Returns the redeem premium percentage. Virtual function that can be overridden in future versions of the module
* and can contain arbitrary logic to calculate the redemption premium.
*/
function _getRedeemPremium(
ISetToken _setToken,
address /* _reserveAsset */,
uint256 /* _setTokenQuantity */
)
virtual
internal
view
returns (uint256)
{
return navIssuanceSettings[_setToken].premiumPercentage;
}
/**
* Returns the fees attributed to the manager and the protocol. The fees are calculated as follows:
*
* ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity
* Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity
*
* @param _setToken Instance of the SetToken
* @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from
* @param _protocolManagerFeeIndex Index to pull rev share NAV Issuance fee from the Controller
* @param _protocolDirectFeeIndex Index to pull direct NAV issuance fee from the Controller
* @param _managerFeeIndex Index from NAVIssuanceSettings (0 = issue fee, 1 = redeem fee)
*
* @return uint256 Fees paid to the protocol in reserve asset
* @return uint256 Fees paid to the manager in reserve asset
* @return uint256 Net reserve to user net of fees
*/
function _getFees(
ISetToken _setToken,
uint256 _reserveAssetQuantity,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns (uint256, uint256, uint256)
{
(uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages(
_setToken,
_protocolManagerFeeIndex,
_protocolDirectFeeIndex,
_managerFeeIndex
);
// Calculate total notional fees
uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity);
uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity);
uint256 netReserveFlow = _reserveAssetQuantity.sub(protocolFees).sub(managerFee);
return (protocolFees, managerFee, netReserveFlow);
}
function _getProtocolAndManagerFeePercentages(
ISetToken _setToken,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns(uint256, uint256)
{
// Get protocol fee percentages
uint256 protocolDirectFeePercent = controller.getModuleFee(address(this), _protocolDirectFeeIndex);
uint256 protocolManagerShareFeePercent = controller.getModuleFee(address(this), _protocolManagerFeeIndex);
uint256 managerFeePercent = navIssuanceSettings[_setToken].managerFees[_managerFeeIndex];
// Calculate revenue share split percentage
uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent);
uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage);
uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent);
return (totalProtocolFeePercentage, managerRevenueSharePercentage);
}
function _getSetTokenMintQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _netReserveFlows, // Value of reserve asset net of fees
uint256 _setTotalSupply
)
internal
view
returns (uint256)
{
uint256 premiumPercentage = _getIssuePremium(_setToken, _reserveAsset, _netReserveFlows);
uint256 premiumValue = _netReserveFlows.preciseMul(premiumPercentage);
// Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (1e18)
// Reverts if price is not found
uint256 setTokenValuation = controller.getSetValuer().calculateSetTokenValuation(_setToken, _reserveAsset);
// Get reserve asset decimals
uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals();
uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals);
uint256 normalizedTotalReserveQuantityNetFeesAndPremium = _netReserveFlows.sub(premiumValue).preciseDiv(10 ** reserveAssetDecimals);
// Calculate SetTokens to mint to issuer
uint256 denominator = _setTotalSupply.preciseMul(setTokenValuation).add(normalizedTotalReserveQuantityNetFees).sub(normalizedTotalReserveQuantityNetFeesAndPremium);
return normalizedTotalReserveQuantityNetFeesAndPremium.preciseMul(_setTotalSupply).preciseDiv(denominator);
}
function _getRedeemReserveQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
internal
view
returns (uint256)
{
// Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (10e18)
// Reverts if price is not found
uint256 setTokenValuation = controller.getSetValuer().calculateSetTokenValuation(_setToken, _reserveAsset);
uint256 totalRedeemValueInPreciseUnits = _setTokenQuantity.preciseMul(setTokenValuation);
// Get reserve asset decimals
uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals();
uint256 prePremiumReserveQuantity = totalRedeemValueInPreciseUnits.preciseMul(10 ** reserveAssetDecimals);
uint256 premiumPercentage = _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity);
uint256 premiumQuantity = prePremiumReserveQuantity.preciseMulCeil(premiumPercentage);
return prePremiumReserveQuantity.sub(premiumQuantity);
}
/**
* The new position multiplier is calculated as follows:
* inflationPercentage = (newSupply - oldSupply) / newSupply
* newMultiplier = (1 - inflationPercentage) * positionMultiplier
*/
function _getIssuePositionMultiplier(
ISetToken _setToken,
ActionInfo memory _issueInfo
)
internal
view
returns (uint256, int256)
{
// Calculate inflation and new position multiplier. Note: Round inflation up in order to round position multiplier down
uint256 newTotalSupply = _issueInfo.setTokenQuantity.add(_issueInfo.previousSetTokenSupply);
int256 newPositionMultiplier = _setToken.positionMultiplier()
.mul(_issueInfo.previousSetTokenSupply.toInt256())
.div(newTotalSupply.toInt256());
return (newTotalSupply, newPositionMultiplier);
}
/**
* Calculate deflation and new position multiplier. Note: Round deflation down in order to round position multiplier down
*
* The new position multiplier is calculated as follows:
* deflationPercentage = (oldSupply - newSupply) / newSupply
* newMultiplier = (1 + deflationPercentage) * positionMultiplier
*/
function _getRedeemPositionMultiplier(
ISetToken _setToken,
uint256 _setTokenQuantity,
ActionInfo memory _redeemInfo
)
internal
view
returns (uint256, int256)
{
uint256 newTotalSupply = _redeemInfo.previousSetTokenSupply.sub(_setTokenQuantity);
int256 newPositionMultiplier = _setToken.positionMultiplier()
.mul(_redeemInfo.previousSetTokenSupply.toInt256())
.div(newTotalSupply.toInt256());
return (newTotalSupply, newPositionMultiplier);
}
/**
* The new position reserve asset unit is calculated as follows:
* totalReserve = (oldUnit * oldSetTokenSupply) + reserveQuantity
* newUnit = totalReserve / newSetTokenSupply
*/
function _getIssuePositionUnit(
ISetToken _setToken,
address _reserveAsset,
ActionInfo memory _issueInfo
)
internal
view
returns (uint256)
{
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
uint256 totalReserve = existingUnit
.preciseMul(_issueInfo.previousSetTokenSupply)
.add(_issueInfo.netFlowQuantity);
return totalReserve.preciseDiv(_issueInfo.newSetTokenSupply);
}
/**
* The new position reserve asset unit is calculated as follows:
* totalReserve = (oldUnit * oldSetTokenSupply) - reserveQuantityToSendOut
* newUnit = totalReserve / newSetTokenSupply
*/
function _getRedeemPositionUnit(
ISetToken _setToken,
address _reserveAsset,
ActionInfo memory _redeemInfo
)
internal
view
returns (uint256)
{
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
uint256 totalExistingUnits = existingUnit.preciseMul(_redeemInfo.previousSetTokenSupply);
uint256 outflow = _redeemInfo.netFlowQuantity.add(_redeemInfo.protocolFees).add(_redeemInfo.managerFee);
// Require withdrawable quantity is greater than existing collateral
require(totalExistingUnits >= outflow, "Must be greater than total available collateral");
return totalExistingUnits.sub(outflow).preciseDiv(_redeemInfo.newSetTokenSupply);
}
/**
* If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic
* can contain arbitrary logic including validations, external function calls, etc.
*/
function _callPreIssueHooks(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
address _caller,
address _to
)
internal
{
INAVIssuanceHook preIssueHook = navIssuanceSettings[_setToken].managerIssuanceHook;
if (address(preIssueHook) != address(0)) {
preIssueHook.invokePreIssueHook(_setToken, _reserveAsset, _reserveAssetQuantity, _caller, _to);
}
}
/**
* If a pre-redeem hook has been configured, call the external-protocol contract.
*/
function _callPreRedeemHooks(ISetToken _setToken, uint256 _setQuantity, address _caller, address _to) internal {
INAVIssuanceHook preRedeemHook = navIssuanceSettings[_setToken].managerRedemptionHook;
if (address(preRedeemHook) != address(0)) {
preRedeemHook.invokePreRedeemHook(_setToken, _setQuantity, _caller, _to);
}
}
} | IPriceOracle Set Protocol Interface for interacting with PriceOracle/ | interface IPriceOracle {
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
Copyright 2020 Set Labs Inc.
pragma solidity 0.6.10;
}
| 101,164 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./lib/SafeMathInt.sol";
import "./lib/UInt256Lib.sol";
interface IUFragments {
function totalSupply() external view returns (uint256);
function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256);
}
interface IOracle {
function getData() external returns (uint256, bool);
}
/**
* @title uFragments Monetary Supply Policy
* @dev This is an implementation of the uFragments Ideal Money protocol.
* uFragments operates symmetrically on expansion and contraction. It will both split and
* combine coins to maintain a stable unit price.
*
* This component regulates the token supply of the uFragments ERC20 token in response to
* market oracles.
*/
contract UFragmentsPolicy is OwnableUpgradeable {
using SafeMath for uint256;
using SafeMathInt for int256;
using UInt256Lib for uint256;
event LogRebase(
uint256 indexed epoch,
uint256 exchangeRate,
uint256 cpi,
int256 requestedSupplyAdjustment,
uint256 timestampSec
);
IUFragments public uFrags;
// Provides the current CPI, as an 18 decimal fixed point number.
IOracle public cpiOracle;
// Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number.
// (eg) An oracle value of 1.5e18 it would mean 1 Ample is trading for $1.50.
IOracle public marketOracle;
// CPI value at the time of launch, as an 18 decimal fixed point number.
uint256 private baseCpi;
// If the current exchange rate is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the rate.
// (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change.
// DECIMALS Fixed point number.
uint256 public deviationThreshold;
// The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag
// Check setRebaseLag comments for more details.
// Natural number, no decimal places.
uint256 public rebaseLag;
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestampSec;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec;
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec;
// The number of rebase cycles since inception
uint256 public epoch;
uint256 private constant DECIMALS = 18;
// Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256.
// Both are 18 decimals fixed point numbers.
uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS;
// MAX_SUPPLY = MAX_INT256 / MAX_RATE
uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE;
// This module orchestrates the rebase execution and downstream notification.
address public orchestrator;
modifier onlyOrchestrator() {
require(msg.sender == orchestrator);
_;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase() external onlyOrchestrator {
require(inRebaseWindow());
// This comparison also ensures there is no reentrancy.
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < block.timestamp);
// Snap the rebase time to the start of this window.
lastRebaseTimestampSec = block.timestamp.sub(block.timestamp.mod(minRebaseTimeIntervalSec)).add(
rebaseWindowOffsetSec
);
epoch = epoch.add(1);
uint256 cpi;
bool cpiValid;
(cpi, cpiValid) = cpiOracle.getData();
require(cpiValid);
uint256 targetRate = cpi.mul(10**DECIMALS).div(baseCpi);
uint256 exchangeRate;
bool rateValid;
(exchangeRate, rateValid) = marketOracle.getData();
require(rateValid);
if (exchangeRate > MAX_RATE) {
exchangeRate = MAX_RATE;
}
int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate);
// Apply the Dampening factor.
supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe());
if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe();
}
uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, exchangeRate, cpi, supplyDelta, block.timestamp);
}
/**
* @notice Sets the reference to the CPI oracle.
* @param cpiOracle_ The address of the cpi oracle contract.
*/
function setCpiOracle(IOracle cpiOracle_) external onlyOwner {
cpiOracle = cpiOracle_;
}
/**
* @notice Sets the reference to the market oracle.
* @param marketOracle_ The address of the market oracle contract.
*/
function setMarketOracle(IOracle marketOracle_) external onlyOwner {
marketOracle = marketOracle_;
}
/**
* @notice Sets the reference to the orchestrator.
* @param orchestrator_ The address of the orchestrator contract.
*/
function setOrchestrator(address orchestrator_) external onlyOwner {
orchestrator = orchestrator_;
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetRate, then no supply
* modifications are made. DECIMALS fixed point number.
* @param deviationThreshold_ The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner {
deviationThreshold = deviationThreshold_;
}
/**
* @notice Sets the rebase lag parameter.
It is used to dampen the applied supply adjustment by 1 / rebaseLag
If the rebase lag R, equals 1, the smallest value for R, then the full supply
correction is applied on each rebase cycle.
If it is greater than 1, then a correction of 1/R of is applied on each rebase.
* @param rebaseLag_ The new rebase lag parameter.
*/
function setRebaseLag(uint256 rebaseLag_) external onlyOwner {
require(rebaseLag_ > 0);
rebaseLag = rebaseLag_;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase
* operations, in seconds.
* @param rebaseWindowOffsetSec_ The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param rebaseWindowLengthSec_ The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 minRebaseTimeIntervalSec_,
uint256 rebaseWindowOffsetSec_,
uint256 rebaseWindowLengthSec_
) external onlyOwner {
require(minRebaseTimeIntervalSec_ > 0);
require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_);
minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_;
rebaseWindowOffsetSec = rebaseWindowOffsetSec_;
rebaseWindowLengthSec = rebaseWindowLengthSec_;
}
/**
* @notice A multi-chain AMPL interface method. The Ampleforth monetary policy contract
* on the base-chain and XC-AmpleController contracts on the satellite-chains
* implement this method. It atomically returns two values:
* what the current contract believes to be,
* the globalAmpleforthEpoch and globalAMPLSupply.
* @return globalAmpleforthEpoch The current epoch number.
* @return globalAMPLSupply The total supply at the current epoch.
*/
function globalEpochAndAMPLSupply() external view returns (uint256, uint256) {
return (epoch, uFrags.totalSupply());
}
/**
* @dev ZOS upgradable contract initialization method.
* It is called at the time of contract creation to invoke parent class initializers and
* initialize the contract's state variables.
*/
function initialize(
address owner_,
IUFragments uFrags_,
uint256 baseCpi_
) public initializer {
__Ownable_init();
transferOwnership(owner_);
// deviationThreshold = 0.04e18 = 4e16
deviationThreshold = 4 * 10**(DECIMALS - 2);
rebaseLag = 30;
minRebaseTimeIntervalSec = 1 days;
rebaseWindowOffsetSec = 64800; // 6PM UTC
rebaseWindowLengthSec = 45 minutes;
lastRebaseTimestampSec = 0;
epoch = 0;
uFrags = uFrags_;
baseCpi = baseCpi_;
}
/**
* @return If the latest block timestamp is within the rebase time window it, returns true.
* Otherwise, returns false.
*/
function inRebaseWindow() public view returns (bool) {
return (block.timestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec &&
block.timestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)));
}
/**
* @return Computes the total supply adjustment in response to the exchange rate
* and the targetRate.
*/
function computeSupplyDelta(uint256 rate, uint256 targetRate) internal view returns (int256) {
if (withinDeviationThreshold(rate, targetRate)) {
return 0;
}
// supplyDelta = totalSupply * (rate - targetRate) / targetRate
int256 targetRateSigned = targetRate.toInt256Safe();
return
uFrags.totalSupply().toInt256Safe().mul(rate.toInt256Safe().sub(targetRateSigned)).div(
targetRateSigned
);
}
/**
* @param rate The current exchange rate, an 18 decimal fixed point number.
* @param targetRate The target exchange rate, an 18 decimal fixed point number.
* @return If the rate is within the deviation threshold from the target rate, returns true.
* Otherwise, returns false.
*/
function withinDeviationThreshold(uint256 rate, uint256 targetRate)
internal
view
returns (bool)
{
uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold).div(10**DECIMALS);
return
(rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) ||
(rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
}
}
| Sets the deviation threshold fraction. If the exchange rate given by the market oracle is within this fractional distance from the targetRate, then no supply modifications are made. DECIMALS fixed point number. deviationThreshold_ The new exchange rate threshold fraction./ | function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner {
deviationThreshold = deviationThreshold_;
}
If the rebase lag R, equals 1, the smallest value for R, then the full supply
correction is applied on each rebase cycle.
If it is greater than 1, then a correction of 1/R of is applied on each rebase.
| 12,653,209 |
/**
* @title -FoMo-3D v0.7.1
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ .--,-``-.
*========,---,.======================____==========================/ / '.=======,---,====*
* ,' .' | ,' , `. / ../ ; .' .' `\
* ,---.' | ,---. ,-+-,.' _ | ,---. \ ``\ .`- ' ,---.' \
* | | .' ' ,'\ ,-+-. ; , || ' ,'\ ,---,. \___\/ \ : | | .`\ |
* : : : / / | ,--.'|' | || / / | ,' .' | \ : | : : | ' |
* : | |-, . ; ,. : | | ,', | |, . ; ,. : ,---.' | / / / | ' ' ; :
* | : ;/| ' | |: : | | / | |--' ' | |: : | | .' \ \ \ ' | ; . |
* | | .' ' | .; : | : | | , ' | .; : : |.' ___ / : | | | : | '
* ' : ' | : | | : | |/ | : | `---' / /\ / : ' : | / ;
* | | | \ \ / | | |`-' \ \ / / ,,/ ',- . | | '` ,/
* | : \ `----' | ;/ `----' \ ''\ ; ; : .'
*====| | ,'=============='---'==========(long version)===========\ \ .'===| ,.'======*
* `----' `--`-,,-' '---'
* ╔═╗┌─┐┌─┐┬┌─┐┬┌─┐┬ ┌─────────────────────────┐ ╦ ╦┌─┐┌┐ ╔═╗┬┌┬┐┌─┐
* ║ ║├┤ ├┤ ││ │├─┤│ │ https://exitscam.me │ ║║║├┤ ├┴┐╚═╗│ │ ├┤
* ╚═╝└ └ ┴└─┘┴┴ ┴┴─┘ └─┬─────────────────────┬─┘ ╚╩╝└─┘└─┘╚═╝┴ ┴ └─┘
* ┌────────────────────────────────┘ └──────────────────────────────┐
* │╔═╗┌─┐┬ ┬┌┬┐┬┌┬┐┬ ┬ ╔╦╗┌─┐┌─┐┬┌─┐┌┐┌ ╦┌┐┌┌┬┐┌─┐┬─┐┌─┐┌─┐┌─┐┌─┐ ╔═╗┌┬┐┌─┐┌─┐┬┌─│
* │╚═╗│ ││ │ │││ │ └┬┘ ═ ║║├┤ └─┐││ ┬│││ ═ ║│││ │ ├┤ ├┬┘├┤ ├─┤│ ├┤ ═ ╚═╗ │ ├─┤│ ├┴┐│
* │╚═╝└─┘┴─┘┴─┴┘┴ ┴ ┴ ═╩╝└─┘└─┘┴└─┘┘└┘ ╩┘└┘ ┴ └─┘┴└─└ ┴ ┴└─┘└─┘ ╚═╝ ┴ ┴ ┴└─┘┴ ┴│
* │ ┌──────────┐ ┌───────┐ ┌─────────┐ ┌────────┐ │
* └────┤ Inventor ├───────────┤ Justo ├────────────┤ Sumpunk ├──────────────┤ Mantso ├──┘
* └──────────┘ └───────┘ └─────────┘ └────────┘
* ┌─────────────────────────────────────────────────────────┐ ╔╦╗┬ ┬┌─┐┌┐┌┬┌─┌─┐ ╔╦╗┌─┐
* │ Ambius, Aritz Cracker, Cryptoknight, Crypto McPump, │ ║ ├─┤├─┤│││├┴┐└─┐ ║ │ │
* │ Capex, JogFera, The Shocker, Daok, Randazzz, PumpRabbi, │ ╩ ┴ ┴┴ ┴┘└┘┴ ┴└─┘ ╩ └─┘
* │ Kadaz, Incognito Jo, Lil Stronghands, Ninja Turtle, └───────────────────────────┐
* │ Psaints, Satoshi, Vitalik, Nano 2nd, Bogdanoffs Isaac Newton, Nikola Tesla, │
* │ Le Comte De Saint Germain, Albert Einstein, Socrates, & all the volunteer moderator │
* │ & support staff, content, creators, autonomous agents, and indie devs for P3D. │
* │ Without your help, we wouldn't have the time to code this. │
* └─────────────────────────────────────────────────────────────────────────────────────┘
*
* This product is protected under license. Any unauthorized copy, modification, or use without
* express written consent from the creators is prohibited.
*
* WARNING: THIS PRODUCT IS HIGHLY ADDICTIVE. IF YOU HAVE AN ADDICTIVE NATURE. DO NOT PLAY.
*/
//==============================================================================
/*
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
contract F3Devents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
//==============================================================================
// _ _ _ _|_ _ _ __|_ _ _ _|_ _ .
// (_(_)| | | | (_|(_ | _\(/_ | |_||_) .
//====================================|=========================================
contract modularLong is F3Devents {}
contract FoMo3Dlong is modularLong {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcLong for uint256;
otherFoMo3D private otherF3D_;
DiviesInterface constant private Divies = DiviesInterface(0xc7029Ed9EBa97A096e72607f4340c34049C7AF48);
JIincForwarderInterface constant private Jekyll_Island_Inc = JIincForwarderInterface(0xdd4950F977EE28D2C132f1353D1595035Db444EE);
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xD60d353610D9a5Ca478769D371b53CEfAA7B6E4c);
F3DexternalSettingsInterface constant private extSettings = F3DexternalSettingsInterface(0x32967D6c142c2F38AB39235994e2DDF11c37d590);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "FoMo3D Long Official";
string constant public symbol = "F3D";
uint256 private rndExtra_ = extSettings.getLongExtra(); // length of the very first ICO
uint256 private rndGap_ = extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 1 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (F3D, P3D) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = F3Ddatasets.TeamFee(30,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[1] = F3Ddatasets.TeamFee(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[2] = F3Ddatasets.TeamFee(56,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[3] = F3Ddatasets.TeamFee(43,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
// how to split up the final pot based on which team was picked
// (F3D, P3D)
potSplit_[0] = F3Ddatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com
potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com
potSplit_[2] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com
potSplit_[3] = F3Ddatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
*
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
**
* @dev receives name/player info from names contract
*
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
**
* @dev receives entire player name list
*
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
**
* @dev ends the round. manages paying out winner/splitting up pot
*
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _p3d.add(_com);
_com = 0;
}
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// send share for p3d to divies
if (_p3d > 0)
Divies.deposit.value(_p3d)();
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
**
* @dev updates round timer based on number of whole keys bought.
*
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
**
* @dev distributes eth based on fees to com, aff, and p3d
*
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// pay 2% out to community rewards
uint256 _com = _eth / 50;
uint256 _p3d;
if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _com;
_com = 0;
}
// pay 1% out to FoMo3D short
uint256 _long = _eth / 100;
otherF3D_.potSwap.value(_long)();
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
// pay out p3d
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
// deposit to divies contract
Divies.deposit.value(_p3d)();
// set up event data
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
**
* @dev distributes eth based on fees to gen and pot
*
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
**
* @dev prepares compression data and fires event for buy or reload tx's
*
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(
msg.sender == 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C ||
msg.sender == 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D ||
msg.sender == 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53 ||
msg.sender == 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C ||
msg.sender == 0xF39e044e1AB204460e06E87c6dca2c6319fC69E3,
"only team just can activate"
);
// make sure that its been linked.
require(address(otherF3D_) != address(0), "must link to other FoMo3D first");
// can only be ran once
require(activated_ == false, "fomo3d already activated");
// activate the contract
activated_ = true;
lala lala
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
function setOtherFomo(address _otherF3D)
public
{
// only team just can activate
require(
msg.sender == 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C ||
msg.sender == 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D ||
msg.sender == 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53 ||
msg.sender == 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C ||
msg.sender == 0xF39e044e1AB204460e06E87c6dca2c6319fC69E3,
"only team just can activate"
);
// make sure that it HASNT yet been linked.
require(address(otherF3D_) == address(0), "silly dev, you already did that");
// set up other fomo3d (fast or long) for pot swap
otherF3D_ = otherFoMo3D(_otherF3D);
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library F3Ddatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library F3DKeysCalcLong {
using SafeMath for *;
**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface otherFoMo3D {
function potSwap() external payable;
}
interface F3DexternalSettingsInterface {
function getFastGap() external returns(uint256);
function getLongGap() external returns(uint256);
function getFastExtra() external returns(uint256);
function getLongExtra() external returns(uint256);
}
interface DiviesInterface {
function deposit() external payable;
}
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
**
* @title -Name Filter- v0.1.9
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* _ __ _ ____ ____ _ _ _____ ____ ___
*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============*
*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============*
*
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*
library NameFilter {
**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*
library SafeMath {
**
* @dev Multiplies two numbers, throws on overflow.
*
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
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)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
**
* @dev Adds two numbers, throws on overflow.
*
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
**
* @dev gives square root of given x.
*
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
**
* @dev gives square. multiplies x by x
*
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
**
* @dev x to the power of y
*
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
*/
contract EtherTransferTo{
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
function () payable public {
// nothing to do!
}
function getBalance() public view returns (uint256) {
return address(this).balance;
}
function withdraw(uint amount) onlyOwner returns(bool) {
require(amount <= this.balance);
owner.transfer(amount);
return true;
}
} | setup local rID grab time | function getTimeLeft()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
| 1,605,098 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Payment.sol";
contract BeezToken is AccessControlEnumerable, ERC20{
constructor() ERC20('BEEZ', 'BEEZ') {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
//payment = Payment(msg.sender);
}
struct payback{
uint256 lastPaybackDate; //마지막 Payback날짜 체크
uint128 beezOfMonth; //이번달 충전 금액 //maxWonCharge - wonOfMonth[address] : 이번달 충전가능금액(charge.vue에 출력)
}
uint256 month = 1627743600; //매달 초기화(이달 1일을 나타냄)
uint8 decimals = 10**0; //decimals 10**18 X / 10**0 = etherscan, remix 보기 편함
uint8 incentiveRate = 100; //인센티브 비율
mapping (address => payback) paybackCheck; //주소 넣어서 인센티브 구조체 가져오는 매핑
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/******************************************************************************************************************/
/********사용자, 소상공인 MAIN화면 매달 초기화 함수(사용자 : 이달의 beez & 소상공인 : 토큰매출,이번달beez)********/
//매달 초기화 함수
function updateMonth(address _address, uint256 _date) private {
//금액 충전시 마지막으로 인센티브 충전된 날짜가 지난달인 경우 (block.timestamp >= month && =>이건 빼야됨)
if(paybackCheck[_address].lastPaybackDate < month){
paybackCheck[_address].beezOfMonth = 0; //인센티브 밸런스 초기화(여기서 이번에 충전된 )
}
//(나중에 다시 block.timestamp으로 수정)
paybackCheck[_address].lastPaybackDate = _date; //최근 인센티브 충전된 날짜 현재시간으로 업데이트
}
//매달 변경될때, aws람다를 사용해 백앤드에 요청을 보낸다. 요청받은 백앤드는 현재 시간(UNIX시간)을 setMonth에 입력
function setMonth(uint256 _month) external {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
month = _month;
}
function getMonth() external view returns (uint256) {
return month;
}
/******************************************************************************************************************/
/*********사용자, 소상공인 결재 / 사용자 리뷰페이백 / 소상공인 환전 함수***********/
//결제
function payment(address _sender, address _recipient, uint128 _wonAmount, uint128 _amount, uint256 _date) external virtual returns (bool){
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
updateMonth(_recipient, _date); //_date는 나중에 뺄꺼임. 이번달 첫 결재할 경우, 소상공인 incentiveCheck[_recipient].wonOfMonth 0으로 만들기 위해 //
_transfer(_sender, _recipient, _amount*decimals); //won 결제
paybackCheck[_recipient].beezOfMonth += _amount; //소상공인 (이번달)현금매출 증가
Payback(_sender, _wonAmount, _date);
return true;
}
//리뷰 페이백 external- 컨트랙트 바깥에서만 호출될 수 있고 컨트랙트 내의 다른 함수에서 호출 X(public과 동일)
function Payback(address _to, uint128 _amount, uint256 _date) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
updateMonth(_to, _date);
_mint(_to, (_amount/incentiveRate)*decimals); //payback 함수
paybackCheck[_to].beezOfMonth += _amount/incentiveRate;
}
//소상공인 환전 함수
function exchangeBurn(address _to, uint256 _amount) external {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_burn(_to, _amount*decimals);
}
/******************************************************************************************************************/
/*************************사용자, 소상공인 MAIN화면에 출력되는 비즈토큰 view 함수*********************************/
//보유 bz 확인
function balance(address _account) external view virtual returns(uint256) {
return balanceOf(_account);
}
//이달의 bz체크, 월 마다 리셋되야함
function balanceBeezOfMon (address _account) external view returns (uint128) {
if(paybackCheck[_account].lastPaybackDate < month){
return 0;
}
else{
return paybackCheck[_account].beezOfMonth;
}
}
/******************************************************************************************************************/
/***************************************************권한**********************************************************/
function addMinter(address _address) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role to addMinter");
_setupRole(MINTER_ROLE, _address);
}
} | 이달의 bz체크, 월 마다 리셋되야함 | function balanceBeezOfMon (address _account) external view returns (uint128) {
if(paybackCheck[_account].lastPaybackDate < month){
return 0;
}
else{
return paybackCheck[_account].beezOfMonth;
}
}
| 12,890,077 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "../Euler.sol";
import "../Storage.sol";
import "../modules/EToken.sol";
import "../modules/Markets.sol";
import "../BaseIRMLinearKink.sol";
import "../vendor/RPow.sol";
interface IExec {
function getPriceFull(address underlying) external view returns (uint twap, uint twapPeriod, uint currPrice);
function getPrice(address underlying) external view returns (uint twap, uint twapPeriod);
function detailedLiquidity(address account) external view returns (IRiskManager.AssetLiquidity[] memory assets);
function liquidity(address account) external view returns (IRiskManager.LiquidityStatus memory status);
}
contract EulerGeneralView is Constants {
bytes32 immutable public moduleGitCommit;
constructor(bytes32 moduleGitCommit_) {
moduleGitCommit = moduleGitCommit_;
}
// Query
struct Query {
address eulerContract;
address account;
address[] markets;
}
// Response
struct ResponseMarket {
// Universal
address underlying;
string name;
string symbol;
uint8 decimals;
address eTokenAddr;
address dTokenAddr;
address pTokenAddr;
Storage.AssetConfig config;
uint poolSize;
uint totalBalances;
uint totalBorrows;
uint reserveBalance;
uint32 reserveFee;
uint borrowAPY;
uint supplyAPY;
// Pricing
uint twap;
uint twapPeriod;
uint currPrice;
uint16 pricingType;
uint32 pricingParameters;
address pricingForwarded;
// Account specific
uint underlyingBalance;
uint eulerAllowance;
uint eTokenBalance;
uint eTokenBalanceUnderlying;
uint dTokenBalance;
IRiskManager.LiquidityStatus liquidityStatus;
}
struct Response {
uint timestamp;
uint blockNumber;
ResponseMarket[] markets;
address[] enteredMarkets;
}
// Implementation
function doQueryBatch(Query[] memory qs) external view returns (Response[] memory r) {
r = new Response[](qs.length);
for (uint i = 0; i < qs.length; ++i) {
r[i] = doQuery(qs[i]);
}
}
function doQuery(Query memory q) public view returns (Response memory r) {
r.timestamp = block.timestamp;
r.blockNumber = block.number;
Euler eulerProxy = Euler(q.eulerContract);
Markets marketsProxy = Markets(eulerProxy.moduleIdToProxy(MODULEID__MARKETS));
IExec execProxy = IExec(eulerProxy.moduleIdToProxy(MODULEID__EXEC));
IRiskManager.AssetLiquidity[] memory liqs;
if (q.account != address(0)) {
liqs = execProxy.detailedLiquidity(q.account);
}
r.markets = new ResponseMarket[](liqs.length + q.markets.length);
for (uint i = 0; i < liqs.length; ++i) {
ResponseMarket memory m = r.markets[i];
m.underlying = liqs[i].underlying;
m.liquidityStatus = liqs[i].status;
populateResponseMarket(q, m, marketsProxy, execProxy);
}
for (uint j = liqs.length; j < liqs.length + q.markets.length; ++j) {
uint i = j - liqs.length;
ResponseMarket memory m = r.markets[j];
m.underlying = q.markets[i];
populateResponseMarket(q, m, marketsProxy, execProxy);
}
if (q.account != address(0)) {
r.enteredMarkets = marketsProxy.getEnteredMarkets(q.account);
}
}
function populateResponseMarket(Query memory q, ResponseMarket memory m, Markets marketsProxy, IExec execProxy) private view {
m.name = getStringOrBytes32(m.underlying, IERC20.name.selector);
m.symbol = getStringOrBytes32(m.underlying, IERC20.symbol.selector);
m.decimals = IERC20(m.underlying).decimals();
m.eTokenAddr = marketsProxy.underlyingToEToken(m.underlying);
if (m.eTokenAddr == address(0)) return; // not activated
m.dTokenAddr = marketsProxy.eTokenToDToken(m.eTokenAddr);
m.pTokenAddr = marketsProxy.underlyingToPToken(m.underlying);
{
Storage.AssetConfig memory c = marketsProxy.underlyingToAssetConfig(m.underlying);
m.config = c;
}
m.poolSize = IERC20(m.underlying).balanceOf(q.eulerContract);
m.totalBalances = EToken(m.eTokenAddr).totalSupplyUnderlying();
m.totalBorrows = IERC20(m.dTokenAddr).totalSupply();
m.reserveBalance = EToken(m.eTokenAddr).reserveBalanceUnderlying();
m.reserveFee = marketsProxy.reserveFee(m.underlying);
{
uint borrowSPY = uint(int(marketsProxy.interestRate(m.underlying)));
(m.borrowAPY, m.supplyAPY) = computeAPYs(borrowSPY, m.totalBorrows, m.totalBalances, m.reserveFee);
}
(m.twap, m.twapPeriod, m.currPrice) = execProxy.getPriceFull(m.underlying);
(m.pricingType, m.pricingParameters, m.pricingForwarded) = marketsProxy.getPricingConfig(m.underlying);
if (q.account == address(0)) return;
m.underlyingBalance = IERC20(m.underlying).balanceOf(q.account);
m.eTokenBalance = IERC20(m.eTokenAddr).balanceOf(q.account);
m.eTokenBalanceUnderlying = EToken(m.eTokenAddr).balanceOfUnderlying(q.account);
m.dTokenBalance = IERC20(m.dTokenAddr).balanceOf(q.account);
m.eulerAllowance = IERC20(m.underlying).allowance(q.account, q.eulerContract);
}
function computeAPYs(uint borrowSPY, uint totalBorrows, uint totalBalancesUnderlying, uint32 reserveFee) public pure returns (uint borrowAPY, uint supplyAPY) {
borrowAPY = RPow.rpow(borrowSPY + 1e27, SECONDS_PER_YEAR, 10**27) - 1e27;
uint supplySPY = totalBalancesUnderlying == 0 ? 0 : borrowSPY * totalBorrows / totalBalancesUnderlying;
supplySPY = supplySPY * (RESERVE_FEE_SCALE - reserveFee) / RESERVE_FEE_SCALE;
supplyAPY = RPow.rpow(supplySPY + 1e27, SECONDS_PER_YEAR, 10**27) - 1e27;
}
// Interest rate model queries
struct QueryIRM {
address eulerContract;
address underlying;
}
struct ResponseIRM {
uint kink;
uint baseAPY;
uint kinkAPY;
uint maxAPY;
uint baseSupplyAPY;
uint kinkSupplyAPY;
uint maxSupplyAPY;
}
function doQueryIRM(QueryIRM memory q) external view returns (ResponseIRM memory r) {
Euler eulerProxy = Euler(q.eulerContract);
Markets marketsProxy = Markets(eulerProxy.moduleIdToProxy(MODULEID__MARKETS));
uint moduleId = marketsProxy.interestRateModel(q.underlying);
address moduleImpl = eulerProxy.moduleIdToImplementation(moduleId);
BaseIRMLinearKink irm = BaseIRMLinearKink(moduleImpl);
uint kink = r.kink = irm.kink();
uint32 reserveFee = marketsProxy.reserveFee(q.underlying);
uint baseSPY = irm.baseRate();
uint kinkSPY = baseSPY + (kink * irm.slope1());
uint maxSPY = kinkSPY + ((type(uint32).max - kink) * irm.slope2());
(r.baseAPY, r.baseSupplyAPY) = computeAPYs(baseSPY, 0, type(uint32).max, reserveFee);
(r.kinkAPY, r.kinkSupplyAPY) = computeAPYs(kinkSPY, kink, type(uint32).max, reserveFee);
(r.maxAPY, r.maxSupplyAPY) = computeAPYs(maxSPY, type(uint32).max, type(uint32).max, reserveFee);
}
// AccountLiquidity queries
struct ResponseAccountLiquidity {
IRiskManager.AssetLiquidity[] markets;
}
function doQueryAccountLiquidity(address eulerContract, address[] memory addrs) external view returns (ResponseAccountLiquidity[] memory r) {
Euler eulerProxy = Euler(eulerContract);
IExec execProxy = IExec(eulerProxy.moduleIdToProxy(MODULEID__EXEC));
r = new ResponseAccountLiquidity[](addrs.length);
for (uint i = 0; i < addrs.length; ++i) {
r[i].markets = execProxy.detailedLiquidity(addrs[i]);
}
}
// For tokens like MKR which return bytes32 on name() or symbol()
function getStringOrBytes32(address contractAddress, bytes4 selector) private view returns (string memory) {
(bool success, bytes memory result) = contractAddress.staticcall(abi.encodeWithSelector(selector));
if (!success) return "";
return result.length == 32 ? string(abi.encodePacked(result)) : abi.decode(result, (string));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Base.sol";
/// @notice Main storage contract for the Euler system
contract Euler is Base {
constructor(address admin, address installerModule) {
emit Genesis();
reentrancyLock = REENTRANCYLOCK__UNLOCKED;
upgradeAdmin = admin;
governorAdmin = admin;
moduleLookup[MODULEID__INSTALLER] = installerModule;
address installerProxy = _createProxy(MODULEID__INSTALLER);
trustedSenders[installerProxy].moduleImpl = installerModule;
}
string public constant name = "Euler Protocol";
/// @notice Lookup the current implementation contract for a module
/// @param moduleId Fixed constant that refers to a module type (ie MODULEID__ETOKEN)
/// @return An internal address specifies the module's implementation code
function moduleIdToImplementation(uint moduleId) external view returns (address) {
return moduleLookup[moduleId];
}
/// @notice Lookup a proxy that can be used to interact with a module (only valid for single-proxy modules)
/// @param moduleId Fixed constant that refers to a module type (ie MODULEID__MARKETS)
/// @return An address that should be cast to the appropriate module interface, ie IEulerMarkets(moduleIdToProxy(2))
function moduleIdToProxy(uint moduleId) external view returns (address) {
return proxyLookup[moduleId];
}
function dispatch() external {
uint32 moduleId = trustedSenders[msg.sender].moduleId;
address moduleImpl = trustedSenders[msg.sender].moduleImpl;
require(moduleId != 0, "e/sender-not-trusted");
if (moduleImpl == address(0)) moduleImpl = moduleLookup[moduleId];
uint msgDataLength = msg.data.length;
require(msgDataLength >= (4 + 4 + 20), "e/input-too-short");
assembly {
let payloadSize := sub(calldatasize(), 4)
calldatacopy(0, 4, payloadSize)
mstore(payloadSize, shl(96, caller()))
let result := delegatecall(gas(), moduleImpl, 0, add(payloadSize, 20), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Constants.sol";
abstract contract Storage is Constants {
// Dispatcher and upgrades
uint reentrancyLock;
address upgradeAdmin;
address governorAdmin;
mapping(uint => address) moduleLookup; // moduleId => module implementation
mapping(uint => address) proxyLookup; // moduleId => proxy address (only for single-proxy modules)
struct TrustedSenderInfo {
uint32 moduleId; // 0 = un-trusted
address moduleImpl; // only non-zero for external single-proxy modules
}
mapping(address => TrustedSenderInfo) trustedSenders; // sender address => moduleId (0 = un-trusted)
// Account-level state
// Sub-accounts are considered distinct accounts
struct AccountStorage {
// Packed slot: 1 + 5 + 4 + 20 = 30
uint8 deferLiquidityStatus;
uint40 lastAverageLiquidityUpdate;
uint32 numMarketsEntered;
address firstMarketEntered;
uint averageLiquidity;
address averageLiquidityDelegate;
}
mapping(address => AccountStorage) accountLookup;
mapping(address => address[MAX_POSSIBLE_ENTERED_MARKETS]) marketsEntered;
// Markets and assets
struct AssetConfig {
// Packed slot: 20 + 1 + 4 + 4 + 3 = 32
address eTokenAddress;
bool borrowIsolated;
uint32 collateralFactor;
uint32 borrowFactor;
uint24 twapWindow;
}
struct UserAsset {
uint112 balance;
uint144 owed;
uint interestAccumulator;
}
struct AssetStorage {
// Packed slot: 5 + 1 + 4 + 12 + 4 + 2 + 4 = 32
uint40 lastInterestAccumulatorUpdate;
uint8 underlyingDecimals; // Not dynamic, but put here to live in same storage slot
uint32 interestRateModel;
int96 interestRate;
uint32 reserveFee;
uint16 pricingType;
uint32 pricingParameters;
address underlying;
uint96 reserveBalance;
address dTokenAddress;
uint112 totalBalances;
uint144 totalBorrows;
uint interestAccumulator;
mapping(address => UserAsset) users;
mapping(address => mapping(address => uint)) eTokenAllowance;
mapping(address => mapping(address => uint)) dTokenAllowance;
}
mapping(address => AssetConfig) internal underlyingLookup; // underlying => AssetConfig
mapping(address => AssetStorage) internal eTokenLookup; // EToken => AssetStorage
mapping(address => address) internal dTokenLookup; // DToken => EToken
mapping(address => address) internal pTokenLookup; // PToken => underlying
mapping(address => address) internal reversePTokenLookup; // underlying => PToken
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "../BaseLogic.sol";
/// @notice Tokenised representation of assets
contract EToken is BaseLogic {
constructor(bytes32 moduleGitCommit_) BaseLogic(MODULEID__ETOKEN, moduleGitCommit_) {}
function CALLER() private view returns (address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) {
(msgSender, proxyAddr) = unpackTrailingParams();
assetStorage = eTokenLookup[proxyAddr];
underlying = assetStorage.underlying;
require(underlying != address(0), "e/unrecognized-etoken-caller");
}
// Events
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// External methods
/// @notice Pool name, ie "Euler Pool: DAI"
function name() external view returns (string memory) {
(address underlying,,,) = CALLER();
return string(abi.encodePacked("Euler Pool: ", IERC20(underlying).name()));
}
/// @notice Pool symbol, ie "eDAI"
function symbol() external view returns (string memory) {
(address underlying,,,) = CALLER();
return string(abi.encodePacked("e", IERC20(underlying).symbol()));
}
/// @notice Decimals, always normalised to 18.
function decimals() external pure returns (uint8) {
return 18;
}
/// @notice Address of underlying asset
function underlyingAsset() external view returns (address) {
(address underlying,,,) = CALLER();
return underlying;
}
/// @notice Sum of all balances, in internal book-keeping units (non-increasing)
function totalSupply() external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return assetCache.totalBalances;
}
/// @notice Sum of all balances, in underlying units (increases as interest is earned)
function totalSupplyUnderlying() external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return balanceToUnderlyingAmount(assetCache, assetCache.totalBalances) / assetCache.underlyingDecimalsScaler;
}
/// @notice Balance of a particular account, in internal book-keeping units (non-increasing)
function balanceOf(address account) external view returns (uint) {
(, AssetStorage storage assetStorage,,) = CALLER();
return assetStorage.users[account].balance;
}
/// @notice Balance of a particular account, in underlying units (increases as interest is earned)
function balanceOfUnderlying(address account) external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return balanceToUnderlyingAmount(assetCache, assetStorage.users[account].balance) / assetCache.underlyingDecimalsScaler;
}
/// @notice Balance of the reserves, in internal book-keeping units (non-increasing)
function reserveBalance() external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return assetCache.reserveBalance;
}
/// @notice Balance of the reserves, in underlying units (increases as interest is earned)
function reserveBalanceUnderlying() external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return balanceToUnderlyingAmount(assetCache, assetCache.reserveBalance) / assetCache.underlyingDecimalsScaler;
}
/// @notice Convert an eToken balance to an underlying amount, taking into account current exchange rate
/// @param balance eToken balance, in internal book-keeping units (18 decimals)
/// @return Amount in underlying units, (same decimals as underlying token)
function convertBalanceToUnderlying(uint balance) external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return balanceToUnderlyingAmount(assetCache, balance) / assetCache.underlyingDecimalsScaler;
}
/// @notice Convert an underlying amount to an eToken balance, taking into account current exchange rate
/// @param underlyingAmount Amount in underlying units (same decimals as underlying token)
/// @return eToken balance, in internal book-keeping units (18 decimals)
function convertUnderlyingToBalance(uint underlyingAmount) external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return underlyingAmountToBalance(assetCache, decodeExternalAmount(assetCache, underlyingAmount));
}
/// @notice Updates interest accumulator and totalBorrows, credits reserves, re-targets interest rate, and logs asset status
function touch() external nonReentrant {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCache(underlying, assetStorage);
updateInterestRate(assetStorage, assetCache);
logAssetStatus(assetCache);
}
/// @notice Transfer underlying tokens from sender to the Euler pool, and increase account's eTokens
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param amount In underlying units (use max uint256 for full underlying token balance)
function deposit(uint subAccountId, uint amount) external nonReentrant {
(address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER();
address account = getSubAccount(msgSender, subAccountId);
updateAverageLiquidity(account);
emit RequestDeposit(account, amount);
AssetCache memory assetCache = loadAssetCache(underlying, assetStorage);
if (amount == type(uint).max) {
amount = callBalanceOf(assetCache, msgSender);
}
amount = decodeExternalAmount(assetCache, amount);
uint amountTransferred = pullTokens(assetCache, msgSender, amount);
uint amountInternal;
// pullTokens() updates poolSize in the cache, but we need the poolSize before the deposit to determine
// the internal amount so temporarily reduce it by the amountTransferred (which is size checked within
// pullTokens()). We can't compute this value before the pull because we don't know how much we'll
// actually receive (the token might be deflationary).
unchecked {
assetCache.poolSize -= amountTransferred;
amountInternal = underlyingAmountToBalance(assetCache, amountTransferred);
assetCache.poolSize += amountTransferred;
}
increaseBalance(assetStorage, assetCache, proxyAddr, account, amountInternal);
if (assetStorage.users[account].owed != 0) checkLiquidity(account);
logAssetStatus(assetCache);
}
/// @notice Transfer underlying tokens from Euler pool to sender, and decrease account's eTokens
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param amount In underlying units (use max uint256 for full pool balance)
function withdraw(uint subAccountId, uint amount) external nonReentrant {
(address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER();
address account = getSubAccount(msgSender, subAccountId);
updateAverageLiquidity(account);
emit RequestWithdraw(account, amount);
AssetCache memory assetCache = loadAssetCache(underlying, assetStorage);
uint amountInternal;
(amount, amountInternal) = withdrawAmounts(assetStorage, assetCache, account, amount);
require(assetCache.poolSize >= amount, "e/insufficient-pool-size");
pushTokens(assetCache, msgSender, amount);
decreaseBalance(assetStorage, assetCache, proxyAddr, account, amountInternal);
checkLiquidity(account);
logAssetStatus(assetCache);
}
/// @notice Mint eTokens and a corresponding amount of dTokens ("self-borrow")
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param amount In underlying units
function mint(uint subAccountId, uint amount) external nonReentrant {
(address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER();
address account = getSubAccount(msgSender, subAccountId);
updateAverageLiquidity(account);
emit RequestMint(account, amount);
AssetCache memory assetCache = loadAssetCache(underlying, assetStorage);
amount = decodeExternalAmount(assetCache, amount);
uint amountInternal = underlyingAmountToBalanceRoundUp(assetCache, amount);
amount = balanceToUnderlyingAmount(assetCache, amountInternal);
// Mint ETokens
increaseBalance(assetStorage, assetCache, proxyAddr, account, amountInternal);
// Mint DTokens
increaseBorrow(assetStorage, assetCache, assetStorage.dTokenAddress, account, amount);
checkLiquidity(account);
logAssetStatus(assetCache);
}
/// @notice Pay off dToken liability with eTokens ("self-repay")
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param amount In underlying units (use max uint256 to repay the debt in full or up to the available underlying balance)
function burn(uint subAccountId, uint amount) external nonReentrant {
(address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER();
address account = getSubAccount(msgSender, subAccountId);
updateAverageLiquidity(account);
emit RequestBurn(account, amount);
AssetCache memory assetCache = loadAssetCache(underlying, assetStorage);
uint owed = getCurrentOwed(assetStorage, assetCache, account);
if (owed == 0) return;
uint amountInternal;
(amount, amountInternal) = withdrawAmounts(assetStorage, assetCache, account, amount);
if (amount > owed) {
amount = owed;
amountInternal = underlyingAmountToBalanceRoundUp(assetCache, amount);
}
// Burn ETokens
decreaseBalance(assetStorage, assetCache, proxyAddr, account, amountInternal);
// Burn DTokens
decreaseBorrow(assetStorage, assetCache, assetStorage.dTokenAddress, account, amount);
checkLiquidity(account);
logAssetStatus(assetCache);
}
/// @notice Allow spender to access an amount of your eTokens in sub-account 0
/// @param spender Trusted address
/// @param amount Use max uint256 for "infinite" allowance
function approve(address spender, uint amount) external reentrantOK returns (bool) {
return approveSubAccount(0, spender, amount);
}
/// @notice Allow spender to access an amount of your eTokens in a particular sub-account
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param spender Trusted address
/// @param amount Use max uint256 for "infinite" allowance
function approveSubAccount(uint subAccountId, address spender, uint amount) public reentrantOK returns (bool) {
(, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER();
address account = getSubAccount(msgSender, subAccountId);
require(!isSubAccountOf(spender, account), "e/self-approval");
assetStorage.eTokenAllowance[account][spender] = amount;
emitViaProxy_Approval(proxyAddr, account, spender, amount);
return true;
}
/// @notice Retrieve the current allowance
/// @param holder Xor with the desired sub-account ID (if applicable)
/// @param spender Trusted address
function allowance(address holder, address spender) external view returns (uint) {
(, AssetStorage storage assetStorage,,) = CALLER();
return assetStorage.eTokenAllowance[holder][spender];
}
/// @notice Transfer eTokens to another address (from sub-account 0)
/// @param to Xor with the desired sub-account ID (if applicable)
/// @param amount In internal book-keeping units (as returned from balanceOf).
function transfer(address to, uint amount) external returns (bool) {
return transferFrom(address(0), to, amount);
}
/// @notice Transfer the full eToken balance of an address to another
/// @param from This address must've approved the to address, or be a sub-account of msg.sender
/// @param to Xor with the desired sub-account ID (if applicable)
function transferFromMax(address from, address to) external returns (bool) {
(, AssetStorage storage assetStorage,,) = CALLER();
return transferFrom(from, to, assetStorage.users[from].balance);
}
/// @notice Transfer eTokens from one address to another
/// @param from This address must've approved the to address, or be a sub-account of msg.sender
/// @param to Xor with the desired sub-account ID (if applicable)
/// @param amount In internal book-keeping units (as returned from balanceOf).
function transferFrom(address from, address to, uint amount) public nonReentrant returns (bool) {
(address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER();
AssetCache memory assetCache = loadAssetCache(underlying, assetStorage);
if (from == address(0)) from = msgSender;
require(from != to, "e/self-transfer");
updateAverageLiquidity(from);
updateAverageLiquidity(to);
emit RequestTransferEToken(from, to, amount);
if (amount == 0) return true;
if (!isSubAccountOf(msgSender, from) && assetStorage.eTokenAllowance[from][msgSender] != type(uint).max) {
require(assetStorage.eTokenAllowance[from][msgSender] >= amount, "e/insufficient-allowance");
unchecked { assetStorage.eTokenAllowance[from][msgSender] -= amount; }
emitViaProxy_Approval(proxyAddr, from, msgSender, assetStorage.eTokenAllowance[from][msgSender]);
}
transferBalance(assetStorage, assetCache, proxyAddr, from, to, amount);
checkLiquidity(from);
if (assetStorage.users[to].owed != 0) checkLiquidity(to);
logAssetStatus(assetCache);
return true;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "../BaseLogic.sol";
import "../IRiskManager.sol";
import "../PToken.sol";
/// @notice Activating and querying markets, and maintaining entered markets lists
contract Markets is BaseLogic {
constructor(bytes32 moduleGitCommit_) BaseLogic(MODULEID__MARKETS, moduleGitCommit_) {}
/// @notice Create an Euler pool and associated EToken and DToken addresses.
/// @param underlying The address of an ERC20-compliant token. There must be an initialised uniswap3 pool for the underlying/reference asset pair.
/// @return The created EToken, or the existing EToken if already activated.
function activateMarket(address underlying) external nonReentrant returns (address) {
require(pTokenLookup[underlying] == address(0), "e/markets/invalid-token");
return doActivateMarket(underlying);
}
function doActivateMarket(address underlying) private returns (address) {
// Pre-existing
if (underlyingLookup[underlying].eTokenAddress != address(0)) return underlyingLookup[underlying].eTokenAddress;
// Validation
require(trustedSenders[underlying].moduleId == 0 && underlying != address(this), "e/markets/invalid-token");
uint8 decimals = IERC20(underlying).decimals();
require(decimals <= 18, "e/too-many-decimals");
// Get risk manager parameters
IRiskManager.NewMarketParameters memory params;
{
bytes memory result = callInternalModule(MODULEID__RISK_MANAGER,
abi.encodeWithSelector(IRiskManager.getNewMarketParameters.selector, underlying));
(params) = abi.decode(result, (IRiskManager.NewMarketParameters));
}
// Create proxies
address childEToken = params.config.eTokenAddress = _createProxy(MODULEID__ETOKEN);
address childDToken = _createProxy(MODULEID__DTOKEN);
// Setup storage
underlyingLookup[underlying] = params.config;
dTokenLookup[childDToken] = childEToken;
AssetStorage storage assetStorage = eTokenLookup[childEToken];
assetStorage.underlying = underlying;
assetStorage.pricingType = params.pricingType;
assetStorage.pricingParameters = params.pricingParameters;
assetStorage.dTokenAddress = childDToken;
assetStorage.lastInterestAccumulatorUpdate = uint40(block.timestamp);
assetStorage.underlyingDecimals = decimals;
assetStorage.interestRateModel = uint32(MODULEID__IRM_DEFAULT);
assetStorage.reserveFee = type(uint32).max; // default
assetStorage.interestAccumulator = INITIAL_INTEREST_ACCUMULATOR;
emit MarketActivated(underlying, childEToken, childDToken);
return childEToken;
}
/// @notice Create a pToken and activate it on Euler. pTokens are protected wrappers around assets that prevent borrowing.
/// @param underlying The address of an ERC20-compliant token. There must already be an activated market on Euler for this underlying, and it must have a non-zero collateral factor.
/// @return The created pToken, or an existing one if already activated.
function activatePToken(address underlying) external nonReentrant returns (address) {
require(pTokenLookup[underlying] == address(0), "e/nested-ptoken");
if (reversePTokenLookup[underlying] != address(0)) return reversePTokenLookup[underlying];
{
AssetConfig memory config = resolveAssetConfig(underlying);
require(config.collateralFactor != 0, "e/ptoken/not-collateral");
}
address pTokenAddr = address(new PToken(address(this), underlying));
pTokenLookup[pTokenAddr] = underlying;
reversePTokenLookup[underlying] = pTokenAddr;
emit PTokenActivated(underlying, pTokenAddr);
doActivateMarket(pTokenAddr);
return pTokenAddr;
}
// General market accessors
/// @notice Given an underlying, lookup the associated EToken
/// @param underlying Token address
/// @return EToken address, or address(0) if not activated
function underlyingToEToken(address underlying) external view returns (address) {
return underlyingLookup[underlying].eTokenAddress;
}
/// @notice Given an underlying, lookup the associated DToken
/// @param underlying Token address
/// @return DToken address, or address(0) if not activated
function underlyingToDToken(address underlying) external view returns (address) {
return eTokenLookup[underlyingLookup[underlying].eTokenAddress].dTokenAddress;
}
/// @notice Given an underlying, lookup the associated PToken
/// @param underlying Token address
/// @return PToken address, or address(0) if it doesn't exist
function underlyingToPToken(address underlying) external view returns (address) {
return reversePTokenLookup[underlying];
}
/// @notice Looks up the Euler-related configuration for a token, and resolves all default-value placeholders to their currently configured values.
/// @param underlying Token address
/// @return Configuration struct
function underlyingToAssetConfig(address underlying) external view returns (AssetConfig memory) {
return resolveAssetConfig(underlying);
}
/// @notice Looks up the Euler-related configuration for a token, and returns it unresolved (with default-value placeholders)
/// @param underlying Token address
/// @return config Configuration struct
function underlyingToAssetConfigUnresolved(address underlying) external view returns (AssetConfig memory config) {
config = underlyingLookup[underlying];
require(config.eTokenAddress != address(0), "e/market-not-activated");
}
/// @notice Given an EToken address, looks up the associated underlying
/// @param eToken EToken address
/// @return underlying Token address
function eTokenToUnderlying(address eToken) external view returns (address underlying) {
underlying = eTokenLookup[eToken].underlying;
require(underlying != address(0), "e/invalid-etoken");
}
/// @notice Given an EToken address, looks up the associated DToken
/// @param eToken EToken address
/// @return dTokenAddr DToken address
function eTokenToDToken(address eToken) external view returns (address dTokenAddr) {
dTokenAddr = eTokenLookup[eToken].dTokenAddress;
require(dTokenAddr != address(0), "e/invalid-etoken");
}
function getAssetStorage(address underlying) private view returns (AssetStorage storage) {
address eTokenAddr = underlyingLookup[underlying].eTokenAddress;
require(eTokenAddr != address(0), "e/market-not-activated");
return eTokenLookup[eTokenAddr];
}
/// @notice Looks up an asset's currently configured interest rate model
/// @param underlying Token address
/// @return Module ID that represents the interest rate model (IRM)
function interestRateModel(address underlying) external view returns (uint) {
AssetStorage storage assetStorage = getAssetStorage(underlying);
return assetStorage.interestRateModel;
}
/// @notice Retrieves the current interest rate for an asset
/// @param underlying Token address
/// @return The interest rate in yield-per-second, scaled by 10**27
function interestRate(address underlying) external view returns (int96) {
AssetStorage storage assetStorage = getAssetStorage(underlying);
return assetStorage.interestRate;
}
/// @notice Retrieves the current interest rate accumulator for an asset
/// @param underlying Token address
/// @return An opaque accumulator that increases as interest is accrued
function interestAccumulator(address underlying) external view returns (uint) {
AssetStorage storage assetStorage = getAssetStorage(underlying);
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return assetCache.interestAccumulator;
}
/// @notice Retrieves the reserve fee in effect for an asset
/// @param underlying Token address
/// @return Amount of interest that is redirected to the reserves, as a fraction scaled by RESERVE_FEE_SCALE (4e9)
function reserveFee(address underlying) external view returns (uint32) {
AssetStorage storage assetStorage = getAssetStorage(underlying);
return assetStorage.reserveFee == type(uint32).max ? uint32(DEFAULT_RESERVE_FEE) : assetStorage.reserveFee;
}
/// @notice Retrieves the pricing config for an asset
/// @param underlying Token address
/// @return pricingType (1=pegged, 2=uniswap3, 3=forwarded)
/// @return pricingParameters If uniswap3 pricingType then this represents the uniswap pool fee used, otherwise unused
/// @return pricingForwarded If forwarded pricingType then this is the address prices are forwarded to, otherwise address(0)
function getPricingConfig(address underlying) external view returns (uint16 pricingType, uint32 pricingParameters, address pricingForwarded) {
AssetStorage storage assetStorage = getAssetStorage(underlying);
pricingType = assetStorage.pricingType;
pricingParameters = assetStorage.pricingParameters;
pricingForwarded = pricingType == PRICINGTYPE__FORWARDED ? pTokenLookup[underlying] : address(0);
}
// Enter/exit markets
/// @notice Retrieves the list of entered markets for an account (assets enabled for collateral or borrowing)
/// @param account User account
/// @return List of underlying token addresses
function getEnteredMarkets(address account) external view returns (address[] memory) {
return getEnteredMarketsArray(account);
}
/// @notice Add an asset to the entered market list, or do nothing if already entered
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param newMarket Underlying token address
function enterMarket(uint subAccountId, address newMarket) external nonReentrant {
address msgSender = unpackTrailingParamMsgSender();
address account = getSubAccount(msgSender, subAccountId);
require(underlyingLookup[newMarket].eTokenAddress != address(0), "e/market-not-activated");
doEnterMarket(account, newMarket);
}
/// @notice Remove an asset from the entered market list, or do nothing if not already present
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param oldMarket Underlying token address
function exitMarket(uint subAccountId, address oldMarket) external nonReentrant {
address msgSender = unpackTrailingParamMsgSender();
address account = getSubAccount(msgSender, subAccountId);
AssetConfig memory config = resolveAssetConfig(oldMarket);
AssetStorage storage assetStorage = eTokenLookup[config.eTokenAddress];
uint balance = assetStorage.users[account].balance;
uint owed = assetStorage.users[account].owed;
require(owed == 0, "e/outstanding-borrow");
doExitMarket(account, oldMarket);
if (config.collateralFactor != 0 && balance != 0) {
checkLiquidity(account);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./BaseIRM.sol";
contract BaseIRMLinearKink is BaseIRM {
uint public immutable baseRate;
uint public immutable slope1;
uint public immutable slope2;
uint public immutable kink;
constructor(uint moduleId_, bytes32 moduleGitCommit_, uint baseRate_, uint slope1_, uint slope2_, uint kink_) BaseIRM(moduleId_, moduleGitCommit_) {
baseRate = baseRate_;
slope1 = slope1_;
slope2 = slope2_;
kink = kink_;
}
function computeInterestRateImpl(address, uint32 utilisation) internal override view returns (int96) {
uint ir = baseRate;
if (utilisation <= kink) {
ir += utilisation * slope1;
} else {
ir += kink * slope1;
ir += slope2 * (utilisation - kink);
}
return int96(int(ir));
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
// From MakerDAO DSS
// Copyright (C) 2018 Rain <[email protected]>
//
// 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 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity ^0.8.0;
library RPow {
function rpow(uint x, uint n, uint base) internal pure returns (uint z) {
assembly {
switch x case 0 {switch n case 0 {z := base} default {z := 0}}
default {
switch mod(n, 2) case 0 { z := base } default { z := x }
let half := div(base, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, base)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, base)
}
}
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
//import "hardhat/console.sol"; // DEV_MODE
import "./Storage.sol";
import "./Events.sol";
import "./Proxy.sol";
abstract contract Base is Storage, Events {
// Modules
function _createProxy(uint proxyModuleId) internal returns (address) {
require(proxyModuleId != 0, "e/create-proxy/invalid-module");
require(proxyModuleId <= MAX_EXTERNAL_MODULEID, "e/create-proxy/internal-module");
// If we've already created a proxy for a single-proxy module, just return it:
if (proxyLookup[proxyModuleId] != address(0)) return proxyLookup[proxyModuleId];
// Otherwise create a proxy:
address proxyAddr = address(new Proxy());
if (proxyModuleId <= MAX_EXTERNAL_SINGLE_PROXY_MODULEID) proxyLookup[proxyModuleId] = proxyAddr;
trustedSenders[proxyAddr] = TrustedSenderInfo({ moduleId: uint32(proxyModuleId), moduleImpl: address(0) });
emit ProxyCreated(proxyAddr, proxyModuleId);
return proxyAddr;
}
function callInternalModule(uint moduleId, bytes memory input) internal returns (bytes memory) {
(bool success, bytes memory result) = moduleLookup[moduleId].delegatecall(input);
if (!success) revertBytes(result);
return result;
}
// Modifiers
modifier nonReentrant() {
require(reentrancyLock == REENTRANCYLOCK__UNLOCKED, "e/reentrancy");
reentrancyLock = REENTRANCYLOCK__LOCKED;
_;
reentrancyLock = REENTRANCYLOCK__UNLOCKED;
}
modifier reentrantOK() { // documentation only
_;
}
// Used to flag functions which do not modify storage, but do perform a delegate call
// to a view function, which prohibits a standard view modifier. The flag is used to
// patch state mutability in compiled ABIs and interfaces.
modifier staticDelegate() {
_;
}
// WARNING: Must be very careful with this modifier. It resets the free memory pointer
// to the value it was when the function started. This saves gas if more memory will
// be allocated in the future. However, if the memory will be later referenced
// (for example because the function has returned a pointer to it) then you cannot
// use this modifier.
modifier FREEMEM() {
uint origFreeMemPtr;
assembly {
origFreeMemPtr := mload(0x40)
}
_;
/*
assembly { // DEV_MODE: overwrite the freed memory with garbage to detect bugs
let garbage := 0xDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF
for { let i := origFreeMemPtr } lt(i, mload(0x40)) { i := add(i, 32) } { mstore(i, garbage) }
}
*/
assembly {
mstore(0x40, origFreeMemPtr)
}
}
// Error handling
function revertBytes(bytes memory errMsg) internal pure {
if (errMsg.length > 0) {
assembly {
revert(add(32, errMsg), mload(errMsg))
}
}
revert("e/empty-error");
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Storage.sol";
abstract contract Events {
event Genesis();
event ProxyCreated(address indexed proxy, uint moduleId);
event MarketActivated(address indexed underlying, address indexed eToken, address indexed dToken);
event PTokenActivated(address indexed underlying, address indexed pToken);
event EnterMarket(address indexed underlying, address indexed account);
event ExitMarket(address indexed underlying, address indexed account);
event Deposit(address indexed underlying, address indexed account, uint amount);
event Withdraw(address indexed underlying, address indexed account, uint amount);
event Borrow(address indexed underlying, address indexed account, uint amount);
event Repay(address indexed underlying, address indexed account, uint amount);
event Liquidation(address indexed liquidator, address indexed violator, address indexed underlying, address collateral, uint repay, uint yield, uint healthScore, uint baseDiscount, uint discount);
event TrackAverageLiquidity(address indexed account);
event UnTrackAverageLiquidity(address indexed account);
event DelegateAverageLiquidity(address indexed account, address indexed delegate);
event PTokenWrap(address indexed underlying, address indexed account, uint amount);
event PTokenUnWrap(address indexed underlying, address indexed account, uint amount);
event AssetStatus(address indexed underlying, uint totalBalances, uint totalBorrows, uint96 reserveBalance, uint poolSize, uint interestAccumulator, int96 interestRate, uint timestamp);
event RequestDeposit(address indexed account, uint amount);
event RequestWithdraw(address indexed account, uint amount);
event RequestMint(address indexed account, uint amount);
event RequestBurn(address indexed account, uint amount);
event RequestTransferEToken(address indexed from, address indexed to, uint amount);
event RequestBorrow(address indexed account, uint amount);
event RequestRepay(address indexed account, uint amount);
event RequestTransferDToken(address indexed from, address indexed to, uint amount);
event RequestLiquidate(address indexed liquidator, address indexed violator, address indexed underlying, address collateral, uint repay, uint minYield);
event InstallerSetUpgradeAdmin(address indexed newUpgradeAdmin);
event InstallerSetGovernorAdmin(address indexed newGovernorAdmin);
event InstallerInstallModule(uint indexed moduleId, address indexed moduleImpl, bytes32 moduleGitCommit);
event GovSetAssetConfig(address indexed underlying, Storage.AssetConfig newConfig);
event GovSetIRM(address indexed underlying, uint interestRateModel, bytes resetParams);
event GovSetPricingConfig(address indexed underlying, uint16 newPricingType, uint32 newPricingParameter);
event GovSetReserveFee(address indexed underlying, uint32 newReserveFee);
event GovConvertReserves(address indexed underlying, address indexed recipient, uint amount);
event RequestSwap(address indexed accountIn, address indexed accountOut, address indexed underlyingIn, address underlyingOut, uint amount, uint swapType);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
contract Proxy {
address immutable creator;
constructor() {
creator = msg.sender;
}
// External interface
fallback() external {
address creator_ = creator;
if (msg.sender == creator_) {
assembly {
mstore(0, 0)
calldatacopy(31, 0, calldatasize())
switch mload(0) // numTopics
case 0 { log0(32, sub(calldatasize(), 1)) }
case 1 { log1(64, sub(calldatasize(), 33), mload(32)) }
case 2 { log2(96, sub(calldatasize(), 65), mload(32), mload(64)) }
case 3 { log3(128, sub(calldatasize(), 97), mload(32), mload(64), mload(96)) }
case 4 { log4(160, sub(calldatasize(), 129), mload(32), mload(64), mload(96), mload(128)) }
default { revert(0, 0) }
return(0, 0)
}
} else {
assembly {
mstore(0, 0xe9c4a3ac00000000000000000000000000000000000000000000000000000000) // dispatch() selector
calldatacopy(4, 0, calldatasize())
mstore(add(4, calldatasize()), shl(96, caller()))
let result := call(gas(), creator_, 0, 0, add(24, calldatasize()), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
abstract contract Constants {
// Universal
uint internal constant SECONDS_PER_YEAR = 365.2425 * 86400; // Gregorian calendar
// Protocol parameters
uint internal constant MAX_SANE_AMOUNT = type(uint112).max;
uint internal constant MAX_SANE_SMALL_AMOUNT = type(uint96).max;
uint internal constant MAX_SANE_DEBT_AMOUNT = type(uint144).max;
uint internal constant INTERNAL_DEBT_PRECISION = 1e9;
uint internal constant MAX_ENTERED_MARKETS = 10; // per sub-account
uint internal constant MAX_POSSIBLE_ENTERED_MARKETS = 2**32; // limited by size of AccountStorage.numMarketsEntered
uint internal constant CONFIG_FACTOR_SCALE = 4_000_000_000; // must fit into a uint32
uint internal constant RESERVE_FEE_SCALE = 4_000_000_000; // must fit into a uint32
uint32 internal constant DEFAULT_RESERVE_FEE = uint32(0.23 * 4_000_000_000);
uint internal constant INITIAL_INTEREST_ACCUMULATOR = 1e27;
uint internal constant AVERAGE_LIQUIDITY_PERIOD = 24 * 60 * 60;
uint16 internal constant MIN_UNISWAP3_OBSERVATION_CARDINALITY = 144;
uint24 internal constant DEFAULT_TWAP_WINDOW_SECONDS = 30 * 60;
uint32 internal constant DEFAULT_BORROW_FACTOR = uint32(0.28 * 4_000_000_000);
uint32 internal constant SELF_COLLATERAL_FACTOR = uint32(0.95 * 4_000_000_000);
// Implementation internals
uint internal constant REENTRANCYLOCK__UNLOCKED = 1;
uint internal constant REENTRANCYLOCK__LOCKED = 2;
uint8 internal constant DEFERLIQUIDITY__NONE = 0;
uint8 internal constant DEFERLIQUIDITY__CLEAN = 1;
uint8 internal constant DEFERLIQUIDITY__DIRTY = 2;
// Pricing types
uint16 internal constant PRICINGTYPE__PEGGED = 1;
uint16 internal constant PRICINGTYPE__UNISWAP3_TWAP = 2;
uint16 internal constant PRICINGTYPE__FORWARDED = 3;
// Modules
// Public single-proxy modules
uint internal constant MODULEID__INSTALLER = 1;
uint internal constant MODULEID__MARKETS = 2;
uint internal constant MODULEID__LIQUIDATION = 3;
uint internal constant MODULEID__GOVERNANCE = 4;
uint internal constant MODULEID__EXEC = 5;
uint internal constant MODULEID__SWAP = 6;
uint internal constant MAX_EXTERNAL_SINGLE_PROXY_MODULEID = 499_999;
// Public multi-proxy modules
uint internal constant MODULEID__ETOKEN = 500_000;
uint internal constant MODULEID__DTOKEN = 500_001;
uint internal constant MAX_EXTERNAL_MODULEID = 999_999;
// Internal modules
uint internal constant MODULEID__RISK_MANAGER = 1_000_000;
// Interest rate models
// Default for new markets
uint internal constant MODULEID__IRM_DEFAULT = 2_000_000;
// Testing-only
uint internal constant MODULEID__IRM_ZERO = 2_000_001;
uint internal constant MODULEID__IRM_FIXED = 2_000_002;
uint internal constant MODULEID__IRM_LINEAR = 2_000_100;
// Classes
uint internal constant MODULEID__IRM_CLASS__STABLE = 2_000_500;
uint internal constant MODULEID__IRM_CLASS__MAJOR = 2_000_501;
uint internal constant MODULEID__IRM_CLASS__MIDCAP = 2_000_502;
uint internal constant MODULEID__IRM_CLASS__MEGA = 2_000_503;
// Swap types
uint internal constant SWAP_TYPE__UNI_EXACT_INPUT_SINGLE = 1;
uint internal constant SWAP_TYPE__UNI_EXACT_INPUT = 2;
uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE = 3;
uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT = 4;
uint internal constant SWAP_TYPE__1INCH = 5;
uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE_REPAY = 6;
uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_REPAY = 7;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./BaseModule.sol";
import "./BaseIRM.sol";
import "./Interfaces.sol";
import "./Utils.sol";
import "./vendor/RPow.sol";
import "./IRiskManager.sol";
abstract contract BaseLogic is BaseModule {
constructor(uint moduleId_, bytes32 moduleGitCommit_) BaseModule(moduleId_, moduleGitCommit_) {}
// Account auth
function getSubAccount(address primary, uint subAccountId) internal pure returns (address) {
require(subAccountId < 256, "e/sub-account-id-too-big");
return address(uint160(primary) ^ uint160(subAccountId));
}
function isSubAccountOf(address primary, address subAccount) internal pure returns (bool) {
return (uint160(primary) | 0xFF) == (uint160(subAccount) | 0xFF);
}
// Entered markets array
function getEnteredMarketsArray(address account) internal view returns (address[] memory) {
uint32 numMarketsEntered = accountLookup[account].numMarketsEntered;
address firstMarketEntered = accountLookup[account].firstMarketEntered;
address[] memory output = new address[](numMarketsEntered);
if (numMarketsEntered == 0) return output;
address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account];
output[0] = firstMarketEntered;
for (uint i = 1; i < numMarketsEntered; ++i) {
output[i] = markets[i];
}
return output;
}
function isEnteredInMarket(address account, address underlying) internal view returns (bool) {
uint32 numMarketsEntered = accountLookup[account].numMarketsEntered;
address firstMarketEntered = accountLookup[account].firstMarketEntered;
if (numMarketsEntered == 0) return false;
if (firstMarketEntered == underlying) return true;
address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account];
for (uint i = 1; i < numMarketsEntered; ++i) {
if (markets[i] == underlying) return true;
}
return false;
}
function doEnterMarket(address account, address underlying) internal {
AccountStorage storage accountStorage = accountLookup[account];
uint32 numMarketsEntered = accountStorage.numMarketsEntered;
address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account];
if (numMarketsEntered != 0) {
if (accountStorage.firstMarketEntered == underlying) return; // already entered
for (uint i = 1; i < numMarketsEntered; i++) {
if (markets[i] == underlying) return; // already entered
}
}
require(numMarketsEntered < MAX_ENTERED_MARKETS, "e/too-many-entered-markets");
if (numMarketsEntered == 0) accountStorage.firstMarketEntered = underlying;
else markets[numMarketsEntered] = underlying;
accountStorage.numMarketsEntered = numMarketsEntered + 1;
emit EnterMarket(underlying, account);
}
// Liquidity check must be done by caller after calling this
function doExitMarket(address account, address underlying) internal {
AccountStorage storage accountStorage = accountLookup[account];
uint32 numMarketsEntered = accountStorage.numMarketsEntered;
address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account];
uint searchIndex = type(uint).max;
if (numMarketsEntered == 0) return; // already exited
if (accountStorage.firstMarketEntered == underlying) {
searchIndex = 0;
} else {
for (uint i = 1; i < numMarketsEntered; i++) {
if (markets[i] == underlying) {
searchIndex = i;
break;
}
}
if (searchIndex == type(uint).max) return; // already exited
}
uint lastMarketIndex = numMarketsEntered - 1;
if (searchIndex != lastMarketIndex) {
if (searchIndex == 0) accountStorage.firstMarketEntered = markets[lastMarketIndex];
else markets[searchIndex] = markets[lastMarketIndex];
}
accountStorage.numMarketsEntered = uint32(lastMarketIndex);
if (lastMarketIndex != 0) markets[lastMarketIndex] = address(0); // zero out for storage refund
emit ExitMarket(underlying, account);
}
// AssetConfig
function resolveAssetConfig(address underlying) internal view returns (AssetConfig memory) {
AssetConfig memory config = underlyingLookup[underlying];
require(config.eTokenAddress != address(0), "e/market-not-activated");
if (config.borrowFactor == type(uint32).max) config.borrowFactor = DEFAULT_BORROW_FACTOR;
if (config.twapWindow == type(uint24).max) config.twapWindow = DEFAULT_TWAP_WINDOW_SECONDS;
return config;
}
// AssetCache
struct AssetCache {
address underlying;
uint112 totalBalances;
uint144 totalBorrows;
uint96 reserveBalance;
uint interestAccumulator;
uint40 lastInterestAccumulatorUpdate;
uint8 underlyingDecimals;
uint32 interestRateModel;
int96 interestRate;
uint32 reserveFee;
uint16 pricingType;
uint32 pricingParameters;
uint poolSize; // result of calling balanceOf on underlying (in external units)
uint underlyingDecimalsScaler;
uint maxExternalAmount;
}
function initAssetCache(address underlying, AssetStorage storage assetStorage, AssetCache memory assetCache) internal view returns (bool dirty) {
dirty = false;
assetCache.underlying = underlying;
// Storage loads
assetCache.lastInterestAccumulatorUpdate = assetStorage.lastInterestAccumulatorUpdate;
uint8 underlyingDecimals = assetCache.underlyingDecimals = assetStorage.underlyingDecimals;
assetCache.interestRateModel = assetStorage.interestRateModel;
assetCache.interestRate = assetStorage.interestRate;
assetCache.reserveFee = assetStorage.reserveFee;
assetCache.pricingType = assetStorage.pricingType;
assetCache.pricingParameters = assetStorage.pricingParameters;
assetCache.reserveBalance = assetStorage.reserveBalance;
assetCache.totalBalances = assetStorage.totalBalances;
assetCache.totalBorrows = assetStorage.totalBorrows;
assetCache.interestAccumulator = assetStorage.interestAccumulator;
// Derived state
unchecked {
assetCache.underlyingDecimalsScaler = 10**(18 - underlyingDecimals);
assetCache.maxExternalAmount = MAX_SANE_AMOUNT / assetCache.underlyingDecimalsScaler;
}
uint poolSize = callBalanceOf(assetCache, address(this));
if (poolSize <= assetCache.maxExternalAmount) {
unchecked { assetCache.poolSize = poolSize * assetCache.underlyingDecimalsScaler; }
} else {
assetCache.poolSize = 0;
}
// Update interest accumulator and reserves
if (block.timestamp != assetCache.lastInterestAccumulatorUpdate) {
dirty = true;
uint deltaT = block.timestamp - assetCache.lastInterestAccumulatorUpdate;
// Compute new values
uint newInterestAccumulator = (RPow.rpow(uint(int(assetCache.interestRate) + 1e27), deltaT, 1e27) * assetCache.interestAccumulator) / 1e27;
uint newTotalBorrows = assetCache.totalBorrows * newInterestAccumulator / assetCache.interestAccumulator;
uint newReserveBalance = assetCache.reserveBalance;
uint newTotalBalances = assetCache.totalBalances;
uint feeAmount = (newTotalBorrows - assetCache.totalBorrows)
* (assetCache.reserveFee == type(uint32).max ? DEFAULT_RESERVE_FEE : assetCache.reserveFee)
/ (RESERVE_FEE_SCALE * INTERNAL_DEBT_PRECISION);
if (feeAmount != 0) {
uint poolAssets = assetCache.poolSize + (newTotalBorrows / INTERNAL_DEBT_PRECISION);
newTotalBalances = poolAssets * newTotalBalances / (poolAssets - feeAmount);
newReserveBalance += newTotalBalances - assetCache.totalBalances;
}
// Store new values in assetCache, only if no overflows will occur
if (newTotalBalances <= MAX_SANE_AMOUNT && newTotalBorrows <= MAX_SANE_DEBT_AMOUNT) {
assetCache.totalBorrows = encodeDebtAmount(newTotalBorrows);
assetCache.interestAccumulator = newInterestAccumulator;
assetCache.lastInterestAccumulatorUpdate = uint40(block.timestamp);
if (newTotalBalances != assetCache.totalBalances) {
assetCache.reserveBalance = encodeSmallAmount(newReserveBalance);
assetCache.totalBalances = encodeAmount(newTotalBalances);
}
}
}
}
function loadAssetCache(address underlying, AssetStorage storage assetStorage) internal returns (AssetCache memory assetCache) {
if (initAssetCache(underlying, assetStorage, assetCache)) {
assetStorage.lastInterestAccumulatorUpdate = assetCache.lastInterestAccumulatorUpdate;
assetStorage.underlying = assetCache.underlying; // avoid an SLOAD of this slot
assetStorage.reserveBalance = assetCache.reserveBalance;
assetStorage.totalBalances = assetCache.totalBalances;
assetStorage.totalBorrows = assetCache.totalBorrows;
assetStorage.interestAccumulator = assetCache.interestAccumulator;
}
}
function loadAssetCacheRO(address underlying, AssetStorage storage assetStorage) internal view returns (AssetCache memory assetCache) {
initAssetCache(underlying, assetStorage, assetCache);
}
// Utils
function decodeExternalAmount(AssetCache memory assetCache, uint externalAmount) internal pure returns (uint scaledAmount) {
require(externalAmount <= assetCache.maxExternalAmount, "e/amount-too-large");
unchecked { scaledAmount = externalAmount * assetCache.underlyingDecimalsScaler; }
}
function encodeAmount(uint amount) internal pure returns (uint112) {
require(amount <= MAX_SANE_AMOUNT, "e/amount-too-large-to-encode");
return uint112(amount);
}
function encodeSmallAmount(uint amount) internal pure returns (uint96) {
require(amount <= MAX_SANE_SMALL_AMOUNT, "e/small-amount-too-large-to-encode");
return uint96(amount);
}
function encodeDebtAmount(uint amount) internal pure returns (uint144) {
require(amount <= MAX_SANE_DEBT_AMOUNT, "e/debt-amount-too-large-to-encode");
return uint144(amount);
}
function computeExchangeRate(AssetCache memory assetCache) private pure returns (uint) {
if (assetCache.totalBalances == 0) return 1e18;
return (assetCache.poolSize + (assetCache.totalBorrows / INTERNAL_DEBT_PRECISION)) * 1e18 / assetCache.totalBalances;
}
function underlyingAmountToBalance(AssetCache memory assetCache, uint amount) internal pure returns (uint) {
uint exchangeRate = computeExchangeRate(assetCache);
return amount * 1e18 / exchangeRate;
}
function underlyingAmountToBalanceRoundUp(AssetCache memory assetCache, uint amount) internal pure returns (uint) {
uint exchangeRate = computeExchangeRate(assetCache);
return (amount * 1e18 + (exchangeRate - 1)) / exchangeRate;
}
function balanceToUnderlyingAmount(AssetCache memory assetCache, uint amount) internal pure returns (uint) {
uint exchangeRate = computeExchangeRate(assetCache);
return amount * exchangeRate / 1e18;
}
function callBalanceOf(AssetCache memory assetCache, address account) internal view FREEMEM returns (uint) {
// We set a gas limit so that a malicious token can't eat up all gas and cause a liquidity check to fail.
(bool success, bytes memory data) = assetCache.underlying.staticcall{gas: 20000}(abi.encodeWithSelector(IERC20.balanceOf.selector, account));
// If token's balanceOf() call fails for any reason, return 0. This prevents malicious tokens from causing liquidity checks to fail.
// If the contract doesn't exist (maybe because selfdestructed), then data.length will be 0 and we will return 0.
// Data length > 32 is allowed because some legitimate tokens append extra data that can be safely ignored.
if (!success || data.length < 32) return 0;
return abi.decode(data, (uint256));
}
function updateInterestRate(AssetStorage storage assetStorage, AssetCache memory assetCache) internal {
uint32 utilisation;
{
uint totalBorrows = assetCache.totalBorrows / INTERNAL_DEBT_PRECISION;
uint poolAssets = assetCache.poolSize + totalBorrows;
if (poolAssets == 0) utilisation = 0; // empty pool arbitrarily given utilisation of 0
else utilisation = uint32(totalBorrows * (uint(type(uint32).max) * 1e18) / poolAssets / 1e18);
}
bytes memory result = callInternalModule(assetCache.interestRateModel,
abi.encodeWithSelector(BaseIRM.computeInterestRate.selector, assetCache.underlying, utilisation));
(int96 newInterestRate) = abi.decode(result, (int96));
assetStorage.interestRate = assetCache.interestRate = newInterestRate;
}
function logAssetStatus(AssetCache memory a) internal {
emit AssetStatus(a.underlying, a.totalBalances, a.totalBorrows / INTERNAL_DEBT_PRECISION, a.reserveBalance, a.poolSize, a.interestAccumulator, a.interestRate, block.timestamp);
}
// Balances
function increaseBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) internal {
assetStorage.users[account].balance = encodeAmount(assetStorage.users[account].balance + amount);
assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(uint(assetCache.totalBalances) + amount);
updateInterestRate(assetStorage, assetCache);
emit Deposit(assetCache.underlying, account, amount);
emitViaProxy_Transfer(eTokenAddress, address(0), account, amount);
}
function decreaseBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) internal {
uint origBalance = assetStorage.users[account].balance;
require(origBalance >= amount, "e/insufficient-balance");
assetStorage.users[account].balance = encodeAmount(origBalance - amount);
assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(assetCache.totalBalances - amount);
updateInterestRate(assetStorage, assetCache);
emit Withdraw(assetCache.underlying, account, amount);
emitViaProxy_Transfer(eTokenAddress, account, address(0), amount);
}
function transferBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address from, address to, uint amount) internal {
uint origFromBalance = assetStorage.users[from].balance;
require(origFromBalance >= amount, "e/insufficient-balance");
uint newFromBalance;
unchecked { newFromBalance = origFromBalance - amount; }
assetStorage.users[from].balance = encodeAmount(newFromBalance);
assetStorage.users[to].balance = encodeAmount(assetStorage.users[to].balance + amount);
emit Withdraw(assetCache.underlying, from, amount);
emit Deposit(assetCache.underlying, to, amount);
emitViaProxy_Transfer(eTokenAddress, from, to, amount);
}
function withdrawAmounts(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint amount) internal view returns (uint, uint) {
uint amountInternal;
if (amount == type(uint).max) {
amountInternal = assetStorage.users[account].balance;
amount = balanceToUnderlyingAmount(assetCache, amountInternal);
} else {
amount = decodeExternalAmount(assetCache, amount);
amountInternal = underlyingAmountToBalanceRoundUp(assetCache, amount);
}
return (amount, amountInternal);
}
// Borrows
// Returns internal precision
function getCurrentOwedExact(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint owed) internal view returns (uint) {
// Don't bother loading the user's accumulator
if (owed == 0) return 0;
// Can't divide by 0 here: If owed is non-zero, we must've initialised the user's interestAccumulator
return owed * assetCache.interestAccumulator / assetStorage.users[account].interestAccumulator;
}
// When non-zero, we round *up* to the smallest external unit so that outstanding dust in a loan can be repaid.
// unchecked is OK here since owed is always loaded from storage, so we know it fits into a uint144 (pre-interest accural)
// Takes and returns 27 decimals precision.
function roundUpOwed(AssetCache memory assetCache, uint owed) private pure returns (uint) {
if (owed == 0) return 0;
unchecked {
uint scale = INTERNAL_DEBT_PRECISION * assetCache.underlyingDecimalsScaler;
return (owed + scale - 1) / scale * scale;
}
}
// Returns 18-decimals precision (debt amount is rounded up)
function getCurrentOwed(AssetStorage storage assetStorage, AssetCache memory assetCache, address account) internal view returns (uint) {
return roundUpOwed(assetCache, getCurrentOwedExact(assetStorage, assetCache, account, assetStorage.users[account].owed)) / INTERNAL_DEBT_PRECISION;
}
function updateUserBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address account) private returns (uint newOwedExact, uint prevOwedExact) {
prevOwedExact = assetStorage.users[account].owed;
newOwedExact = getCurrentOwedExact(assetStorage, assetCache, account, prevOwedExact);
assetStorage.users[account].owed = encodeDebtAmount(newOwedExact);
assetStorage.users[account].interestAccumulator = assetCache.interestAccumulator;
}
function logBorrowChange(AssetCache memory assetCache, address dTokenAddress, address account, uint prevOwed, uint owed) private {
prevOwed = roundUpOwed(assetCache, prevOwed) / INTERNAL_DEBT_PRECISION;
owed = roundUpOwed(assetCache, owed) / INTERNAL_DEBT_PRECISION;
if (owed > prevOwed) {
uint change = owed - prevOwed;
emit Borrow(assetCache.underlying, account, change);
emitViaProxy_Transfer(dTokenAddress, address(0), account, change / assetCache.underlyingDecimalsScaler);
} else if (prevOwed > owed) {
uint change = prevOwed - owed;
emit Repay(assetCache.underlying, account, change);
emitViaProxy_Transfer(dTokenAddress, account, address(0), change / assetCache.underlyingDecimalsScaler);
}
}
function increaseBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address account, uint amount) internal {
amount *= INTERNAL_DEBT_PRECISION;
require(assetCache.pricingType != PRICINGTYPE__FORWARDED || pTokenLookup[assetCache.underlying] == address(0), "e/borrow-not-supported");
(uint owed, uint prevOwed) = updateUserBorrow(assetStorage, assetCache, account);
if (owed == 0) doEnterMarket(account, assetCache.underlying);
owed += amount;
assetStorage.users[account].owed = encodeDebtAmount(owed);
assetStorage.totalBorrows = assetCache.totalBorrows = encodeDebtAmount(assetCache.totalBorrows + amount);
updateInterestRate(assetStorage, assetCache);
logBorrowChange(assetCache, dTokenAddress, account, prevOwed, owed);
}
function decreaseBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address account, uint origAmount) internal {
uint amount = origAmount * INTERNAL_DEBT_PRECISION;
(uint owed, uint prevOwed) = updateUserBorrow(assetStorage, assetCache, account);
uint owedRoundedUp = roundUpOwed(assetCache, owed);
require(amount <= owedRoundedUp, "e/repay-too-much");
uint owedRemaining;
unchecked { owedRemaining = owedRoundedUp - amount; }
if (owed > assetCache.totalBorrows) owed = assetCache.totalBorrows;
assetStorage.users[account].owed = encodeDebtAmount(owedRemaining);
assetStorage.totalBorrows = assetCache.totalBorrows = encodeDebtAmount(assetCache.totalBorrows - owed + owedRemaining);
updateInterestRate(assetStorage, assetCache);
logBorrowChange(assetCache, dTokenAddress, account, prevOwed, owedRemaining);
}
function transferBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address from, address to, uint origAmount) internal {
uint amount = origAmount * INTERNAL_DEBT_PRECISION;
(uint fromOwed, uint fromOwedPrev) = updateUserBorrow(assetStorage, assetCache, from);
(uint toOwed, uint toOwedPrev) = updateUserBorrow(assetStorage, assetCache, to);
if (toOwed == 0) doEnterMarket(to, assetCache.underlying);
// If amount was rounded up, transfer exact amount owed
if (amount > fromOwed && amount - fromOwed < INTERNAL_DEBT_PRECISION * assetCache.underlyingDecimalsScaler) amount = fromOwed;
require(fromOwed >= amount, "e/insufficient-balance");
unchecked { fromOwed -= amount; }
// Transfer any residual dust
if (fromOwed < INTERNAL_DEBT_PRECISION) {
amount += fromOwed;
fromOwed = 0;
}
toOwed += amount;
assetStorage.users[from].owed = encodeDebtAmount(fromOwed);
assetStorage.users[to].owed = encodeDebtAmount(toOwed);
logBorrowChange(assetCache, dTokenAddress, from, fromOwedPrev, fromOwed);
logBorrowChange(assetCache, dTokenAddress, to, toOwedPrev, toOwed);
}
// Reserves
function increaseReserves(AssetStorage storage assetStorage, AssetCache memory assetCache, uint amount) internal {
assetStorage.reserveBalance = assetCache.reserveBalance = encodeSmallAmount(assetCache.reserveBalance + amount);
assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(assetCache.totalBalances + amount);
}
// Token asset transfers
// amounts are in underlying units
function pullTokens(AssetCache memory assetCache, address from, uint amount) internal returns (uint amountTransferred) {
uint poolSizeBefore = assetCache.poolSize;
Utils.safeTransferFrom(assetCache.underlying, from, address(this), amount / assetCache.underlyingDecimalsScaler);
uint poolSizeAfter = assetCache.poolSize = decodeExternalAmount(assetCache, callBalanceOf(assetCache, address(this)));
require(poolSizeAfter >= poolSizeBefore, "e/negative-transfer-amount");
unchecked { amountTransferred = poolSizeAfter - poolSizeBefore; }
}
function pushTokens(AssetCache memory assetCache, address to, uint amount) internal returns (uint amountTransferred) {
uint poolSizeBefore = assetCache.poolSize;
Utils.safeTransfer(assetCache.underlying, to, amount / assetCache.underlyingDecimalsScaler);
uint poolSizeAfter = assetCache.poolSize = decodeExternalAmount(assetCache, callBalanceOf(assetCache, address(this)));
require(poolSizeBefore >= poolSizeAfter, "e/negative-transfer-amount");
unchecked { amountTransferred = poolSizeBefore - poolSizeAfter; }
}
// Liquidity
function getAssetPrice(address asset) internal returns (uint) {
bytes memory result = callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.getPrice.selector, asset));
return abi.decode(result, (uint));
}
function getAccountLiquidity(address account) internal returns (uint collateralValue, uint liabilityValue) {
bytes memory result = callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.computeLiquidity.selector, account));
(IRiskManager.LiquidityStatus memory status) = abi.decode(result, (IRiskManager.LiquidityStatus));
collateralValue = status.collateralValue;
liabilityValue = status.liabilityValue;
}
function checkLiquidity(address account) internal {
uint8 status = accountLookup[account].deferLiquidityStatus;
if (status == DEFERLIQUIDITY__NONE) {
callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.requireLiquidity.selector, account));
} else if (status == DEFERLIQUIDITY__CLEAN) {
accountLookup[account].deferLiquidityStatus = DEFERLIQUIDITY__DIRTY;
}
}
// Optional average liquidity tracking
function computeNewAverageLiquidity(address account, uint deltaT) private returns (uint) {
uint currDuration = deltaT >= AVERAGE_LIQUIDITY_PERIOD ? AVERAGE_LIQUIDITY_PERIOD : deltaT;
uint prevDuration = AVERAGE_LIQUIDITY_PERIOD - currDuration;
uint currAverageLiquidity;
{
(uint collateralValue, uint liabilityValue) = getAccountLiquidity(account);
currAverageLiquidity = collateralValue > liabilityValue ? collateralValue - liabilityValue : 0;
}
return (accountLookup[account].averageLiquidity * prevDuration / AVERAGE_LIQUIDITY_PERIOD) +
(currAverageLiquidity * currDuration / AVERAGE_LIQUIDITY_PERIOD);
}
function getUpdatedAverageLiquidity(address account) internal returns (uint) {
uint lastAverageLiquidityUpdate = accountLookup[account].lastAverageLiquidityUpdate;
if (lastAverageLiquidityUpdate == 0) return 0;
uint deltaT = block.timestamp - lastAverageLiquidityUpdate;
if (deltaT == 0) return accountLookup[account].averageLiquidity;
return computeNewAverageLiquidity(account, deltaT);
}
function getUpdatedAverageLiquidityWithDelegate(address account) internal returns (uint) {
address delegate = accountLookup[account].averageLiquidityDelegate;
return delegate != address(0) && accountLookup[delegate].averageLiquidityDelegate == account
? getUpdatedAverageLiquidity(delegate)
: getUpdatedAverageLiquidity(account);
}
function updateAverageLiquidity(address account) internal {
uint lastAverageLiquidityUpdate = accountLookup[account].lastAverageLiquidityUpdate;
if (lastAverageLiquidityUpdate == 0) return;
uint deltaT = block.timestamp - lastAverageLiquidityUpdate;
if (deltaT == 0) return;
accountLookup[account].lastAverageLiquidityUpdate = uint40(block.timestamp);
accountLookup[account].averageLiquidity = computeNewAverageLiquidity(account, deltaT);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Base.sol";
abstract contract BaseModule is Base {
// Construction
// public accessors common to all modules
uint immutable public moduleId;
bytes32 immutable public moduleGitCommit;
constructor(uint moduleId_, bytes32 moduleGitCommit_) {
moduleId = moduleId_;
moduleGitCommit = moduleGitCommit_;
}
// Accessing parameters
function unpackTrailingParamMsgSender() internal pure returns (address msgSender) {
assembly {
msgSender := shr(96, calldataload(sub(calldatasize(), 40)))
}
}
function unpackTrailingParams() internal pure returns (address msgSender, address proxyAddr) {
assembly {
msgSender := shr(96, calldataload(sub(calldatasize(), 40)))
proxyAddr := shr(96, calldataload(sub(calldatasize(), 20)))
}
}
// Emit logs via proxies
function emitViaProxy_Transfer(address proxyAddr, address from, address to, uint value) internal FREEMEM {
(bool success,) = proxyAddr.call(abi.encodePacked(
uint8(3),
keccak256(bytes('Transfer(address,address,uint256)')),
bytes32(uint(uint160(from))),
bytes32(uint(uint160(to))),
value
));
require(success, "e/log-proxy-fail");
}
function emitViaProxy_Approval(address proxyAddr, address owner, address spender, uint value) internal FREEMEM {
(bool success,) = proxyAddr.call(abi.encodePacked(
uint8(3),
keccak256(bytes('Approval(address,address,uint256)')),
bytes32(uint(uint160(owner))),
bytes32(uint(uint160(spender))),
value
));
require(success, "e/log-proxy-fail");
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./BaseModule.sol";
abstract contract BaseIRM is BaseModule {
constructor(uint moduleId_, bytes32 moduleGitCommit_) BaseModule(moduleId_, moduleGitCommit_) {}
int96 internal constant MAX_ALLOWED_INTEREST_RATE = int96(int(uint(5 * 1e27) / SECONDS_PER_YEAR)); // 500% APR
int96 internal constant MIN_ALLOWED_INTEREST_RATE = 0;
function computeInterestRateImpl(address, uint32) internal virtual returns (int96);
function computeInterestRate(address underlying, uint32 utilisation) external returns (int96) {
int96 rate = computeInterestRateImpl(underlying, utilisation);
if (rate > MAX_ALLOWED_INTEREST_RATE) rate = MAX_ALLOWED_INTEREST_RATE;
else if (rate < MIN_ALLOWED_INTEREST_RATE) rate = MIN_ALLOWED_INTEREST_RATE;
return rate;
}
function reset(address underlying, bytes calldata resetParams) external virtual {}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface IERC20Permit {
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
function permit(address owner, address spender, uint value, uint deadline, bytes calldata signature) external;
}
interface IERC3156FlashBorrower {
function onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes calldata data) external returns (bytes32);
}
interface IERC3156FlashLender {
function maxFlashLoan(address token) external view returns (uint256);
function flashFee(address token, uint256 amount) external view returns (uint256);
function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data) external returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Interfaces.sol";
library Utils {
function safeTransferFrom(address token, address from, address to, uint value) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), string(data));
}
function safeTransfer(address token, address to, uint value) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), string(data));
}
function safeApprove(address token, address to, uint value) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), string(data));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Storage.sol";
// This interface is used to avoid a circular dependency between BaseLogic and RiskManager
interface IRiskManager {
struct NewMarketParameters {
uint16 pricingType;
uint32 pricingParameters;
Storage.AssetConfig config;
}
struct LiquidityStatus {
uint collateralValue;
uint liabilityValue;
uint numBorrows;
bool borrowIsolated;
}
struct AssetLiquidity {
address underlying;
LiquidityStatus status;
}
function getNewMarketParameters(address underlying) external returns (NewMarketParameters memory);
function requireLiquidity(address account) external view;
function computeLiquidity(address account) external view returns (LiquidityStatus memory status);
function computeAssetLiquidities(address account) external view returns (AssetLiquidity[] memory assets);
function getPrice(address underlying) external view returns (uint twap, uint twapPeriod);
function getPriceFull(address underlying) external view returns (uint twap, uint twapPeriod, uint currPrice);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Interfaces.sol";
import "./Utils.sol";
/// @notice Protected Tokens are simple wrappers for tokens, allowing you to use tokens as collateral without permitting borrowing
contract PToken {
address immutable euler;
address immutable underlyingToken;
constructor(address euler_, address underlying_) {
euler = euler_;
underlyingToken = underlying_;
}
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowances;
uint totalBalances;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
/// @notice PToken name, ie "Euler Protected DAI"
function name() external view returns (string memory) {
return string(abi.encodePacked("Euler Protected ", IERC20(underlyingToken).name()));
}
/// @notice PToken symbol, ie "pDAI"
function symbol() external view returns (string memory) {
return string(abi.encodePacked("p", IERC20(underlyingToken).symbol()));
}
/// @notice Number of decimals, which is same as the underlying's
function decimals() external view returns (uint8) {
return IERC20(underlyingToken).decimals();
}
/// @notice Address of the underlying asset
function underlying() external view returns (address) {
return underlyingToken;
}
/// @notice Balance of an account's wrapped tokens
function balanceOf(address who) external view returns (uint) {
return balances[who];
}
/// @notice Sum of all wrapped token balances
function totalSupply() external view returns (uint) {
return totalBalances;
}
/// @notice Retrieve the current allowance
/// @param holder Address giving permission to access tokens
/// @param spender Trusted address
function allowance(address holder, address spender) external view returns (uint) {
return allowances[holder][spender];
}
/// @notice Transfer your own pTokens to another address
/// @param recipient Recipient address
/// @param amount Amount of wrapped token to transfer
function transfer(address recipient, uint amount) external returns (bool) {
return transferFrom(msg.sender, recipient, amount);
}
/// @notice Transfer pTokens from one address to another. The euler address is automatically granted approval.
/// @param from This address must've approved the to address
/// @param recipient Recipient address
/// @param amount Amount to transfer
function transferFrom(address from, address recipient, uint amount) public returns (bool) {
require(balances[from] >= amount, "insufficient balance");
if (from != msg.sender && msg.sender != euler && allowances[from][msg.sender] != type(uint).max) {
require(allowances[from][msg.sender] >= amount, "insufficient allowance");
allowances[from][msg.sender] -= amount;
emit Approval(from, msg.sender, allowances[from][msg.sender]);
}
balances[from] -= amount;
balances[recipient] += amount;
emit Transfer(from, recipient, amount);
return true;
}
/// @notice Allow spender to access an amount of your pTokens. It is not necessary to approve the euler address.
/// @param spender Trusted address
/// @param amount Use max uint256 for "infinite" allowance
function approve(address spender, uint amount) external returns (bool) {
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/// @notice Convert underlying tokens to pTokens
/// @param amount In underlying units (which are equivalent to pToken units)
function wrap(uint amount) external {
Utils.safeTransferFrom(underlyingToken, msg.sender, address(this), amount);
claimSurplus(msg.sender);
}
/// @notice Convert pTokens to underlying tokens
/// @param amount In pToken units (which are equivalent to underlying units)
function unwrap(uint amount) external {
doUnwrap(msg.sender, amount);
}
// Only callable by the euler contract:
function forceUnwrap(address who, uint amount) external {
require(msg.sender == euler, "permission denied");
doUnwrap(who, amount);
}
/// @notice Claim any surplus tokens held by the PToken contract. This should only be used by contracts.
/// @param who Beneficiary to be credited for the surplus token amount
function claimSurplus(address who) public {
uint currBalance = IERC20(underlyingToken).balanceOf(address(this));
require(currBalance > totalBalances, "no surplus balance to claim");
uint amount = currBalance - totalBalances;
totalBalances += amount;
balances[who] += amount;
emit Transfer(address(0), who, amount);
}
// Internal shared:
function doUnwrap(address who, uint amount) private {
require(balances[who] >= amount, "insufficient balance");
totalBalances -= amount;
balances[who] -= amount;
Utils.safeTransfer(underlyingToken, who, amount);
emit Transfer(who, address(0), amount);
}
} | Create a pToken and activate it on Euler. pTokens are protected wrappers around assets that prevent borrowing. underlying The address of an ERC20-compliant token. There must already be an activated market on Euler for this underlying, and it must have a non-zero collateral factor. return The created pToken, or an existing one if already activated. | function activatePToken(address underlying) external nonReentrant returns (address) {
require(pTokenLookup[underlying] == address(0), "e/nested-ptoken");
if (reversePTokenLookup[underlying] != address(0)) return reversePTokenLookup[underlying];
{
AssetConfig memory config = resolveAssetConfig(underlying);
require(config.collateralFactor != 0, "e/ptoken/not-collateral");
}
address pTokenAddr = address(new PToken(address(this), underlying));
pTokenLookup[pTokenAddr] = underlying;
reversePTokenLookup[underlying] = pTokenAddr;
emit PTokenActivated(underlying, pTokenAddr);
doActivateMarket(pTokenAddr);
return pTokenAddr;
}
| 144,899 |
// File: node_modules\openzeppelin-solidity\contracts\ownership\Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Holder.sol
contract ERC721Holder is ERC721Receiver {
function onERC721Received(address, uint256, bytes) public returns(bytes4) {
return ERC721_RECEIVED;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// File: node_modules\openzeppelin-solidity\contracts\AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
// File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721BasicToken.sol
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existance of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for a the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Token.sol
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is ERC721, ERC721BasicToken {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
function ERC721Token(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() public view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
// File: contracts\Integers.sol
/**
* Integers Library
*
* In summary this is a simple library of integer functions which allow a simple
* conversion to and from strings
*
* @author James Lockhart <[email protected]>
*/
library Integers {
/**
* Parse Int
*
* Converts an ASCII string value into an uint as long as the string
* its self is a valid unsigned integer
*
* @param _value The ASCII string to be converted to an unsigned integer
* @return uint The unsigned value of the ASCII string
*/
function parseInt(string _value)
public
returns (uint _ret) {
bytes memory _bytesValue = bytes(_value);
uint j = 1;
for(uint i = _bytesValue.length-1; i >= 0 && i < _bytesValue.length; i--) {
assert(_bytesValue[i] >= 48 && _bytesValue[i] <= 57);
_ret += (uint(_bytesValue[i]) - 48)*j;
j*=10;
}
}
/**
* To String
*
* Converts an unsigned integer to the ASCII string equivalent value
*
* @param _base The unsigned integer to be converted to a string
* @return string The resulting ASCII string value
*/
function toString(uint _base)
internal
returns (string) {
if (_base==0){
return "0";
}
bytes memory _tmp = new bytes(32);
uint i;
for(i = 0;_base > 0;i++) {
_tmp[i] = byte((_base % 10) + 48);
_base /= 10;
}
bytes memory _real = new bytes(i--);
for(uint j = 0; j < _real.length; j++) {
_real[j] = _tmp[i--];
}
return string(_real);
}
/**
* To Byte
*
* Convert an 8 bit unsigned integer to a byte
*
* @param _base The 8 bit unsigned integer
* @return byte The byte equivalent
*/
function toByte(uint8 _base)
public
returns (byte _ret) {
assembly {
let m_alloc := add(msize(),0x1)
mstore8(m_alloc, _base)
_ret := mload(m_alloc)
}
}
/**
* To Bytes
*
* Converts an unsigned integer to bytes
*
* @param _base The integer to be converted to bytes
* @return bytes The bytes equivalent
*/
function toBytes(uint _base)
internal
returns (bytes _ret) {
assembly {
let m_alloc := add(msize(),0x1)
_ret := mload(m_alloc)
mstore(_ret, 0x20)
mstore(add(_ret, 0x20), _base)
}
}
}
// File: contracts\Strings.sol
/**
* Strings Library
*
* In summary this is a simple library of string functions which make simple
* string operations less tedious in solidity.
*
* Please be aware these functions can be quite gas heavy so use them only when
* necessary not to clog the blockchain with expensive transactions.
*
* @author James Lockhart <[email protected]>
*/
library Strings {
/**
* Concat (High gas cost)
*
* Appends two strings together and returns a new value
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string which will be the concatenated
* prefix
* @param _value The value to be the concatenated suffix
* @return string The resulting string from combinging the base and value
*/
function concat(string _base, string _value)
internal
returns (string) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length > 0);
string memory _tmpValue = new string(_baseBytes.length +
_valueBytes.length);
bytes memory _newValue = bytes(_tmpValue);
uint i;
uint j;
for(i = 0; i < _baseBytes.length; i++) {
_newValue[j++] = _baseBytes[i];
}
for(i = 0; i<_valueBytes.length; i++) {
_newValue[j++] = _valueBytes[i];
}
return string(_newValue);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function indexOf(string _base, string _value)
internal
returns (int) {
return _indexOf(_base, _value, 0);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string starting
* from a defined offset
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @param _offset The starting point to start searching from which can start
* from 0, but must not exceed the length of the string
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function _indexOf(string _base, string _value, uint _offset)
internal
returns (int) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length == 1);
for(uint i = _offset; i < _baseBytes.length; i++) {
if (_baseBytes[i] == _valueBytes[0]) {
return int(i);
}
}
return -1;
}
/**
* Length
*
* Returns the length of the specified string
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string to be measured
* @return uint The length of the passed string
*/
function length(string _base)
internal
returns (uint) {
bytes memory _baseBytes = bytes(_base);
return _baseBytes.length;
}
/**
* Sub String
*
* Extracts the beginning part of a string based on the desired length
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string that will be used for
* extracting the sub string from
* @param _length The length of the sub string to be extracted from the base
* @return string The extracted sub string
*/
function substring(string _base, int _length)
internal
returns (string) {
return _substring(_base, _length, 0);
}
/**
* Sub String
*
* Extracts the part of a string based on the desired length and offset. The
* offset and length must not exceed the lenth of the base string.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string that will be used for
* extracting the sub string from
* @param _length The length of the sub string to be extracted from the base
* @param _offset The starting point to extract the sub string from
* @return string The extracted sub string
*/
function _substring(string _base, int _length, int _offset)
internal
returns (string) {
bytes memory _baseBytes = bytes(_base);
assert(uint(_offset+_length) <= _baseBytes.length);
string memory _tmp = new string(uint(_length));
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for(uint i = uint(_offset); i < uint(_offset+_length); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
return string(_tmpBytes);
}
/**
* String Split (Very high gas cost)
*
* Splits a string into an array of strings based off the delimiter value.
* Please note this can be quite a gas expensive function due to the use of
* storage so only use if really required.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string value to be split.
* @param _value The delimiter to split the string on which must be a single
* character
* @return string[] An array of values split based off the delimiter, but
* do not container the delimiter.
*/
function split(string _base, string _value)
internal
returns (string[] storage splitArr) {
bytes memory _baseBytes = bytes(_base);
uint _offset = 0;
while(_offset < _baseBytes.length-1) {
int _limit = _indexOf(_base, _value, _offset);
if (_limit == -1) {
_limit = int(_baseBytes.length);
}
string memory _tmp = new string(uint(_limit)-_offset);
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for(uint i = _offset; i < uint(_limit); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
_offset = uint(_limit) + 1;
splitArr.push(string(_tmpBytes));
}
return splitArr;
}
/**
* Compare To
*
* Compares the characters of two strings, to ensure that they have an
* identical footprint
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to compare against
* @param _value The string the base is being compared to
* @return bool Simply notates if the two string have an equivalent
*/
function compareTo(string _base, string _value)
internal
returns (bool) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
if (_baseBytes.length != _valueBytes.length) {
return false;
}
for(uint i = 0; i < _baseBytes.length; i++) {
if (_baseBytes[i] != _valueBytes[i]) {
return false;
}
}
return true;
}
/**
* Compare To Ignore Case (High gas cost)
*
* Compares the characters of two strings, converting them to the same case
* where applicable to alphabetic characters to distinguish if the values
* match.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to compare against
* @param _value The string the base is being compared to
* @return bool Simply notates if the two string have an equivalent value
* discarding case
*/
function compareToIgnoreCase(string _base, string _value)
internal
returns (bool) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
if (_baseBytes.length != _valueBytes.length) {
return false;
}
for(uint i = 0; i < _baseBytes.length; i++) {
if (_baseBytes[i] != _valueBytes[i] &&
_upper(_baseBytes[i]) != _upper(_valueBytes[i])) {
return false;
}
}
return true;
}
/**
* Upper
*
* Converts all the values of a string to their corresponding upper case
* value.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to convert to upper case
* @return string
*/
function upper(string _base)
internal
returns (string) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _upper(_baseBytes[i]);
}
return string(_baseBytes);
}
/**
* Lower
*
* Converts all the values of a string to their corresponding lower case
* value.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to convert to lower case
* @return string
*/
function lower(string _base)
internal
returns (string) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _lower(_baseBytes[i]);
}
return string(_baseBytes);
}
/**
* Upper
*
* Convert an alphabetic character to upper case and return the original
* value when not alphabetic
*
* @param _b1 The byte to be converted to upper case
* @return bytes1 The converted value if the passed value was alphabetic
* and in a lower case otherwise returns the original value
*/
function _upper(bytes1 _b1)
private
constant
returns (bytes1) {
if (_b1 >= 0x61 && _b1 <= 0x7A) {
return bytes1(uint8(_b1)-32);
}
return _b1;
}
/**
* Lower
*
* Convert an alphabetic character to lower case and return the original
* value when not alphabetic
*
* @param _b1 The byte to be converted to lower case
* @return bytes1 The converted value if the passed value was alphabetic
* and in a upper case otherwise returns the original value
*/
function _lower(bytes1 _b1)
private
constant
returns (bytes1) {
if (_b1 >= 0x41 && _b1 <= 0x5A) {
return bytes1(uint8(_b1)+32);
}
return _b1;
}
}
// File: contracts\DigitalArtChain.sol
contract DigitalArtChain is Ownable, ERC721Token, ERC721Holder {
using Strings for string;
using Integers for uint;
function DigitalArtChain () ERC721Token("DigitalArtChain" ,"DAC") public {
}
struct DigitalArt {
string ipfsHash;
address publisher;
}
DigitalArt[] public digitalArts;
mapping (string => uint256) ipfsHashToTokenId;
mapping (address => uint256) internal publishedTokensCount;
mapping (address => uint256[]) internal publishedTokens;
mapping(address => mapping (uint256 => uint256)) internal publishedTokensIndex;
struct SellingItem {
address seller;
uint128 price;
}
mapping (uint256 => SellingItem) public tokenIdToSellingItem;
uint128 public createDigitalArtFee = 0.00198 ether;
uint128 public publisherCut = 500;
string preUri1 = "http://api.digitalartchain.com/tokens?tokenId=";
string preUri2 = "&ipfsHash=";
/*** Modifier ***/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/*** Owner Action ***/
function withdraw() public onlyOwner {
owner.transfer(this.balance);
}
function setCreateDigitalArtFee(uint128 _fee) public onlyOwner {
createDigitalArtFee = _fee;
}
function setPublisherCut(uint128 _cut) public onlyOwner {
require(_cut > 0 && _cut < 10000);
publisherCut = _cut;
}
function setPreUri1(string _preUri) public onlyOwner {
preUri1 = _preUri;
}
function setPreUri2(string _preUri) public onlyOwner {
preUri2 = _preUri;
}
function getIpfsHashToTokenId(string _string) public view returns (uint256){
return ipfsHashToTokenId[_string];
}
function getOwnedTokens(address _owner) public view returns (uint256[]) {
return ownedTokens[_owner];
}
function getAllTokens() public view returns (uint256[]) {
return allTokens;
}
function publishedCountOf(address _publisher) public view returns (uint256) {
return publishedTokensCount[_publisher];
}
function publishedTokenOfOwnerByIndex(address _publisher, uint256 _index) public view returns (uint256) {
require(_index < publishedCountOf(_publisher));
return publishedTokens[_publisher][_index];
}
function getPublishedTokens(address _publisher) public view returns (uint256[]) {
return publishedTokens[_publisher];
}
function mintDigitalArt(string _ipfsHash) public payable {
require(msg.value == createDigitalArtFee);
require(ipfsHashToTokenId[_ipfsHash] == 0);
DigitalArt memory _digitalArt = DigitalArt({ipfsHash: _ipfsHash, publisher: msg.sender});
uint256 newDigitalArtId = digitalArts.push(_digitalArt) - 1;
ipfsHashToTokenId[_ipfsHash] = newDigitalArtId;
_mint(msg.sender, newDigitalArtId);
publishedTokensCount[msg.sender]++;
uint256 length = publishedTokens[msg.sender].length;
publishedTokens[msg.sender].push(newDigitalArtId);
publishedTokensIndex[msg.sender][newDigitalArtId] = length;
}
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return preUri1.concat(_tokenId.toString()).concat(preUri2).concat(digitalArts[_tokenId].ipfsHash);
}
function addDigitalArtSellingItem(uint256 _tokenId, uint128 _price) public onlyOwnerOf(_tokenId) {
require(tokenIdToSellingItem[_tokenId].seller == address(0));
SellingItem memory _sellingItem = SellingItem(msg.sender, uint128(_price));
tokenIdToSellingItem[_tokenId] = _sellingItem;
approve(address(this), _tokenId);
safeTransferFrom(msg.sender, address(this), _tokenId);
}
function cancelDigitalArtSellingItem(uint256 _tokenId) public {
require(tokenIdToSellingItem[_tokenId].seller == msg.sender);
this.safeTransferFrom(address(this), tokenIdToSellingItem[_tokenId].seller, _tokenId);
delete tokenIdToSellingItem[_tokenId];
}
function purchaseDigitalArtSellingItem(uint256 _tokenId) public payable {
require(tokenIdToSellingItem[_tokenId].seller != address(0));
require(tokenIdToSellingItem[_tokenId].seller != msg.sender);
require(tokenIdToSellingItem[_tokenId].price == msg.value);
SellingItem memory sellingItem = tokenIdToSellingItem[_tokenId];
if (sellingItem.price > 0) {
uint128 actualPublisherCut = _computePublisherCut(sellingItem.price);
uint128 proceeds = sellingItem.price - actualPublisherCut;
sellingItem.seller.transfer(proceeds);
digitalArts[_tokenId].publisher.transfer(actualPublisherCut);
}
delete tokenIdToSellingItem[_tokenId];
this.safeTransferFrom(address(this), msg.sender, _tokenId);
}
/*** Tools ***/
function _computePublisherCut(uint128 _price) internal view returns (uint128) {
return _price * publisherCut / 10000;
}
} | Lower Converts all the values of a string to their corresponding lower case value. _base When being used for a data type this is the extended object otherwise this is the string base to convert to lower case return string/ | function lower(string _base)
internal
returns (string) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _lower(_baseBytes[i]);
}
return string(_baseBytes);
}
| 4,808,901 |
pragma solidity ^0.4.21;
// File: deploy/contracts/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error.
* Note, the div and mul methods were removed as they are not currently needed
*/
library SafeMath {
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;
}
}
// File: deploy/contracts/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint256 public totalSupply;
string public name;
string public symbol;
uint8 public decimals;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
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 Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: deploy/contracts/Stampable.sol
contract Stampable is ERC20 {
using SafeMath for uint256;
// A struct that represents a particular token balance
struct TokenBalance {
uint256 amount;
uint index;
}
// A struct that represents a particular address balance
struct AddressBalance {
mapping (uint256 => TokenBalance) tokens;
uint256[] tokenIndex;
}
// A mapping of address to balances
mapping (address => AddressBalance) balances;
// The total number of tokens owned per address
mapping (address => uint256) ownershipCount;
// Whitelist for addresses allowed to stamp tokens
mapping (address => bool) public stampingWhitelist;
/**
* Modifier for only whitelisted addresses
*/
modifier onlyStampingWhitelisted() {
require(stampingWhitelist[msg.sender]);
_;
}
// Event for token stamping
event TokenStamp (address indexed from, uint256 tokenStamped, uint256 stamp, uint256 amt);
/**
* @dev Function to stamp a token in the msg.sender's wallet
* @param _tokenToStamp uint256 The tokenId of theirs to stamp (0 for unstamped tokens)
* @param _stamp uint256 The new stamp to apply
* @param _amt uint256 The quantity of tokens to stamp
*/
function stampToken (uint256 _tokenToStamp, uint256 _stamp, uint256 _amt)
onlyStampingWhitelisted
public returns (bool) {
require(_amt <= balances[msg.sender].tokens[_tokenToStamp].amount);
// Subtract balance of 0th token ID _amt value.
removeToken(msg.sender, _tokenToStamp, _amt);
// "Stamp" the token
addToken(msg.sender, _stamp, _amt);
// Emit the stamping event
emit TokenStamp(msg.sender, _tokenToStamp, _stamp, _amt);
return true;
}
function addToken(address _owner, uint256 _token, uint256 _amount) internal {
// If they don't yet have any, assign this token an index
if (balances[_owner].tokens[_token].amount == 0) {
balances[_owner].tokens[_token].index = balances[_owner].tokenIndex.push(_token) - 1;
}
// Increase their balance of said token
balances[_owner].tokens[_token].amount = balances[_owner].tokens[_token].amount.add(_amount);
// Increase their ownership count
ownershipCount[_owner] = ownershipCount[_owner].add(_amount);
}
function removeToken(address _owner, uint256 _token, uint256 _amount) internal {
// Decrease their ownership count
ownershipCount[_owner] = ownershipCount[_owner].sub(_amount);
// Decrease their balance of the token
balances[_owner].tokens[_token].amount = balances[_owner].tokens[_token].amount.sub(_amount);
// If they don't have any left, remove it
if (balances[_owner].tokens[_token].amount == 0) {
uint index = balances[_owner].tokens[_token].index;
uint256 lastCoin = balances[_owner].tokenIndex[balances[_owner].tokenIndex.length - 1];
balances[_owner].tokenIndex[index] = lastCoin;
balances[_owner].tokens[lastCoin].index = index;
balances[_owner].tokenIndex.length--;
// Make sure the user's token is removed
delete balances[_owner].tokens[_token];
}
}
}
// File: deploy/contracts/FanCoin.sol
contract FanCoin is Stampable {
using SafeMath for uint256;
// The owner of this token
address public owner;
// Keeps track of allowances for particular address. - ERC20 Method
mapping (address => mapping (address => uint256)) public allowed;
event TokenTransfer (address indexed from, address indexed to, uint256 tokenId, uint256 value);
event MintTransfer (address indexed from, address indexed to, uint256 originalTokenId, uint256 tokenId, uint256 value);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* The constructor for the FanCoin token
*/
function FanCoin() public {
owner = 0x7DDf115B8eEf3058944A3373025FB507efFAD012;
name = "FanChain";
symbol = "FANZ";
decimals = 4;
// Total supply is one billion tokens
totalSupply = 6e8 * uint256(10) ** decimals;
// Add the owner to the stamping whitelist
stampingWhitelist[owner] = true;
// Initially give all of the tokens to the owner
addToken(owner, 0, totalSupply);
}
/** ERC 20
* @dev Retrieves the balance of a specified address
* @param _owner address The address to query the balance of.
* @return A uint256 representing the amount owned by the _owner
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipCount[_owner];
}
/**
* @dev Retrieves the balance of a specified address for a specific token
* @param _owner address The address to query the balance of
* @param _tokenId uint256 The token being queried
* @return A uint256 representing the amount owned by the _owner
*/
function balanceOfToken(address _owner, uint256 _tokenId) public view returns (uint256 balance) {
return balances[_owner].tokens[_tokenId].amount;
}
/**
* @dev Returns all of the tokens owned by a particular address
* @param _owner address The address to query
* @return A uint256 array representing the tokens owned
*/
function tokensOwned(address _owner) public view returns (uint256[] tokens) {
return balances[_owner].tokenIndex;
}
/** ERC 20
* @dev Transfers tokens to a specific address
* @param _to address The address to transfer tokens to
* @param _value unit256 The amount to be transferred
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= totalSupply);
require(_value <= ownershipCount[msg.sender]);
// Cast the value as the ERC20 standard uses uint256
uint256 _tokensToTransfer = uint256(_value);
// Do the transfer
require(transferAny(msg.sender, _to, _tokensToTransfer));
// Notify that a transfer has occurred
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer a specific kind of token to another address
* @param _to address The address to transfer to
* @param _tokenId address The type of token to transfer
* @param _value uint256 The number of tokens to transfer
*/
function transferToken(address _to, uint256 _tokenId, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender].tokens[_tokenId].amount);
// Do the transfer
internalTransfer(msg.sender, _to, _tokenId, _value);
// Notify that a transfer happened
emit TokenTransfer(msg.sender, _to, _tokenId, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer a list of token kinds and values to another address
* @param _to address The address to transfer to
* @param _tokenIds uint256[] The list of tokens to transfer
* @param _values uint256[] The list of amounts to transfer
*/
function transferTokens(address _to, uint256[] _tokenIds, uint256[] _values) public returns (bool) {
require(_to != address(0));
require(_tokenIds.length == _values.length);
require(_tokenIds.length < 100); // Arbitrary limit
// Do verification first
for (uint i = 0; i < _tokenIds.length; i++) {
require(_values[i] > 0);
require(_values[i] <= balances[msg.sender].tokens[_tokenIds[i]].amount);
}
// Transfer every type of token specified
for (i = 0; i < _tokenIds.length; i++) {
require(internalTransfer(msg.sender, _to, _tokenIds[i], _values[i]));
emit TokenTransfer(msg.sender, _to, _tokenIds[i], _values[i]);
emit Transfer(msg.sender, _to, _values[i]);
}
return true;
}
/**
* @dev Transfers the given number of tokens regardless of how they are stamped
* @param _from address The address to transfer from
* @param _to address The address to transfer to
* @param _value uint256 The number of tokens to send
*/
function transferAny(address _from, address _to, uint256 _value) private returns (bool) {
// Iterate through all of the tokens owned, and transfer either the
// current balance of that token, or the remaining total amount to be
// transferred (`_value`), whichever is smaller. Because tokens are completely removed
// as their balances reach 0, we just run the loop until we have transferred all
// of the tokens we need to
uint256 _tokensToTransfer = _value;
while (_tokensToTransfer > 0) {
uint256 tokenId = balances[_from].tokenIndex[0];
uint256 tokenBalance = balances[_from].tokens[tokenId].amount;
if (tokenBalance >= _tokensToTransfer) {
require(internalTransfer(_from, _to, tokenId, _tokensToTransfer));
_tokensToTransfer = 0;
} else {
_tokensToTransfer = _tokensToTransfer - tokenBalance;
require(internalTransfer(_from, _to, tokenId, tokenBalance));
}
}
return true;
}
/**
* Internal function for transferring a specific type of token
*/
function internalTransfer(address _from, address _to, uint256 _tokenId, uint256 _value) private returns (bool) {
// Decrease the amount being sent first
removeToken(_from, _tokenId, _value);
// Increase receivers token balances
addToken(_to, _tokenId, _value);
return true;
}
/** ERC 20
* @dev Transfer on behalf of another address
* @param _from address The address to send tokens from
* @param _to address The address to send tokens 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 <= ownershipCount[_from]);
require(_value <= allowed[_from][msg.sender]);
// Get the uint256 version of value
uint256 _castValue = uint256(_value);
// Decrease the spending limit
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
// Actually perform the transfer
require(transferAny(_from, _to, _castValue));
// Notify that a transfer has occurred
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Transfer and stamp tokens from a mint in one step
* @param _to address To send the tokens to
* @param _tokenToStamp uint256 The token to stamp (0 is unstamped tokens)
* @param _stamp uint256 The new stamp to apply
* @param _amount uint256 The number of tokens to stamp and transfer
*/
function mintTransfer(address _to, uint256 _tokenToStamp, uint256 _stamp, uint256 _amount) public
onlyStampingWhitelisted returns (bool) {
require(_to != address(0));
require(_amount <= balances[msg.sender].tokens[_tokenToStamp].amount);
// Decrease the amount being sent first
removeToken(msg.sender, _tokenToStamp, _amount);
// Increase receivers token balances
addToken(_to, _stamp, _amount);
emit MintTransfer(msg.sender, _to, _tokenToStamp, _stamp, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
/**
* @dev Add an address to the whitelist
* @param _addr address The address to add
*/
function addToWhitelist(address _addr) public
onlyOwner {
stampingWhitelist[_addr] = true;
}
/**
* @dev Remove an address from the whitelist
* @param _addr address The address to remove
*/
function removeFromWhitelist(address _addr) public
onlyOwner {
stampingWhitelist[_addr] = false;
}
/** ERC 20
* @dev Approve sent address to spend the specified amount of tokens on
* behalf of msg.sender
*
* See https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* for any potential security concerns
*
* @param _spender address The address that will spend funds
* @param _value uint256 The number of tokens they are allowed to spend
*/
function approve(address _spender, uint256 _value) public returns (bool) {
require(allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/** ERC 20
* @dev Returns the amount a spender is allowed to spend for a particular
* address
* @param _owner address The address which owns the funds
* @param _spender address The address which will spend the funds.
* @return uint256 The number of tokens still available for the spender
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/** ERC 20
* @dev Increases the number of tokens a spender is allowed to spend for
* `msg.sender`
* @param _spender address The address of the spender
* @param _addedValue uint256 The amount to increase the spenders approval by
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/** ERC 20
* @dev Decreases the number of tokens a spender is allowed to spend for
* `msg.sender`
* @param _spender address The address of the spender
* @param _subtractedValue uint256 The amount to decrease the spenders approval by
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) {
uint _value = allowed[msg.sender][_spender];
if (_subtractedValue > _value) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = _value.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
| Transfers the given number of tokens regardless of how they are stamped _from address The address to transfer from _to address The address to transfer to _value uint256 The number of tokens to send/ Iterate through all of the tokens owned, and transfer either the current balance of that token, or the remaining total amount to be transferred (`_value`), whichever is smaller. Because tokens are completely removed as their balances reach 0, we just run the loop until we have transferred all of the tokens we need to | function transferAny(address _from, address _to, uint256 _value) private returns (bool) {
uint256 _tokensToTransfer = _value;
while (_tokensToTransfer > 0) {
uint256 tokenId = balances[_from].tokenIndex[0];
uint256 tokenBalance = balances[_from].tokens[tokenId].amount;
if (tokenBalance >= _tokensToTransfer) {
require(internalTransfer(_from, _to, tokenId, _tokensToTransfer));
_tokensToTransfer = 0;
_tokensToTransfer = _tokensToTransfer - tokenBalance;
require(internalTransfer(_from, _to, tokenId, tokenBalance));
}
}
return true;
}
| 5,505,127 |
// Verified using https://dapp.tools
// hevm: flattened sources of /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/UniswapV3Medianizer.sol
pragma solidity =0.6.7 >=0.4.0 >=0.5.0 >=0.5.0 <0.8.0;
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/pool/IUniswapV3PoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. (0 - uint128(1)). Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/pool/IUniswapV3PoolDerivedState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns a relative timestamp value representing how long, in seconds, the pool has spent between
/// tickLower and tickUpper
/// @dev This timestamp is strictly relative. To get a useful elapsed time (i.e., duration) value, the value returned
/// by this method should be checkpointed externally after a position is minted, and again before a position is
/// burned. Thus the external contract must control the lifecycle of the position.
/// @param tickLower The lower tick of the range for which to get the seconds inside
/// @param tickUpper The upper tick of the range for which to get the seconds inside
/// @return A relative timestamp for how long the pool spent in the tick range
function secondsInside(int24 tickLower, int24 tickUpper) external view returns (uint32);
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return liquidityCumulatives Cumulative liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory liquidityCumulatives);
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/pool/IUniswapV3PoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/pool/IUniswapV3PoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/pool/IUniswapV3PoolOwnerActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/pool/IUniswapV3PoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// feeGrowthOutsideX128 values can only be used if the tick is initialized,
/// i.e. if liquidityGross is greater than 0. In addition, these values are only relative and are used to
/// compute snapshots.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns 8 packed tick seconds outside values. See SecondsOutside for more information
function secondsOutside(int24 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the current tick multiplied by seconds elapsed for the life of the pool as of the
/// observation,
/// Returns liquidityCumulative the current liquidity multiplied by seconds elapsed for the life of the pool as of
/// the observation,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 liquidityCumulative,
bool initialized
);
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/IUniswapV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/* import './pool/IUniswapV3PoolImmutables.sol'; */
/* import './pool/IUniswapV3PoolState.sol'; */
/* import './pool/IUniswapV3PoolDerivedState.sol'; */
/* import './pool/IUniswapV3PoolActions.sol'; */
/* import './pool/IUniswapV3PoolOwnerActions.sol'; */
/* import './pool/IUniswapV3PoolEvents.sol'; */
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/libraries/FullMath.sol
// SPDX-License-Identifier: MIT
/* pragma solidity >=0.4.0; */
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < (0 - uint256(1)));
result++;
}
}
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/libraries/LowGasSafeMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity 0.6.7; */
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/libraries/PoolAddress.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/libraries/TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = (0 - uint256(1)) / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/libraries/OracleLibrary.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0 <0.8.0; */
/* import '../libraries/FullMath.sol'; */
/* import '../libraries/TickMath.sol'; */
/* import '../interfaces/IUniswapV3Pool.sol'; */
/* import '../libraries/LowGasSafeMath.sol'; */
/* import '../libraries/PoolAddress.sol'; */
/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
/// @notice Fetches time-weighted average tick using Uniswap V3 oracle
/// @param pool Address of Uniswap V3 pool that we want to observe
/// @param period Number of seconds in the past to start calculating time-weighted average
/// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp
function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) {
require(period != 0, 'BP');
uint32[] memory secondAgos = new uint32[](2);
secondAgos[0] = period;
secondAgos[1] = 0;
(int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
timeWeightedAverageTick = int24(tickCumulativesDelta / period);
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % period != 0)) timeWeightedAverageTick--;
}
/// @notice Given a tick and a token amount, calculates the amount of token received in exchange
/// @param tick Tick value used to calculate the quote
/// @param baseAmount Amount of token to be converted
/// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
/// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
/// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
) internal pure returns (uint256 quoteAmount) {
uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
// Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
if (sqrtRatioX96 <= uint128(-1)) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
: FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
} else {
uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
: FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
}
}
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/UniswapV3Medianizer.sol
/* pragma solidity 0.6.7; */
/* import './univ3/interfaces/IUniswapV3Pool.sol'; */
/* import './univ3/libraries/OracleLibrary.sol'; */
abstract contract TokenLike {
function balanceOf(address) public view virtual returns (uint256);
}
contract UniswapV3Medianizer {
// --- Auth ---
mapping (address => uint) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "UniswapV3Medianizer/account-not-authorized");
_;
}
// --- Uniswap Vars ---
// Default amount of targetToken used when calculating the denominationToken output
uint128 public defaultAmountIn = 1 ether;
// Minimum liquidity of targetToken to consider a valid result
uint256 public minimumLiquidity;
// Token for which the contract calculates the medianPrice for
address public targetToken;
// Pair token from the Uniswap pair
address public denominationToken;
// The pool to read price data from
address public uniswapPool;
// --- General Vars ---
// The desired amount of time over which the moving average should be computed, e.g. 24 hours
uint32 public windowSize;
// Manual flag that can be set by governance and indicates if a result is valid or not
uint256 public validityFlag;
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event ModifyParameters(
bytes32 parameter,
address addr
);
event ModifyParameters(
bytes32 parameter,
uint256 val
);
constructor(
address uniswapPool_,
address targetToken_,
uint32 windowSize_,
uint256 minimumLiquidity_
) public {
require(uniswapPool_ != address(0), "UniswapV3Medianizer/null-uniswap-factory");
require(windowSize_ > 0, 'UniswapV3Medianizer/null-window-size');
authorizedAccounts[msg.sender] = 1;
uniswapPool = uniswapPool_;
windowSize = windowSize_;
minimumLiquidity = minimumLiquidity_;
validityFlag = 1;
targetToken = targetToken_;
address token0 = IUniswapV3Pool(uniswapPool_).token0();
address token1 = IUniswapV3Pool(uniswapPool_).token1();
require(targetToken_ == token0 || targetToken_ == token1, "UniswapV3Medianizer/target-not-from-pool");
denominationToken = targetToken_ == token0 ? token1 : token0;
// Emit events
emit AddAuthorization(msg.sender);
emit ModifyParameters(bytes32("windowSize"), windowSize_);
}
// --- General Utils --
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
function both(bool x, bool y) private pure returns (bool z) {
assembly{ z := and(x, y)}
}
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "UniswapV3Medianizer/toUint128_overflow");
return uint128(value);
}
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "UniswapV3Medianizer/toUint32_overflow");
return uint32(value);
}
// --- Administration ---
/**
* @notice Modify uint256 parameters
* @param parameter Name of the parameter to modify
* @param data New parameter value
**/
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "validityFlag") {
require(either(data == 1, data == 0), "UniswapV3Medianizer/invalid-data");
validityFlag = data;
}
else if (parameter == "defaultAmountIn") {
require(data > 0, "UniswapV3Medianizer/invalid-default-amount-in");
defaultAmountIn = toUint128(data);
}
else if (parameter == "windowSize") {
require(data > 0, 'UniswapV3Medianizer/invalid-window-size');
windowSize = toUint32(data);
}
else if (parameter == "minimumLiquidity") {
minimumLiquidity = data;
}
else revert("UniswapV3Medianizer/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
// --- Getters ---
/**
* @notice Returns true if feed is valid
**/
function isValid() public view returns (bool) {
return both(validityFlag == 1, TokenLike(targetToken).balanceOf(address(uniswapPool)) >= minimumLiquidity);
}
/**
* @notice Returns medianPrice for windowSize
**/
function getMedianPrice() public view returns (uint256) {
return getMedianPrice(windowSize);
}
/**
* @notice Returns medianPrice for a given period
* @param period Number of seconds in the past to start calculating time-weighted average
* @return TWAP
**/
function getMedianPrice(uint32 period) public view returns (uint256) {
int24 timeWeightedAverageTick = OracleLibrary.consult(address(uniswapPool), period);
return OracleLibrary.getQuoteAtTick(
timeWeightedAverageTick,
defaultAmountIn,
targetToken,
denominationToken
);
}
/**
* @notice Fetch the latest medianPrice (for maxWindow) or revert if is is null
**/
function read() external view returns (uint256 value) {
value = getMedianPrice();
require(
both(value > 0, isValid()),
"UniswapV3Medianizer/invalid-price-feed"
);
}
/**
* @notice Fetch the latest medianPrice and whether it is null or not
**/
function getResultWithValidity() external view returns (uint256 value, bool valid) {
value = getMedianPrice();
valid = both(value > 0, isValid());
}
}
| Returns medianPrice for a given period period Number of seconds in the past to start calculating time-weighted average return TWAP/ | function getMedianPrice(uint32 period) public view returns (uint256) {
int24 timeWeightedAverageTick = OracleLibrary.consult(address(uniswapPool), period);
return OracleLibrary.getQuoteAtTick(
timeWeightedAverageTick,
defaultAmountIn,
targetToken,
denominationToken
);
}
| 544,742 |
pragma solidity ^0.4.0;
import "./Foundation.sol";
contract Kingdom {
struct Ballot {
mapping (address => bool) Voted;
mapping (address => uint) Kings;
address[] KingsArr;
uint Weight;
uint Budget;
}
address public King;
Ballot public InProgressBallot;
mapping (address => bool) Citizens;
mapping (address => bool) Immigrants;
mapping (address => uint) Balances;
mapping (address => uint) LockedFunds;
Foundation public FoundationAddress;
uint public Supply;
string public Name;
uint public Budget;
uint public RegimeStartBlock;
uint public RegimePeriod;
uint constant MinimumPeriod = 10000;
modifier isKing() {
require(msg.sender == King);
_;
}
modifier isNotKing() {
require(msg.sender != King);
_;
}
modifier isCitizen() {
require(Citizens[msg.sender] == true);
_;
}
modifier isImmigrant() {
require(Immigrants[msg.sender] == true);
_;
}
modifier hasBalance() {
require(Balances[msg.sender] > 0);
_;
}
function Found(address _foundationAddress, string _name, uint _initialSupply, uint _regimePeriod) public returns (bool success){
// Store the address of the foundation we are using
FoundationAddress = Foundation(_foundationAddress);
// Validate options
if (_regimePeriod < MinimumPeriod){
return false;
}
// Burn the foundation coins
if (!FoundationAddress.BurnCoins(_initialSupply)){
return false;
}
// Create the initial money supply
Supply = _initialSupply;
// Set the legal and economic parameters of this Kingdom
RegimePeriod = _regimePeriod;
RegimeStartBlock = block.number;
Name = _name;
Budget = _initialSupply;
// Founder is the first King
King = msg.sender;
// Set up the first Ballot
delete InProgressBallot;
return true;
}
// If you were a citizen during this regime you can vote on the next regime, but you lock all your funds when you do
function Delegate(address _king, uint _budget) isCitizen() public returns (bool success) {
// Make sure they have not Voted
if (InProgressBallot.Voted[msg.sender]){
return false;
}
// Lock the voters funds until after the election
LockedFunds[msg.sender] = Balances[msg.sender];
// If this is a new candidate then stuff them in the list
if (InProgressBallot.Kings[_king] == 0){
InProgressBallot.KingsArr.push(_king);
}
// Record the vote
InProgressBallot.Kings[_king] += Balances[msg.sender];
InProgressBallot.Budget += Balances[msg.sender] * _budget;
InProgressBallot.Weight += Balances[msg.sender];
InProgressBallot.Voted[msg.sender] = true;
return true;
}
function UnlockFunds() public returns (bool success) {
// You can only unlock funds when an election is over and you have not voted in the next one
if (InProgressBallot.Voted[msg.sender] == true){
return false;
}
if (LockedFunds[msg.sender] == 0) {
return false;
}
// Restore the funds
Balances[msg.sender] += LockedFunds[msg.sender];
LockedFunds[msg.sender] = 0;
// In case they lost their citizenship, it is now restored
Citizens[msg.sender] = true;
return true;
}
// Anyone not the king can send funds to whomever they wish
function SendCoins(address _recipient, uint _amount) public isNotKing() returns (bool success){
// Make sure the funds exist
if (Balances[msg.sender] < _amount) {
return false;
}
// Transfer the funds
Balances[_recipient] += _amount;
Balances[msg.sender] -= _amount;
// If the recpient isn't a citizen they automatically become an imigrant
if (Citizens[_recipient] == false){
Immigrants[_recipient] = true;
}
// If the sender used up all their funds they lose their citizenship for now
if (Balances[msg.sender] == 0){
Citizens[msg.sender] = false;
}
}
// The king can only send money to citizens.
function GovernmentSpend(address _recipient, uint _amount) public isKing() returns (bool success) {
require(Citizens[_recipient] == true);
require(King != _recipient);
require(_amount <= Budget);
Balances[_recipient] += _amount;
Budget -= _amount;
return true;
}
// At the end of the regime, anyone may call for a regime change
function RegimeChange() public returns (bool success) {
// Is it time yet?
if (RegimeStartBlock + RegimePeriod > block.number) {
return false;
}
// Count the voters
address winner = King;
uint winningVotes = 0;
for (uint i = 0; i < InProgressBallot.KingsArr.length; ++i) {
address pot = InProgressBallot.KingsArr[i];
if (InProgressBallot.Kings[pot] > winningVotes){
winner = pot;
winningVotes = InProgressBallot.Kings[pot];
}
}
// Crown the king
King = winner;
// Remove any remaining funds from circulation
Supply -= Budget;
// Calculate the new Budget.
Budget = InProgressBallot.Budget / InProgressBallot.Weight;
// Start the Regime
RegimeStartBlock = block.number;
// Reset the Ballot
delete InProgressBallot;
return true;
}
// Let anyone convert fundation coins to Kingdom coins
function Mint(uint _amount) public returns (bool success) {
// Make sure there are funds
if (_amount == 0) {
return false;
}
// Burn the foundation coins
if (!FoundationAddress.BurnCoins(_amount)){
return false;
}
// Add these coins to the Supply
Supply += _amount;
// You are now a citizen
Citizens[msg.sender] = true;
}
} | At the end of the regime, anyone may call for a regime change Is it time yet? | function RegimeChange() public returns (bool success) {
if (RegimeStartBlock + RegimePeriod > block.number) {
return false;
}
uint winningVotes = 0;
for (uint i = 0; i < InProgressBallot.KingsArr.length; ++i) {
address pot = InProgressBallot.KingsArr[i];
if (InProgressBallot.Kings[pot] > winningVotes){
winner = pot;
winningVotes = InProgressBallot.Kings[pot];
}
}
return true;
}
| 1,014,091 |
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TradingAction.sol";
import "./ActionGuards.sol";
import "./nTokenMintAction.sol";
import "./nTokenRedeemAction.sol";
import "../SettleAssetsExternal.sol";
import "../FreeCollateralExternal.sol";
import "../../math/SafeInt256.sol";
import "../../global/StorageLayoutV1.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/AccountContextHandler.sol";
import "../../../interfaces/notional/NotionalCallback.sol";
contract BatchAction is StorageLayoutV1, ActionGuards {
using BalanceHandler for BalanceState;
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using SafeInt256 for int256;
/// @notice Executes a batch of balance transfers including minting and redeeming nTokens.
/// @param account the account for the action
/// @param actions array of balance actions to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAction(address account, BalanceAction[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
// Return any settle amounts here to reduce the number of storage writes to balances
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
for (uint256 i = 0; i < actions.length; i++) {
BalanceAction calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions
/// @param account the account for the action
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions via an authorized callback contract. This
/// can be used as a "flash loan" facility for special contracts that migrate assets between protocols or perform
/// other actions on behalf of the user.
/// Contracts can borrow from Notional and receive a callback prior to an FC check, this can be useful if the contract
/// needs to perform a trade or repay a debt on a different protocol before depositing collateral. Since Notional's AMM
/// will never be as capital efficient or gas efficient as other flash loan facilities, this method requires whitelisting
/// and will mainly be used for contracts that make migrating assets a better user experience.
/// @param account the account that will take all the actions
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @param callbackData arbitrary bytes to be passed backed to the caller in the callback
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:authorizedCallbackContract
function batchBalanceAndTradeActionWithCallback(
address account,
BalanceActionWithTrades[] calldata actions,
bytes calldata callbackData
) external payable {
// NOTE: Re-entrancy is allowed for authorized callback functions.
require(authorizedCallbackContract[msg.sender], "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
accountContext.setAccountContext(account);
// Be sure to set the account context before initiating the callback, all stateful updates
// have been finalized at this point so we are safe to issue a callback. This callback may
// re-enter Notional safely to deposit or take other actions.
NotionalCallback(msg.sender).notionalCallback(msg.sender, account, callbackData);
if (accountContext.hasDebt != 0x00) {
// NOTE: this method may update the account context to turn off the hasDebt flag, this
// is ok because the worst case would be causing an extra free collateral check when it
// is not required. This check will be entered if the account hasDebt prior to the callback
// being triggered above, so it will happen regardless of what the callback function does.
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
function _batchBalanceAndTradeAction(
address account,
BalanceActionWithTrades[] calldata actions
) internal returns (AccountContext memory) {
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
// NOTE: loading the portfolio state must happen after settle account to get the
// correct portfolio, it will have changed if the account is settled.
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
for (uint256 i = 0; i < actions.length; i++) {
BalanceActionWithTrades calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
// Does not revert on invalid action types here, they also have no effect.
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
if (action.trades.length > 0) {
int256 netCash;
if (accountContext.isBitmapEnabled()) {
require(
accountContext.bitmapCurrencyId == action.currencyId,
"Invalid trades for account"
);
bool didIncurDebt;
(netCash, didIncurDebt) = TradingAction.executeTradesBitmapBatch(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
action.trades
);
if (didIncurDebt) {
accountContext.hasDebt = Constants.HAS_ASSET_DEBT | accountContext.hasDebt;
}
} else {
// NOTE: we return portfolio state here instead of setting it inside executeTradesArrayBatch
// because we want to only write to storage once after all trades are completed
(portfolioState, netCash) = TradingAction.executeTradesArrayBatch(
account,
action.currencyId,
portfolioState,
action.trades
);
}
// If the account owes cash after trading, ensure that it has enough
if (netCash < 0) _checkSufficientCash(balanceState, netCash.neg());
balanceState.netCashChange = balanceState.netCashChange.add(netCash);
}
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
// Update the portfolio state if bitmap is not enabled. If bitmap is already enabled
// then all the assets have already been updated in in storage.
if (!accountContext.isBitmapEnabled()) {
// NOTE: account context is updated in memory inside this method call.
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
// NOTE: free collateral and account context will be set outside of this method call.
return accountContext;
}
/// @dev Executes deposits
function _executeDepositAction(
address account,
BalanceState memory balanceState,
DepositActionType depositType,
uint256 depositActionAmount_
) private {
int256 depositActionAmount = SafeInt256.toInt(depositActionAmount_);
int256 assetInternalAmount;
require(depositActionAmount >= 0);
if (depositType == DepositActionType.None) {
return;
} else if (
depositType == DepositActionType.DepositAsset ||
depositType == DepositActionType.DepositAssetAndMintNToken
) {
// NOTE: this deposit will NOT revert on a failed transfer unless there is a
// transfer fee. The actual transfer will take effect later in balanceState.finalize
assetInternalAmount = balanceState.depositAssetToken(
account,
depositActionAmount,
false // no force transfer
);
} else if (
depositType == DepositActionType.DepositUnderlying ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken
) {
// NOTE: this deposit will revert on a failed transfer immediately
assetInternalAmount = balanceState.depositUnderlyingToken(account, depositActionAmount);
} else if (depositType == DepositActionType.ConvertCashToNToken) {
// _executeNTokenAction will check if the account has sufficient cash
assetInternalAmount = depositActionAmount;
}
_executeNTokenAction(
balanceState,
depositType,
depositActionAmount,
assetInternalAmount
);
}
/// @dev Executes nToken actions
function _executeNTokenAction(
BalanceState memory balanceState,
DepositActionType depositType,
int256 depositActionAmount,
int256 assetInternalAmount
) private {
// After deposits have occurred, check if we are minting nTokens
if (
depositType == DepositActionType.DepositAssetAndMintNToken ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken ||
depositType == DepositActionType.ConvertCashToNToken
) {
// Will revert if trying to mint ntokens and results in a negative cash balance
_checkSufficientCash(balanceState, assetInternalAmount);
balanceState.netCashChange = balanceState.netCashChange.sub(assetInternalAmount);
// Converts a given amount of cash (denominated in internal precision) into nTokens
int256 tokensMinted = nTokenMintAction.nTokenMint(
balanceState.currencyId,
assetInternalAmount
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.add(
tokensMinted
);
} else if (depositType == DepositActionType.RedeemNToken) {
require(
// prettier-ignore
balanceState
.storedNTokenBalance
.add(balanceState.netNTokenTransfer) // transfers would not occur at this point
.add(balanceState.netNTokenSupplyChange) >= depositActionAmount,
"Insufficient token balance"
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.sub(
depositActionAmount
);
int256 assetCash = nTokenRedeemAction.nTokenRedeemViaBatch(
balanceState.currencyId,
depositActionAmount
);
balanceState.netCashChange = balanceState.netCashChange.add(assetCash);
}
}
/// @dev Calculations any withdraws and finalizes balances
function _calculateWithdrawActionAndFinalize(
address account,
AccountContext memory accountContext,
BalanceState memory balanceState,
uint256 withdrawAmountInternalPrecision,
bool withdrawEntireCashBalance,
bool redeemToUnderlying
) private {
int256 withdrawAmount = SafeInt256.toInt(withdrawAmountInternalPrecision);
require(withdrawAmount >= 0); // dev: withdraw action overflow
// NOTE: if withdrawEntireCashBalance is set it will override the withdrawAmountInternalPrecision input
if (withdrawEntireCashBalance) {
// This option is here so that accounts do not end up with dust after lending since we generally
// cannot calculate exact cash amounts from the liquidity curve.
withdrawAmount = balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision);
// If the account has a negative cash balance then cannot withdraw
if (withdrawAmount < 0) withdrawAmount = 0;
}
// prettier-ignore
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.sub(withdrawAmount);
balanceState.finalize(account, accountContext, redeemToUnderlying);
}
function _finalizeAccountContext(address account, AccountContext memory accountContext)
private
{
// At this point all balances, market states and portfolio states should be finalized. Just need to check free
// collateral if required.
accountContext.setAccountContext(account);
if (accountContext.hasDebt != 0x00) {
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
/// @notice When lending, adding liquidity or minting nTokens the account must have a sufficient cash balance
/// to do so.
function _checkSufficientCash(BalanceState memory balanceState, int256 amountInternalPrecision)
private
pure
{
// The total cash position at this point is: storedCashBalance + netCashChange + netAssetTransferInternalPrecision
require(
amountInternalPrecision >= 0 &&
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= amountInternalPrecision,
"Insufficient cash"
);
}
function _settleAccountIfRequired(address account)
private
returns (AccountContext memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
// Returns a new memory reference to account context
return SettleAssetsExternal.settleAccount(account, accountContext);
} else {
return accountContext;
}
}
/// @notice Get a list of deployed library addresses (sorted by library name)
function getLibInfo() external view returns (address, address, address, address, address, address) {
return (
address(FreeCollateralExternal),
address(MigrateIncentives),
address(SettleAssetsExternal),
address(TradingAction),
address(nTokenMintAction),
address(nTokenRedeemAction)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../FreeCollateralExternal.sol";
import "../SettleAssetsExternal.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library TradingAction {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
using SafeInt256 for int256;
using SafeMath for uint256;
event LendBorrowTrade(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash
);
event AddRemoveLiquidity(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash,
int256 netLiquidityTokens
);
event SettledCashDebt(
address indexed settledAccount,
uint16 indexed currencyId,
address indexed settler,
int256 amountToSettleAsset,
int256 fCashAmount
);
event nTokenResidualPurchase(
uint16 indexed currencyId,
uint40 indexed maturity,
address indexed purchaser,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
);
/// @dev Used internally to manage stack issues
struct TradeContext {
int256 cash;
int256 fCashAmount;
int256 fee;
int256 netCash;
int256 totalFee;
uint256 blockTime;
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param bitmapCurrencyId currency id of the bitmap
/// @param nextSettleTime used to calculate the relative positions in the bitmap
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return netCash generated by trading
/// @return didIncurDebt if the bitmap had an fCash position go negative
function executeTradesBitmapBatch(
address account,
uint16 bitmapCurrencyId,
uint40 nextSettleTime,
bytes32[] calldata trades
) external returns (int256, bool) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(bitmapCurrencyId);
MarketParameters memory market;
bool didIncurDebt;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
c.fCashAmount = BitmapAssetsHandler.addifCashAsset(
account,
bitmapCurrencyId,
maturity,
nextSettleTime,
c.fCashAmount
);
didIncurDebt = didIncurDebt || (c.fCashAmount < 0);
c.netCash = c.netCash.add(c.cash);
}
return (c.netCash, didIncurDebt);
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param currencyId currency id to trade
/// @param portfolioState used to update the positions in the portfolio
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return resulting portfolio state
/// @return netCash generated by trading
function executeTradesArrayBatch(
address account,
uint16 currencyId,
PortfolioState memory portfolioState,
bytes32[] calldata trades
) external returns (PortfolioState memory, int256) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(currencyId);
MarketParameters memory market;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trades[i]))));
if (
tradeType == TradeActionType.AddLiquidity ||
tradeType == TradeActionType.RemoveLiquidity
) {
revert("Disabled");
/**
* Manual adding and removing of liquidity is currently disabled.
*
* // Liquidity tokens can only be added by array portfolio
* c.cash = _executeLiquidityTrade(
* account,
* cashGroup,
* market,
* tradeType,
* trades[i],
* portfolioState,
* c.netCash
* );
*/
} else {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
portfolioState.addAsset(
currencyId,
maturity,
Constants.FCASH_ASSET_TYPE,
c.fCashAmount
);
}
c.netCash = c.netCash.add(c.cash);
}
return (portfolioState, c.netCash);
}
/// @notice Executes a non-liquidity token trade
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param trade bytes32 encoding of the particular trade
/// @param blockTime the current block time
/// @return maturity of the asset that was traded
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
bytes32 trade,
uint256 blockTime
)
private
returns (
uint256 maturity,
int256 cashAmount,
int256 fCashAmount
)
{
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trade))));
if (tradeType == TradeActionType.PurchaseNTokenResidual) {
(maturity, cashAmount, fCashAmount) = _purchaseNTokenResidual(
account,
cashGroup,
blockTime,
trade
);
} else if (tradeType == TradeActionType.SettleCashDebt) {
(maturity, cashAmount, fCashAmount) = _settleCashDebt(account, cashGroup, blockTime, trade);
} else if (tradeType == TradeActionType.Lend || tradeType == TradeActionType.Borrow) {
(cashAmount, fCashAmount) = _executeLendBorrowTrade(
cashGroup,
market,
tradeType,
blockTime,
trade
);
// This is a little ugly but required to deal with stack issues. We know the market is loaded
// with the proper maturity inside _executeLendBorrowTrade
maturity = market.maturity;
emit LendBorrowTrade(
account,
uint16(cashGroup.currencyId),
uint40(maturity),
cashAmount,
fCashAmount
);
} else {
revert("Invalid trade type");
}
}
/// @notice Executes a liquidity token trade, no fees incurred and only array portfolios may hold
/// liquidity tokens.
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param trade bytes32 encoding of the particular trade
/// @param portfolioState the current account's portfolio state
/// @param netCash the current net cash accrued in this batch of trades, can be
// used for adding liquidity
/// @return cashAmount: a positive or negative cash amount accrued to the account
function _executeLiquidityTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
bytes32 trade,
PortfolioState memory portfolioState,
int256 netCash
) private returns (int256) {
uint256 marketIndex = uint8(bytes1(trade << 8));
// NOTE: this loads the market in memory
cashGroup.loadMarket(market, marketIndex, true, block.timestamp);
int256 cashAmount;
int256 fCashAmount;
int256 tokens;
if (tradeType == TradeActionType.AddLiquidity) {
cashAmount = int256((uint256(trade) >> 152) & type(uint88).max);
// Setting cash amount to zero will deposit all net cash accumulated in this trade into
// liquidity. This feature allows accounts to borrow in one maturity to provide liquidity
// in another in a single transaction without dust. It also allows liquidity providers to
// sell off the net cash residuals and use the cash amount in the new market without dust
if (cashAmount == 0) cashAmount = netCash;
// Add liquidity will check cash amount is positive
(tokens, fCashAmount) = market.addLiquidity(cashAmount);
cashAmount = cashAmount.neg(); // Report a negative cash amount in the event
} else {
tokens = int256((uint256(trade) >> 152) & type(uint88).max);
(cashAmount, fCashAmount) = market.removeLiquidity(tokens);
tokens = tokens.neg(); // Report a negative amount tokens in the event
}
{
uint256 minImpliedRate = uint32(uint256(trade) >> 120);
uint256 maxImpliedRate = uint32(uint256(trade) >> 88);
// If minImpliedRate is not set then it will be zero
require(market.lastImpliedRate >= minImpliedRate, "Trade failed, slippage");
if (maxImpliedRate != 0)
require(market.lastImpliedRate <= maxImpliedRate, "Trade failed, slippage");
}
// Add the assets in this order so they are sorted
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
Constants.FCASH_ASSET_TYPE,
fCashAmount
);
// Adds the liquidity token asset
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
marketIndex + 1,
tokens
);
emit AddRemoveLiquidity(
account,
cashGroup.currencyId,
// This will not overflow for a long time
uint40(market.maturity),
cashAmount,
fCashAmount,
tokens
);
return cashAmount;
}
/// @notice Executes a lend or borrow trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeLendBorrowTrade(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
uint256 blockTime,
bytes32 trade
)
private
returns (
int256 cashAmount,
int256 fCashAmount
)
{
uint256 marketIndex = uint256(uint8(bytes1(trade << 8)));
// NOTE: this updates the market in memory
cashGroup.loadMarket(market, marketIndex, false, blockTime);
fCashAmount = int256(uint88(bytes11(trade << 16)));
// fCash to account will be negative here
if (tradeType == TradeActionType.Borrow) fCashAmount = fCashAmount.neg();
cashAmount = market.executeTrade(
cashGroup,
fCashAmount,
market.maturity.sub(blockTime),
marketIndex
);
require(cashAmount != 0, "Trade failed, liquidity");
uint256 rateLimit = uint256(uint32(bytes4(trade << 104)));
if (rateLimit != 0) {
if (tradeType == TradeActionType.Borrow) {
// Do not allow borrows over the rate limit
require(market.lastImpliedRate <= rateLimit, "Trade failed, slippage");
} else {
// Do not allow lends under the rate limit
require(market.lastImpliedRate >= rateLimit, "Trade failed, slippage");
}
}
}
/// @notice If an account has a negative cash balance we allow anyone to lend to to that account at a penalty
/// rate to the 3 month market.
/// @param account the account initiating the trade, used to check that self settlement is not possible
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the three month maturity where fCash will be exchanged
/// @return cashAmount: a negative cash amount that the account must pay to the settled account
/// @return fCashAmount: a positive fCash amount that the account will receive
function _settleCashDebt(
address account,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
address counterparty = address(uint256(trade) >> 88);
// Allowing an account to settle itself would result in strange outcomes
require(account != counterparty, "Cannot settle self");
int256 amountToSettleAsset = int256(uint88(uint256(trade)));
AccountContext memory counterpartyContext =
AccountContextHandler.getAccountContext(counterparty);
if (counterpartyContext.mustSettleAssets()) {
counterpartyContext = SettleAssetsExternal.settleAccount(counterparty, counterpartyContext);
}
// This will check if the amountToSettleAsset is valid and revert if it is not. Amount to settle is a positive
// number denominated in asset terms. If amountToSettleAsset is set equal to zero on the input, will return the
// max amount to settle. This will update the balance storage on the counterparty.
amountToSettleAsset = BalanceHandler.setBalanceStorageForSettleCashDebt(
counterparty,
cashGroup,
amountToSettleAsset,
counterpartyContext
);
// Settled account must borrow from the 3 month market at a penalty rate. This will fail if the market
// is not initialized.
uint256 threeMonthMaturity = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
int256 fCashAmount =
_getfCashSettleAmount(cashGroup, threeMonthMaturity, blockTime, amountToSettleAsset);
// Defensive check to ensure that we can't inadvertently cause the settler to lose fCash.
require(fCashAmount >= 0);
// It's possible that this action will put an account into negative free collateral. In this case they
// will immediately become eligible for liquidation and the account settling the debt can also liquidate
// them in the same transaction. Do not run a free collateral check here to allow this to happen.
{
PortfolioAsset[] memory assets = new PortfolioAsset[](1);
assets[0].currencyId = cashGroup.currencyId;
assets[0].maturity = threeMonthMaturity;
assets[0].notional = fCashAmount.neg(); // This is the debt the settled account will incur
assets[0].assetType = Constants.FCASH_ASSET_TYPE;
// Can transfer assets, we have settled above
counterpartyContext = TransferAssets.placeAssetsInAccount(
counterparty,
counterpartyContext,
assets
);
}
counterpartyContext.setAccountContext(counterparty);
emit SettledCashDebt(
counterparty,
uint16(cashGroup.currencyId),
account,
amountToSettleAsset,
fCashAmount.neg()
);
return (threeMonthMaturity, amountToSettleAsset.neg(), fCashAmount);
}
/// @dev Helper method to calculate the fCashAmount from the penalty settlement rate
function _getfCashSettleAmount(
CashGroupParameters memory cashGroup,
uint256 threeMonthMaturity,
uint256 blockTime,
int256 amountToSettleAsset
) private view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(threeMonthMaturity, blockTime);
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(
oracleRate.add(cashGroup.getSettlementPenalty()),
threeMonthMaturity.sub(blockTime)
);
// Amount to settle is positive, this returns the fCashAmount that the settler will
// receive as a positive number
return
cashGroup.assetRate
.convertToUnderlying(amountToSettleAsset)
// Exchange rate converts from cash to fCash when multiplying
.mulInRatePrecision(exchangeRate);
}
/// @notice Allows an account to purchase ntoken residuals
/// @param purchaser account that is purchasing the residuals
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the idiosyncratic maturity where fCash will be exchanged
/// @return cashAmount: a positive or negative cash amount that the account will receive or pay
/// @return fCashAmount: a positive or negative fCash amount that the account will receive
function _purchaseNTokenResidual(
address purchaser,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
uint256 maturity = uint256(uint32(uint256(trade) >> 216));
int256 fCashAmountToPurchase = int88(uint88(uint256(trade) >> 128));
require(maturity > blockTime, "Invalid maturity");
// Require that the residual to purchase does not fall on an existing maturity (i.e.
// it is an idiosyncratic maturity)
require(
!DateTime.isValidMarketMaturity(cashGroup.maxMarketIndex, maturity, blockTime),
"Non idiosyncratic maturity"
);
address nTokenAddress = nTokenHandler.nTokenAddress(cashGroup.currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
/* assetArrayLength */,
bytes5 parameters
) = nTokenHandler.getNTokenContext(nTokenAddress);
// Restrict purchasing until some amount of time after the last initialized time to ensure that arbitrage
// opportunities are not available (by generating residuals and then immediately purchasing them at a discount)
// This is always relative to the last initialized time which is set at utc0 when initialized, not the
// reference time. Therefore we will always restrict residual purchase relative to initialization, not reference.
// This is safer, prevents an attack if someone forces residuals and then somehow prevents market initialization
// until the residual time buffer passes.
require(
blockTime >
lastInitializedTime.add(
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_TIME_BUFFER])) * 1 hours
),
"Insufficient block time"
);
int256 notional =
BitmapAssetsHandler.getifCashNotional(nTokenAddress, cashGroup.currencyId, maturity);
// Check if amounts are valid and set them to the max available if necessary
if (notional < 0 && fCashAmountToPurchase < 0) {
// Does not allow purchasing more negative notional than available
if (fCashAmountToPurchase < notional) fCashAmountToPurchase = notional;
} else if (notional > 0 && fCashAmountToPurchase > 0) {
// Does not allow purchasing more positive notional than available
if (fCashAmountToPurchase > notional) fCashAmountToPurchase = notional;
} else {
// Does not allow moving notional in the opposite direction
revert("Invalid amount");
}
// If fCashAmount > 0 then this will return netAssetCash > 0, if fCashAmount < 0 this will return
// netAssetCash < 0. fCashAmount will go to the purchaser and netAssetCash will go to the nToken.
int256 netAssetCashNToken =
_getResidualPriceAssetCash(
cashGroup,
maturity,
blockTime,
fCashAmountToPurchase,
parameters
);
_updateNTokenPortfolio(
nTokenAddress,
cashGroup.currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase,
netAssetCashNToken
);
emit nTokenResidualPurchase(
uint16(cashGroup.currencyId),
uint40(maturity),
purchaser,
fCashAmountToPurchase,
netAssetCashNToken
);
return (maturity, netAssetCashNToken.neg(), fCashAmountToPurchase);
}
/// @notice Returns the amount of asset cash required to purchase the nToken residual
function _getResidualPriceAssetCash(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime,
int256 fCashAmount,
bytes6 parameters
) internal view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
// Residual purchase incentive is specified in ten basis point increments
uint256 purchaseIncentive =
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_INCENTIVE])) *
Constants.TEN_BASIS_POINTS;
if (fCashAmount > 0) {
// When fCash is positive then we add the purchase incentive, the purchaser
// can pay less cash for the fCash relative to the oracle rate
oracleRate = oracleRate.add(purchaseIncentive);
} else if (oracleRate > purchaseIncentive) {
// When fCash is negative, we reduce the interest rate that the purchaser will
// borrow at, we do this check to ensure that we floor the oracle rate at zero.
oracleRate = oracleRate.sub(purchaseIncentive);
} else {
// If the oracle rate is less than the purchase incentive floor the interest rate at zero
oracleRate = 0;
}
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(oracleRate, maturity.sub(blockTime));
// Returns the net asset cash from the nToken perspective, which is the same sign as the fCash amount
return
cashGroup.assetRate.convertFromUnderlying(fCashAmount.divInRatePrecision(exchangeRate));
}
function _updateNTokenPortfolio(
address nTokenAddress,
uint256 currencyId,
uint256 maturity,
uint256 lastInitializedTime,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
) private {
int256 finalNotional = BitmapAssetsHandler.addifCashAsset(
nTokenAddress,
currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase.neg() // the nToken takes on the negative position
);
// Defensive check to ensure that fCash amounts do not flip signs
require(
(fCashAmountToPurchase > 0 && finalNotional >= 0) ||
(fCashAmountToPurchase < 0 && finalNotional <= 0)
);
// prettier-ignore
(
int256 nTokenCashBalance,
/* storedNTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nTokenAddress, currencyId);
nTokenCashBalance = nTokenCashBalance.add(netAssetCashNToken);
// This will ensure that the cash balance is not negative
BalanceHandler.setBalanceStorageForNToken(nTokenAddress, currencyId, nTokenCashBalance);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/StorageLayoutV1.sol";
import "../../internal/nToken/nTokenHandler.sol";
abstract contract ActionGuards is StorageLayoutV1 {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
function initializeReentrancyGuard() internal {
require(reentrancyStatus == 0);
// Initialize the guard to a non-zero value, see the OZ reentrancy guard
// description for why this is more gas efficient:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol
reentrancyStatus = _NOT_ENTERED;
}
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(reentrancyStatus != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
reentrancyStatus = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
reentrancyStatus = _NOT_ENTERED;
}
// These accounts cannot receive deposits, transfers, fCash or any other
// types of value transfers.
function requireValidAccount(address account) internal view {
require(account != Constants.RESERVE); // Reserve address is address(0)
require(account != address(this));
(
uint256 isNToken,
/* incentiveAnnualEmissionRate */,
/* lastInitializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(account);
require(isNToken == 0);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenMintAction {
using SafeInt256 for int256;
using BalanceHandler for BalanceState;
using CashGroup for CashGroupParameters;
using Market for MarketParameters;
using nTokenHandler for nTokenPortfolio;
using PortfolioHandler for PortfolioState;
using AssetRate for AssetRateParameters;
using SafeMath for uint256;
using nTokenHandler for nTokenPortfolio;
/// @notice Converts the given amount of cash to nTokens in the same currency.
/// @param currencyId the currency associated the nToken
/// @param amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals
/// @return nTokens minted by this action
function nTokenMint(uint16 currencyId, int256 amountToDepositInternal)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
int256 tokensToMint = calculateTokensToMint(nToken, amountToDepositInternal, blockTime);
require(tokensToMint >= 0, "Invalid token amount");
if (nToken.portfolioState.storedAssets.length == 0) {
// If the token does not have any assets, then the markets must be initialized first.
nToken.cashBalance = nToken.cashBalance.add(amountToDepositInternal);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
currencyId,
nToken.cashBalance
);
} else {
_depositIntoPortfolio(nToken, amountToDepositInternal, blockTime);
}
// NOTE: token supply does not change here, it will change after incentives have been claimed
// during BalanceHandler.finalize
return tokensToMint;
}
/// @notice Calculates the tokens to mint to the account as a ratio of the nToken
/// present value denominated in asset cash terms.
/// @return the amount of tokens to mint, the ifCash bitmap
function calculateTokensToMint(
nTokenPortfolio memory nToken,
int256 amountToDepositInternal,
uint256 blockTime
) internal view returns (int256) {
require(amountToDepositInternal >= 0); // dev: deposit amount negative
if (amountToDepositInternal == 0) return 0;
if (nToken.lastInitializedTime != 0) {
// For the sake of simplicity, nTokens cannot be minted if they have assets
// that need to be settled. This is only done during market initialization.
uint256 nextSettleTime = nToken.getNextSettleTime();
// If next settle time <= blockTime then the token can be settled
require(nextSettleTime > blockTime, "Requires settlement");
}
int256 assetCashPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// Defensive check to ensure PV remains positive
require(assetCashPV >= 0);
// Allow for the first deposit
if (nToken.totalSupply == 0) {
return amountToDepositInternal;
} else {
// assetCashPVPost = assetCashPV + amountToDeposit
// (tokenSupply + tokensToMint) / tokenSupply == (assetCashPV + amountToDeposit) / assetCashPV
// (tokenSupply + tokensToMint) == (assetCashPV + amountToDeposit) * tokenSupply / assetCashPV
// (tokenSupply + tokensToMint) == tokenSupply + (amountToDeposit * tokenSupply) / assetCashPV
// tokensToMint == (amountToDeposit * tokenSupply) / assetCashPV
return amountToDepositInternal.mul(nToken.totalSupply).div(assetCashPV);
}
}
/// @notice Portions out assetCashDeposit into amounts to deposit into individual markets. When
/// entering this method we know that assetCashDeposit is positive and the nToken has been
/// initialized to have liquidity tokens.
function _depositIntoPortfolio(
nTokenPortfolio memory nToken,
int256 assetCashDeposit,
uint256 blockTime
) private {
(int256[] memory depositShares, int256[] memory leverageThresholds) =
nTokenHandler.getDepositParameters(
nToken.cashGroup.currencyId,
nToken.cashGroup.maxMarketIndex
);
// Loop backwards from the last market to the first market, the reasoning is a little complicated:
// If we have to deleverage the markets (i.e. lend instead of provide liquidity) it's quite gas inefficient
// to calculate the cash amount to lend. We do know that longer term maturities will have more
// slippage and therefore the residual from the perMarketDeposit will be lower as the maturities get
// closer to the current block time. Any residual cash from lending will be rolled into shorter
// markets as this loop progresses.
int256 residualCash;
MarketParameters memory market;
for (uint256 marketIndex = nToken.cashGroup.maxMarketIndex; marketIndex > 0; marketIndex--) {
int256 fCashAmount;
// Loads values into the market memory slot
nToken.cashGroup.loadMarket(
market,
marketIndex,
true, // Needs liquidity to true
blockTime
);
// If market has not been initialized, continue. This can occur when cash groups extend maxMarketIndex
// before initializing
if (market.totalLiquidity == 0) continue;
// Checked that assetCashDeposit must be positive before entering
int256 perMarketDeposit =
assetCashDeposit
.mul(depositShares[marketIndex - 1])
.div(Constants.DEPOSIT_PERCENT_BASIS)
.add(residualCash);
(fCashAmount, residualCash) = _lendOrAddLiquidity(
nToken,
market,
perMarketDeposit,
leverageThresholds[marketIndex - 1],
marketIndex,
blockTime
);
if (fCashAmount != 0) {
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
market.maturity,
nToken.lastInitializedTime,
fCashAmount
);
}
}
// nToken is allowed to store assets directly without updating account context.
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// Defensive check to ensure that we do not somehow accrue negative residual cash.
require(residualCash >= 0, "Negative residual cash");
// This will occur if the three month market is over levered and we cannot lend into it
if (residualCash > 0) {
// Any remaining residual cash will be put into the nToken balance and added as liquidity on the
// next market initialization
nToken.cashBalance = nToken.cashBalance.add(residualCash);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
}
/// @notice For a given amount of cash to deposit, decides how much to lend or provide
/// given the market conditions.
function _lendOrAddLiquidity(
nTokenPortfolio memory nToken,
MarketParameters memory market,
int256 perMarketDeposit,
int256 leverageThreshold,
uint256 marketIndex,
uint256 blockTime
) private returns (int256 fCashAmount, int256 residualCash) {
// We start off with the entire per market deposit as residuals
residualCash = perMarketDeposit;
// If the market is over leveraged then we will lend to it instead of providing liquidity
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
(residualCash, fCashAmount) = _deleverageMarket(
nToken.cashGroup,
market,
perMarketDeposit,
blockTime,
marketIndex
);
// Recalculate this after lending into the market, if it is still over leveraged then
// we will not add liquidity and just exit.
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
// Returns the residual cash amount
return (fCashAmount, residualCash);
}
}
// Add liquidity to the market only if we have successfully delevered.
// (marketIndex - 1) is the index of the nToken portfolio array where the asset is stored
// If deleveraged, residualCash is what remains
// If not deleveraged, residual cash is per market deposit
fCashAmount = fCashAmount.add(
_addLiquidityToMarket(nToken, market, marketIndex - 1, residualCash)
);
// No residual cash if we're adding liquidity
return (fCashAmount, 0);
}
/// @notice Markets are over levered when their proportion is greater than a governance set
/// threshold. At this point, providing liquidity will incur too much negative fCash on the nToken
/// account for the given amount of cash deposited, putting the nToken account at risk of liquidation.
/// If the market is over leveraged, we call `deleverageMarket` to lend to the market instead.
function _isMarketOverLeveraged(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 leverageThreshold
) private pure returns (bool) {
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// Comparison we want to do:
// (totalfCash) / (totalfCash + totalCashUnderlying) > leverageThreshold
// However, the division will introduce rounding errors so we change this to:
// totalfCash * RATE_PRECISION > leverageThreshold * (totalfCash + totalCashUnderlying)
// Leverage threshold is denominated in rate precision.
return (
market.totalfCash.mul(Constants.RATE_PRECISION) >
leverageThreshold.mul(market.totalfCash.add(totalCashUnderlying))
);
}
function _addLiquidityToMarket(
nTokenPortfolio memory nToken,
MarketParameters memory market,
uint256 index,
int256 perMarketDeposit
) private returns (int256) {
// Add liquidity to the market
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[index];
// We expect that all the liquidity tokens are in the portfolio in order.
require(
asset.maturity == market.maturity &&
// Ensures that the asset type references the proper liquidity token
asset.assetType == index + Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
// Ensures that the storage state will not be overwritten
asset.storageState == AssetStorageState.NoChange,
"PT: invalid liquidity token"
);
// This will update the market state as well, fCashAmount returned here is negative
(int256 liquidityTokens, int256 fCashAmount) = market.addLiquidity(perMarketDeposit);
asset.notional = asset.notional.add(liquidityTokens);
asset.storageState = AssetStorageState.Update;
return fCashAmount;
}
/// @notice Lends into the market to reduce the leverage that the nToken will add liquidity at. May fail due
/// to slippage or result in some amount of residual cash.
function _deleverageMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 perMarketDeposit,
uint256 blockTime,
uint256 marketIndex
) private returns (int256, int256) {
uint256 timeToMaturity = market.maturity.sub(blockTime);
// Shift the last implied rate by some buffer and calculate the exchange rate to fCash. Hope that this
// is sufficient to cover all potential slippage. We don't use the `getfCashGivenCashAmount` method here
// because it is very gas inefficient.
int256 assumedExchangeRate;
if (market.lastImpliedRate < Constants.DELEVERAGE_BUFFER) {
// Floor the exchange rate at zero interest rate
assumedExchangeRate = Constants.RATE_PRECISION;
} else {
assumedExchangeRate = Market.getExchangeRateFromImpliedRate(
market.lastImpliedRate.sub(Constants.DELEVERAGE_BUFFER),
timeToMaturity
);
}
int256 fCashAmount;
{
int256 perMarketDepositUnderlying =
cashGroup.assetRate.convertToUnderlying(perMarketDeposit);
// NOTE: cash * exchangeRate = fCash
fCashAmount = perMarketDepositUnderlying.mulInRatePrecision(assumedExchangeRate);
}
int256 netAssetCash = market.executeTrade(cashGroup, fCashAmount, timeToMaturity, marketIndex);
// This means that the trade failed
if (netAssetCash == 0) {
return (perMarketDeposit, 0);
} else {
// Ensure that net the per market deposit figure does not drop below zero, this should not be possible
// given how we've calculated the exchange rate but extra caution here
int256 residual = perMarketDeposit.add(netAssetCash);
require(residual >= 0); // dev: insufficient cash
return (residual, fCashAmount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../internal/markets/Market.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenRedeemAction {
using SafeInt256 for int256;
using SafeMath for uint256;
using Bitmap for bytes32;
using BalanceHandler for BalanceState;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using PortfolioHandler for PortfolioState;
using nTokenHandler for nTokenPortfolio;
/// @notice When redeeming nTokens via the batch they must all be sold to cash and this
/// method will return the amount of asset cash sold.
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @return amount of asset cash to return to the account, denominated in internal token decimals
function nTokenRedeemViaBatch(uint16 currencyId, int256 tokensToRedeem)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
// prettier-ignore
(
int256 totalAssetCash,
bool hasResidual,
/* PortfolioAssets[] memory newfCashAssets */
) = _redeem(currencyId, tokensToRedeem, true, false, blockTime);
require(!hasResidual, "Cannot redeem via batch, residual");
return totalAssetCash;
}
/// @notice Redeems nTokens for asset cash and fCash
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @param sellTokenAssets attempt to sell residual fCash and convert to cash, if unsuccessful then place
/// back into the account's portfolio
/// @param acceptResidualAssets if true, then ifCash residuals will be placed into the account and there will
/// be no penalty assessed
/// @return assetCash positive amount of asset cash to the account
/// @return hasResidual true if there are fCash residuals left
/// @return assets an array of fCash asset residuals to place into the account
function redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets
) external returns (int256, bool, PortfolioAsset[] memory) {
return _redeem(
currencyId,
tokensToRedeem,
sellTokenAssets,
acceptResidualAssets,
block.timestamp
);
}
function _redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets,
uint256 blockTime
) internal returns (int256, bool, PortfolioAsset[] memory) {
require(tokensToRedeem > 0);
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
// nTokens cannot be redeemed during the period of time where they require settlement.
require(nToken.getNextSettleTime() > blockTime, "Requires settlement");
require(tokensToRedeem < nToken.totalSupply, "Cannot redeem");
PortfolioAsset[] memory newifCashAssets;
// Get the ifCash bits that are idiosyncratic
bytes32 ifCashBits = nTokenCalculations.getNTokenifCashBits(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
if (ifCashBits != 0 && acceptResidualAssets) {
// This will remove all the ifCash assets proportionally from the account
newifCashAssets = _reduceifCashAssetsProportional(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
tokensToRedeem,
nToken.totalSupply,
ifCashBits
);
// Once the ifCash bits have been withdrawn, set this to zero so that getLiquidityTokenWithdraw
// simply gets the proportional amount of liquidity tokens to remove
ifCashBits = 0;
}
// Returns the liquidity tokens to withdraw per market and the netfCash amounts. Net fCash amounts are only
// set when ifCashBits != 0. Otherwise they must be calculated in _withdrawLiquidityTokens
(int256[] memory tokensToWithdraw, int256[] memory netfCash) = nTokenCalculations.getLiquidityTokenWithdraw(
nToken,
tokensToRedeem,
blockTime,
ifCashBits
);
// Returns the totalAssetCash as a result of withdrawing liquidity tokens and cash. netfCash will be updated
// in memory if required and will contain the fCash to be sold or returned to the portfolio
int256 totalAssetCash = _reduceLiquidAssets(
nToken,
tokensToRedeem,
tokensToWithdraw,
netfCash,
ifCashBits == 0, // If there are no residuals then we need to populate netfCash amounts
blockTime
);
bool netfCashRemaining = true;
if (sellTokenAssets) {
int256 assetCash;
// NOTE: netfCash is modified in place and set to zero if the fCash is sold
(assetCash, netfCashRemaining) = _sellfCashAssets(nToken, netfCash, blockTime);
totalAssetCash = totalAssetCash.add(assetCash);
}
if (netfCashRemaining) {
// If the account is unwilling to accept residuals then will fail here.
require(acceptResidualAssets, "Residuals");
newifCashAssets = _addResidualsToAssets(nToken.portfolioState.storedAssets, newifCashAssets, netfCash);
}
return (totalAssetCash, netfCashRemaining, newifCashAssets);
}
/// @notice Removes liquidity tokens and cash from the nToken
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @param blockTime current block time
/// @return assetCashShare amount of cash the redeemer will receive from withdrawing cash assets from the nToken
function _reduceLiquidAssets(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
bool mustCalculatefCash,
uint256 blockTime
) private returns (int256 assetCashShare) {
// Get asset cash share for the nToken, if it exists. It is required in balance handler that the
// nToken can never have a negative cash asset cash balance so what we get here is always positive
// or zero.
assetCashShare = nToken.cashBalance.mul(nTokensToRedeem).div(nToken.totalSupply);
if (assetCashShare > 0) {
nToken.cashBalance = nToken.cashBalance.subNoNeg(assetCashShare);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
// Get share of liquidity tokens to remove, netfCash is modified in memory during this method if mustCalculatefcash
// is set to true
assetCashShare = assetCashShare.add(
_removeLiquidityTokens(nToken, nTokensToRedeem, tokensToWithdraw, netfCash, blockTime, mustCalculatefCash)
);
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// NOTE: Token supply change will happen when we finalize balances and after minting of incentives
return assetCashShare;
}
/// @notice Removes nToken liquidity tokens and updates the netfCash figures.
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param blockTime current block time
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @return totalAssetCashClaims is the amount of asset cash raised from liquidity token cash claims
function _removeLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
uint256 blockTime,
bool mustCalculatefCash
) private returns (int256 totalAssetCashClaims) {
MarketParameters memory market;
for (uint256 i = 0; i < nToken.portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[i];
asset.notional = asset.notional.sub(tokensToWithdraw[i]);
// Cannot redeem liquidity tokens down to zero or this will cause many issues with
// market initialization.
require(asset.notional > 0, "Cannot redeem to zero");
require(asset.storageState == AssetStorageState.NoChange);
asset.storageState = AssetStorageState.Update;
// This will load a market object in memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
int256 fCashClaim;
{
int256 assetCash;
// Remove liquidity from the market
(assetCash, fCashClaim) = market.removeLiquidity(tokensToWithdraw[i]);
totalAssetCashClaims = totalAssetCashClaims.add(assetCash);
}
int256 fCashToNToken;
if (mustCalculatefCash) {
// Do this calculation if net ifCash is not set, will happen if there are no residuals
int256 fCashShare = BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
asset.maturity
);
fCashShare = fCashShare.mul(nTokensToRedeem).div(nToken.totalSupply);
// netfCash = fCashClaim + fCashShare
netfCash[i] = fCashClaim.add(fCashShare);
fCashToNToken = fCashShare.neg();
} else {
// Account will receive netfCash amount. Deduct that from the fCash claim and add the
// remaining back to the nToken to net off the nToken's position
// fCashToNToken = -fCashShare
// netfCash = fCashClaim + fCashShare
// fCashToNToken = -(netfCash - fCashClaim)
// fCashToNToken = fCashClaim - netfCash
fCashToNToken = fCashClaim.sub(netfCash[i]);
}
// Removes the account's fCash position from the nToken
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
asset.currencyId,
asset.maturity,
nToken.lastInitializedTime,
fCashToNToken
);
}
return totalAssetCashClaims;
}
/// @notice Sells fCash assets back into the market for cash. Negative fCash assets will decrease netAssetCash
/// as a result. The aim here is to ensure that accounts can redeem nTokens without having to take on
/// fCash assets.
function _sellfCashAssets(
nTokenPortfolio memory nToken,
int256[] memory netfCash,
uint256 blockTime
) private returns (int256 totalAssetCash, bool hasResidual) {
MarketParameters memory market;
hasResidual = false;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] == 0) continue;
nToken.cashGroup.loadMarket(market, i + 1, false, blockTime);
int256 netAssetCash = market.executeTrade(
nToken.cashGroup,
// Use the negative of fCash notional here since we want to net it out
netfCash[i].neg(),
nToken.portfolioState.storedAssets[i].maturity.sub(blockTime),
i + 1
);
if (netAssetCash == 0) {
// This means that the trade failed
hasResidual = true;
} else {
totalAssetCash = totalAssetCash.add(netAssetCash);
netfCash[i] = 0;
}
}
}
/// @notice Combines newifCashAssets array with netfCash assets into a single finalfCashAssets array
function _addResidualsToAssets(
PortfolioAsset[] memory liquidityTokens,
PortfolioAsset[] memory newifCashAssets,
int256[] memory netfCash
) internal pure returns (PortfolioAsset[] memory finalfCashAssets) {
uint256 numAssetsToExtend;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] != 0) numAssetsToExtend++;
}
uint256 newLength = newifCashAssets.length + numAssetsToExtend;
finalfCashAssets = new PortfolioAsset[](newLength);
uint index = 0;
for (; index < newifCashAssets.length; index++) {
finalfCashAssets[index] = newifCashAssets[index];
}
uint netfCashIndex = 0;
for (; index < finalfCashAssets.length; ) {
if (netfCash[netfCashIndex] != 0) {
PortfolioAsset memory asset = finalfCashAssets[index];
asset.currencyId = liquidityTokens[netfCashIndex].currencyId;
asset.maturity = liquidityTokens[netfCashIndex].maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = netfCash[netfCashIndex];
index++;
}
netfCashIndex++;
}
return finalfCashAssets;
}
/// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming
/// nTokens to its underlying assets.
function _reduceifCashAssetsProportional(
address account,
uint256 currencyId,
uint256 lastInitializedTime,
int256 tokensToRedeem,
int256 totalSupply,
bytes32 assetsBitmap
) internal returns (PortfolioAsset[] memory) {
uint256 index = assetsBitmap.totalBitsSet();
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(lastInitializedTime, bitNum);
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
int256 notional = fCashSlot.notional;
int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply);
int256 finalNotional = notional.sub(notionalToTransfer);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notionalToTransfer;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../internal/portfolio/PortfolioHandler.sol";
import "../internal/balances/BalanceHandler.sol";
import "../internal/settlement/SettlePortfolioAssets.sol";
import "../internal/settlement/SettleBitmapAssets.sol";
import "../internal/AccountContextHandler.sol";
/// @notice External library for settling assets
library SettleAssetsExternal {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
event AccountSettled(address indexed account);
/// @notice Settles an account, returns the new account context object after settlement.
/// @dev The memory location of the account context object is not the same as the one returned.
function settleAccount(
address account,
AccountContext memory accountContext
) external returns (AccountContext memory) {
// Defensive check to ensure that this is a valid settlement
require(accountContext.mustSettleAssets());
SettleAmount[] memory settleAmounts;
PortfolioState memory portfolioState;
if (accountContext.isBitmapEnabled()) {
(int256 settledCash, uint256 blockTimeUTC0) =
SettleBitmapAssets.settleBitmappedCashGroup(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
block.timestamp
);
require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow
accountContext.nextSettleTime = uint40(blockTimeUTC0);
settleAmounts = new SettleAmount[](1);
settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash);
} else {
portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp);
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts);
emit AccountSettled(account);
return accountContext;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../external/SettleAssetsExternal.sol";
import "../internal/AccountContextHandler.sol";
import "../internal/valuation/FreeCollateral.sol";
/// @title Externally deployed library for free collateral calculations
library FreeCollateralExternal {
using AccountContextHandler for AccountContext;
/// @notice Returns the ETH denominated free collateral of an account, represents the amount of
/// debt that the account can incur before liquidation. If an account's assets need to be settled this
/// will revert, either settle the account or use the off chain SDK to calculate free collateral.
/// @dev Called via the Views.sol method to return an account's free collateral. Does not work
/// for the nToken, the nToken does not have an account context.
/// @param account account to calculate free collateral for
/// @return total free collateral in ETH w/ 8 decimal places
/// @return array of net local values in asset values ordered by currency id
function getFreeCollateralView(address account)
external
view
returns (int256, int256[] memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
// The internal free collateral function does not account for settled assets. The Notional SDK
// can calculate the free collateral off chain if required at this point.
require(!accountContext.mustSettleAssets(), "Assets not settled");
return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp);
}
/// @notice Calculates free collateral and will revert if it falls below zero. If the account context
/// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets
/// need to be settled first.
/// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be
/// called before the end of any transaction for accounts where FC can decrease.
/// @param account account to calculate free collateral for
function checkFreeCollateralAndRevert(address account) external {
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
require(!accountContext.mustSettleAssets(), "Assets not settled");
(int256 ethDenominatedFC, bool updateContext) =
FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp);
if (updateContext) {
accountContext.setAccountContext(account);
}
require(ethDenominatedFC >= 0, "Insufficient free collateral");
}
/// @notice Calculates liquidation factors for an account
/// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is
/// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then
/// liquidation actions will revert.
/// @dev an ntoken account will return 0 FC and revert if called
/// @param account account to liquidate
/// @param localCurrencyId currency that the debts are denominated in
/// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation
/// @return accountContext the accountContext of the liquidated account
/// @return factors struct of relevant factors for liquidation
/// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array)
function getLiquidationFactors(
address account,
uint256 localCurrencyId,
uint256 collateralCurrencyId
)
external
returns (
AccountContext memory accountContext,
LiquidationFactors memory factors,
PortfolioAsset[] memory portfolio
)
{
accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
accountContext = SettleAssetsExternal.settleAccount(account, accountContext);
}
if (accountContext.isBitmapEnabled()) {
// A bitmap currency can only ever hold debt in this currency
require(localCurrencyId == accountContext.bitmapCurrencyId);
}
(factors, portfolio) = FreeCollateral.getLiquidationFactors(
account,
accountContext,
block.timestamp,
localCurrencyId,
collateralCurrencyId
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../global/Constants.sol";
library SafeInt256 {
int256 private constant _INT256_MIN = type(int256).min;
/// @dev Returns the multiplication of two signed integers, reverting on
/// overflow.
/// Counterpart to Solidity's `*` operator.
/// Requirements:
/// - Multiplication cannot overflow.
function mul(int256 a, int256 b) internal pure returns (int256 c) {
c = a * b;
if (a == -1) require (b == 0 || c / b == a);
else require (a == 0 || c / a == b);
}
/// @dev Returns the integer division of two signed integers. Reverts on
/// division by zero. The result is rounded towards zero.
/// Counterpart to Solidity's `/` operator. Note: this function uses a
/// `revert` opcode (which leaves remaining gas untouched) while Solidity
/// uses an invalid opcode to revert (consuming all remaining gas).
/// Requirements:
/// - The divisor cannot be zero.
function div(int256 a, int256 b) internal pure returns (int256 c) {
require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow
// NOTE: solidity will automatically revert on divide by zero
c = a / b;
}
function sub(int256 x, int256 y) internal pure returns (int256 z) {
// taken from uniswap v3
require((z = x - y) <= x == (y >= 0));
}
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
function neg(int256 x) internal pure returns (int256 y) {
return mul(-1, x);
}
function abs(int256 x) internal pure returns (int256) {
if (x < 0) return neg(x);
else return x;
}
function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) {
z = sub(x, y);
require(z >= 0); // dev: int256 sub to negative
return z;
}
/// @dev Calculates x * RATE_PRECISION / y while checking overflows
function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, Constants.RATE_PRECISION), y);
}
/// @dev Calculates x * y / RATE_PRECISION while checking overflows
function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, y), Constants.RATE_PRECISION);
}
function toUint(int256 x) internal pure returns (uint256) {
require(x >= 0);
return uint256(x);
}
function toInt(uint256 x) internal pure returns (int256) {
require (x <= uint256(type(int256).max)); // dev: toInt overflow
return int256(x);
}
function max(int256 x, int256 y) internal pure returns (int256) {
return x > y ? x : y;
}
function min(int256 x, int256 y) internal pure returns (int256) {
return x < y ? x : y;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
/**
* @notice Storage layout for the system. Do not change this file once deployed, future storage
* layouts must inherit this and increment the version number.
*/
contract StorageLayoutV1 {
// The current maximum currency id
uint16 internal maxCurrencyId;
// Sets the state of liquidations being enabled during a paused state. Each of the four lower
// bits can be turned on to represent one of the liquidation types being enabled.
bytes1 internal liquidationEnabledState;
// Set to true once the system has been initialized
bool internal hasInitialized;
/* Authentication Mappings */
// This is set to the timelock contract to execute governance functions
address public owner;
// This is set to an address of a router that can only call governance actions
address public pauseRouter;
// This is set to an address of a router that can only call governance actions
address public pauseGuardian;
// On upgrades this is set in the case that the pause router is used to pass the rollback check
address internal rollbackRouterImplementation;
// A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user
// to set an allowance on all nTokens for a particular integrating contract system.
// owner => spender => transferAllowance
mapping(address => mapping(address => uint256)) internal nTokenWhitelist;
// Individual transfer allowances for nTokens used for ERC20
// owner => spender => currencyId => transferAllowance
mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance;
// Transfer operators
// Mapping from a global ERC1155 transfer operator contract to an approval value for it
mapping(address => bool) internal globalTransferOperator;
// Mapping from an account => operator => approval status for that operator. This is a specific
// approval between two addresses for ERC1155 transfers.
mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator;
// Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in
// BatchAction.sol, can only be set by governance
mapping(address => bool) internal authorizedCallbackContract;
// Reverse mapping from token addresses to currency ids, only used for referencing in views
// and checking for duplicate token listings.
mapping(address => uint16) internal tokenAddressToCurrencyId;
// Reentrancy guard
uint256 internal reentrancyStatus;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Incentives.sol";
import "./TokenHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/FloatingPoint56.sol";
library BalanceHandler {
using SafeInt256 for int256;
using TokenHandler for Token;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
/// @notice Emitted when a cash balance changes
event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange);
/// @notice Emitted when nToken supply changes (not the same as transfers)
event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange);
/// @notice Emitted when reserve fees are accrued
event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee);
/// @notice Emitted when reserve balance is updated
event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance);
/// @notice Emitted when reserve balance is harvested
event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount);
/// @notice Deposits asset tokens into an account
/// @dev Handles two special cases when depositing tokens into an account.
/// - If a token has transfer fees then the amount specified does not equal the amount that the contract
/// will receive. Complete the deposit here rather than in finalize so that the contract has the correct
/// balance to work with.
/// - Force a transfer before finalize to allow a different account to deposit into an account
/// @return assetAmountInternal which is the converted asset amount accounting for transfer fees
function depositAssetToken(
BalanceState memory balanceState,
address account,
int256 assetAmountExternal,
bool forceTransfer
) internal returns (int256 assetAmountInternal) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0); // dev: deposit asset token amount negative
Token memory token = TokenHandler.getAssetToken(balanceState.currencyId);
if (token.tokenType == TokenType.aToken) {
// Handles special accounting requirements for aTokens
assetAmountExternal = AaveHandler.convertToScaledBalanceExternal(
balanceState.currencyId,
assetAmountExternal
);
}
// Force transfer is used to complete the transfer before going to finalize
if (token.hasTransferFee || forceTransfer) {
// If the token has a transfer fee the deposit amount may not equal the actual amount
// that the contract will receive. We handle the deposit here and then update the netCashChange
// accordingly which is denominated in internal precision.
int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal);
// Convert the external precision to internal, it's possible that we lose dust amounts here but
// this is unavoidable because we do not know how transfer fees are calculated.
assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal);
// Transfer has been called
balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal);
return assetAmountInternal;
} else {
assetAmountInternal = token.convertToInternal(assetAmountExternal);
// Otherwise add the asset amount here. It may be net off later and we want to only do
// a single transfer during the finalize method. Use internal precision to ensure that internal accounting
// and external account remain in sync.
// Transfer will be deferred
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.add(assetAmountInternal);
// Returns the converted assetAmountExternal to the internal amount
return assetAmountInternal;
}
}
/// @notice Handle deposits of the underlying token
/// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up
/// with any underlying tokens left as dust on the contract.
function depositUnderlyingToken(
BalanceState memory balanceState,
address account,
int256 underlyingAmountExternal
) internal returns (int256) {
if (underlyingAmountExternal == 0) return 0;
require(underlyingAmountExternal > 0); // dev: deposit underlying token negative
Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId);
// This is the exact amount of underlying tokens the account has in external precision.
if (underlyingToken.tokenType == TokenType.Ether) {
// Underflow checked above
require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance");
} else {
underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal);
}
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
int256 assetTokensReceivedExternalPrecision =
assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal));
// cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different
// type of asset token is listed in the future. It's possible if those tokens have a different precision dust may
// accrue but that is not relevant now.
int256 assetTokensReceivedInternal =
assetToken.convertToInternal(assetTokensReceivedExternalPrecision);
// Transfer / mint has taken effect
balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal);
return assetTokensReceivedInternal;
}
/// @notice Finalizes an account's balances, handling any transfer logic required
/// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken
/// as the nToken is limited in what types of balances it can hold.
function finalize(
BalanceState memory balanceState,
address account,
AccountContext memory accountContext,
bool redeemToUnderlying
) internal returns (int256 transferAmountExternal) {
bool mustUpdate;
if (balanceState.netNTokenTransfer < 0) {
require(
balanceState.storedNTokenBalance
.add(balanceState.netNTokenSupplyChange)
.add(balanceState.netNTokenTransfer) >= 0,
"Neg nToken"
);
}
if (balanceState.netAssetTransferInternalPrecision < 0) {
require(
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= 0,
"Neg Cash"
);
}
// Transfer amount is checked inside finalize transfers in case when converting to external we
// round down to zero. This returns the actual net transfer in internal precision as well.
(
transferAmountExternal,
balanceState.netAssetTransferInternalPrecision
) = _finalizeTransfers(balanceState, account, redeemToUnderlying);
// No changes to total cash after this point
int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision);
if (totalCashChange != 0) {
balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange);
mustUpdate = true;
emit CashBalanceChange(
account,
uint16(balanceState.currencyId),
totalCashChange
);
}
if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) {
// Final nToken balance is used to calculate the account incentive debt
int256 finalNTokenBalance = balanceState.storedNTokenBalance
.add(balanceState.netNTokenTransfer)
.add(balanceState.netNTokenSupplyChange);
// The toUint() call here will ensure that nToken balances never become negative
Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint());
balanceState.storedNTokenBalance = finalNTokenBalance;
if (balanceState.netNTokenSupplyChange != 0) {
emit nTokenSupplyChange(
account,
uint16(balanceState.currencyId),
balanceState.netNTokenSupplyChange
);
}
mustUpdate = true;
}
if (mustUpdate) {
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
accountContext.setActiveCurrency(
balanceState.currencyId,
// Set active currency to true if either balance is non-zero
balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (balanceState.storedCashBalance < 0) {
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances
// are examined
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
}
/// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying
/// is specified.
function _finalizeTransfers(
BalanceState memory balanceState,
address account,
bool redeemToUnderlying
) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) {
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
// Dust accrual to the protocol is possible if the token decimals is less than internal token precision.
// See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal
int256 assetTransferAmountExternal =
assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision);
if (assetTransferAmountExternal == 0) {
return (0, 0);
} else if (redeemToUnderlying && assetTransferAmountExternal < 0) {
// We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than
// zero then we will do a normal transfer instead.
// We use the internal amount here and then scale it to the external amount so that there is
// no loss of precision between our internal accounting and the external account. In this case
// there will be no dust accrual in underlying tokens since we will transfer the exact amount
// of underlying that was received.
actualTransferAmountExternal = assetToken.redeem(
balanceState.currencyId,
account,
// No overflow, checked above
uint256(assetTransferAmountExternal.neg())
);
// In this case we're transferring underlying tokens, we want to convert the internal
// asset transfer amount to store in cash balances
assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal);
} else {
// NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it
// will be converted to balanceOf denomination inside transfer
actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal);
// Convert the actual transferred amount
assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal);
}
}
/// @notice Special method for settling negative current cash debts. This occurs when an account
/// has a negative fCash balance settle to cash. A settler may come and force the account to borrow
/// at the prevailing 3 month rate
/// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary.
function setBalanceStorageForSettleCashDebt(
address account,
CashGroupParameters memory cashGroup,
int256 amountToSettleAsset,
AccountContext memory accountContext
) internal returns (int256) {
require(amountToSettleAsset >= 0); // dev: amount to settle negative
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, cashGroup.currencyId);
// Prevents settlement of positive balances
require(cashBalance < 0, "Invalid settle balance");
if (amountToSettleAsset == 0) {
// Symbolizes that the entire debt should be settled
amountToSettleAsset = cashBalance.neg();
cashBalance = 0;
} else {
// A partial settlement of the debt
require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle");
cashBalance = cashBalance.add(amountToSettleAsset);
}
// NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances
// also have cash debts
if (cashBalance == 0 && nTokenBalance == 0) {
accountContext.setActiveCurrency(
cashGroup.currencyId,
false,
Constants.ACTIVE_IN_BALANCES
);
}
_setBalanceStorage(
account,
cashGroup.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset);
return amountToSettleAsset;
}
/**
* @notice A special balance storage method for fCash liquidation to reduce the bytecode size.
*/
function setBalanceStorageForfCashLiquidation(
address account,
AccountContext memory accountContext,
uint16 currencyId,
int256 netCashChange
) internal {
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, currencyId);
int256 newCashBalance = cashBalance.add(netCashChange);
// If a cash balance is negative already we cannot put an account further into debt. In this case
// the netCashChange must be positive so that it is coming out of debt.
if (newCashBalance < 0) {
require(netCashChange > 0, "Neg Cash");
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check
// where all balances are examined. In this case the has cash debt flag should
// already be set (cash balances cannot get more negative) but we do it again
// here just to be safe.
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
bool isActive = newCashBalance != 0 || nTokenBalance != 0;
accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, currencyId, netCashChange);
_setBalanceStorage(
account,
currencyId,
newCashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
/// @notice Helper method for settling the output of the SettleAssets method
function finalizeSettleAmounts(
address account,
AccountContext memory accountContext,
SettleAmount[] memory settleAmounts
) internal {
for (uint256 i = 0; i < settleAmounts.length; i++) {
SettleAmount memory amt = settleAmounts[i];
if (amt.netCashChange == 0) continue;
(
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) = getBalanceStorage(account, amt.currencyId);
cashBalance = cashBalance.add(amt.netCashChange);
accountContext.setActiveCurrency(
amt.currencyId,
cashBalance != 0 || nTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (cashBalance < 0) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
emit CashBalanceChange(
account,
uint16(amt.currencyId),
amt.netCashChange
);
_setBalanceStorage(
account,
amt.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
}
/// @notice Special method for setting balance storage for nToken
function setBalanceStorageForNToken(
address nTokenAddress,
uint256 currencyId,
int256 cashBalance
) internal {
require(cashBalance >= 0); // dev: invalid nToken cash balance
_setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0);
}
/// @notice increments fees to the reserve
function incrementFeeToReserve(uint256 currencyId, int256 fee) internal {
require(fee >= 0); // dev: invalid fee
// prettier-ignore
(int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId);
totalReserve = totalReserve.add(fee);
_setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0);
emit ReserveFeeAccrued(uint16(currencyId), fee);
}
/// @notice harvests excess reserve balance
function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal {
// parameters are validated by the caller
reserve = reserve.subNoNeg(assetInternalRedeemAmount);
_setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0);
emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount);
}
/// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance
function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal {
require(newBalance >= 0); // dev: invalid balance
_setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0);
emit ReserveBalanceUpdated(currencyId, newBalance);
}
/// @notice Sets internal balance storage.
function _setBalanceStorage(
address account,
uint256 currencyId,
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) private {
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow
// Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow
require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow
if (lastClaimTime == 0) {
// In this case the account has migrated and we set the accountIncentiveDebt
// The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never
// encounter an overflow for accountIncentiveDebt
require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow
balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt);
} else {
// In this case the last claim time has not changed and we do not update the last integral supply
// (stored in the accountIncentiveDebt position)
require(lastClaimTime == balanceStorage.lastClaimTime);
}
balanceStorage.lastClaimTime = uint32(lastClaimTime);
balanceStorage.nTokenBalance = uint80(nTokenBalance);
balanceStorage.cashBalance = int88(cashBalance);
}
/// @notice Gets internal balance storage, nTokens are stored alongside cash balances
function getBalanceStorage(address account, uint256 currencyId)
internal
view
returns (
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
)
{
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
nTokenBalance = balanceStorage.nTokenBalance;
lastClaimTime = balanceStorage.lastClaimTime;
if (lastClaimTime > 0) {
// NOTE: this is only necessary to support the deprecated integral supply values, which are stored
// in the accountIncentiveDebt slot
accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt);
} else {
accountIncentiveDebt = balanceStorage.accountIncentiveDebt;
}
cashBalance = balanceStorage.cashBalance;
}
/// @notice Loads a balance state memory object
/// @dev Balance state objects occupy a lot of memory slots, so this method allows
/// us to reuse them if possible
function loadBalanceState(
BalanceState memory balanceState,
address account,
uint16 currencyId,
AccountContext memory accountContext
) internal view {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
balanceState.currencyId = currencyId;
if (accountContext.isActiveInBalances(currencyId)) {
(
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
) = getBalanceStorage(account, currencyId);
} else {
balanceState.storedCashBalance = 0;
balanceState.storedNTokenBalance = 0;
balanceState.lastClaimTime = 0;
balanceState.accountIncentiveDebt = 0;
}
balanceState.netCashChange = 0;
balanceState.netAssetTransferInternalPrecision = 0;
balanceState.netNTokenTransfer = 0;
balanceState.netNTokenSupplyChange = 0;
}
/// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state
/// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts
/// are migrated to the new incentive calculation
function claimIncentivesManual(BalanceState memory balanceState, address account)
internal
returns (uint256 incentivesClaimed)
{
incentivesClaimed = Incentives.claimIncentives(
balanceState,
account,
balanceState.storedNTokenBalance.toUint()
);
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TransferAssets.sol";
import "../valuation/AssetHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
/// @notice Handles the management of an array of assets including reading from storage, inserting
/// updating, deleting and writing back to storage.
library PortfolioHandler {
using SafeInt256 for int256;
using AssetHandler for PortfolioAsset;
// Mirror of LibStorage.MAX_PORTFOLIO_ASSETS
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @notice Primarily used by the TransferAssets library
function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets)
internal
pure
{
for (uint256 i = 0; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
addAsset(
portfolioState,
asset.currencyId,
asset.maturity,
asset.assetType,
asset.notional
);
}
}
function _mergeAssetIntoArray(
PortfolioAsset[] memory assetArray,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) private pure returns (bool) {
for (uint256 i = 0; i < assetArray.length; i++) {
PortfolioAsset memory asset = assetArray[i];
if (
asset.assetType != assetType ||
asset.currencyId != currencyId ||
asset.maturity != maturity
) continue;
// Either of these storage states mean that some error in logic has occurred, we cannot
// store this portfolio
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: portfolio handler deleted storage
int256 newNotional = asset.notional.add(notional);
// Liquidity tokens cannot be reduced below zero.
if (AssetHandler.isLiquidityToken(assetType)) {
require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow
asset.notional = newNotional;
asset.storageState = AssetStorageState.Update;
return true;
}
return false;
}
/// @notice Adds an asset to a portfolio state in memory (does not write to storage)
/// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity
/// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional.
function addAsset(
PortfolioState memory portfolioState,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) internal pure {
if (
// Will return true if merged
_mergeAssetIntoArray(
portfolioState.storedAssets,
currencyId,
maturity,
assetType,
notional
)
) return;
if (portfolioState.lastNewAssetIndex > 0) {
bool merged = _mergeAssetIntoArray(
portfolioState.newAssets,
currencyId,
maturity,
assetType,
notional
);
if (merged) return;
}
// At this point if we have not merged the asset then append to the array
// Cannot remove liquidity that the portfolio does not have
if (AssetHandler.isLiquidityToken(assetType)) {
require(notional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow
// Need to provision a new array at this point
if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) {
portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets);
}
// Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will
// check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct.
PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex];
newAsset.currencyId = currencyId;
newAsset.maturity = maturity;
newAsset.assetType = assetType;
newAsset.notional = notional;
newAsset.storageState = AssetStorageState.NoChange;
portfolioState.lastNewAssetIndex += 1;
}
/// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do
/// it too much
function _extendNewAssetArray(PortfolioAsset[] memory newAssets)
private
pure
returns (PortfolioAsset[] memory)
{
// Double the size of the new asset array every time we have to extend to reduce the number of times
// that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there).
uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2;
PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength);
for (uint256 i = 0; i < newAssets.length; i++) {
extendedArray[i] = newAssets[i];
}
return extendedArray;
}
/// @notice Takes a portfolio state and writes it to storage.
/// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via
/// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library.
/// @return updated variables to update the account context with
/// hasDebt: whether or not the portfolio has negative fCash assets
/// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio
/// uint8: the length of the storage array
/// uint40: the new nextSettleTime for the portfolio
function storeAssets(PortfolioState memory portfolioState, address account)
internal
returns (
bool,
bytes32,
uint8,
uint40
)
{
bool hasDebt;
// NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is
// set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate
// 7 additional fCash assets for a total of 14 assets. Although even in this case all assets
// would be of the same currency so it would not change the end result of the active currency
// calculation.
bytes32 portfolioActiveCurrencies;
uint256 nextSettleTime;
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler
// during valuation.
require(asset.storageState != AssetStorageState.RevertIfStored);
// Mark any zero notional assets as deleted
if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) {
deleteAsset(portfolioState, i);
}
}
// First delete assets from asset storage to maintain asset storage indexes
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
if (asset.storageState == AssetStorageState.Delete) {
// Delete asset from storage
uint256 currentSlot = asset.storageSlot;
assembly {
sstore(currentSlot, 0x00)
}
} else {
if (asset.storageState == AssetStorageState.Update) {
PortfolioAssetStorage storage assetStorage;
uint256 currentSlot = asset.storageSlot;
assembly {
assetStorage.slot := currentSlot
}
_storeAsset(asset, assetStorage);
}
// Update portfolio context for every asset that is in storage, whether it is
// updated in storage or not.
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
}
}
// Add new assets
uint256 assetStorageLength = portfolioState.storedAssetLength;
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
for (uint256 i = 0; i < portfolioState.newAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.newAssets[i];
if (asset.notional == 0) continue;
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: store assets deleted storage
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
_storeAsset(asset, storageArray[assetStorageLength]);
assetStorageLength += 1;
}
// 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with
// 2 bytes per currency
require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow
return (
hasDebt,
portfolioActiveCurrencies,
uint8(assetStorageLength),
uint40(nextSettleTime)
);
}
/// @notice Updates context information during the store assets method
function _updatePortfolioContext(
PortfolioAsset memory asset,
bool hasDebt,
bytes32 portfolioActiveCurrencies,
uint256 nextSettleTime
)
private
pure
returns (
bool,
bytes32,
uint256
)
{
uint256 settlementDate = asset.getSettlementDate();
// Tis will set it to the minimum settlement date
if (nextSettleTime == 0 || nextSettleTime > settlementDate) {
nextSettleTime = settlementDate;
}
hasDebt = hasDebt || asset.notional < 0;
require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow
portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240);
return (hasDebt, portfolioActiveCurrencies, nextSettleTime);
}
/// @dev Encodes assets for storage
function _storeAsset(
PortfolioAsset memory asset,
PortfolioAssetStorage storage assetStorage
) internal {
require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow
require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow
require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid
require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow
assetStorage.currencyId = uint16(asset.currencyId);
assetStorage.maturity = uint40(asset.maturity);
assetStorage.assetType = uint8(asset.assetType);
assetStorage.notional = int88(asset.notional);
}
/// @notice Deletes an asset from a portfolio
/// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement
/// by adding the offsetting negative position
function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure {
require(index < portfolioState.storedAssets.length); // dev: stored assets bounds
require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero
PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index];
require(
assetToDelete.storageState != AssetStorageState.Delete &&
assetToDelete.storageState != AssetStorageState.RevertIfStored
); // dev: cannot delete asset
portfolioState.storedAssetLength -= 1;
uint256 maxActiveSlotIndex;
uint256 maxActiveSlot;
// The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the
// array so we search for it here.
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory a = portfolioState.storedAssets[i];
if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) {
maxActiveSlot = a.storageSlot;
maxActiveSlotIndex = i;
}
}
if (index == maxActiveSlotIndex) {
// In this case we are deleting the asset with the max storage slot so no swap is necessary.
assetToDelete.storageState = AssetStorageState.Delete;
return;
}
// Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly
// so that when we call store assets they will be updated appropriately
PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex];
(
assetToSwap.storageSlot,
assetToDelete.storageSlot
) = (
assetToDelete.storageSlot,
assetToSwap.storageSlot
);
assetToSwap.storageState = AssetStorageState.Update;
assetToDelete.storageState = AssetStorageState.Delete;
}
/// @notice Returns a portfolio array, will be sorted
function getSortedPortfolio(address account, uint8 assetArrayLength)
internal
view
returns (PortfolioAsset[] memory)
{
PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength);
// No sorting required for length of 1
if (assets.length <= 1) return assets;
_sortInPlace(assets);
return assets;
}
/// @notice Builds a portfolio array from storage. The new assets hint parameter will
/// be used to provision a new array for the new assets. This will increase gas efficiency
/// so that we don't have to make copies when we extend the array.
function buildPortfolioState(
address account,
uint8 assetArrayLength,
uint256 newAssetsHint
) internal view returns (PortfolioState memory) {
PortfolioState memory state;
if (assetArrayLength == 0) return state;
state.storedAssets = getSortedPortfolio(account, assetArrayLength);
state.storedAssetLength = assetArrayLength;
state.newAssets = new PortfolioAsset[](newAssetsHint);
return state;
}
function _sortInPlace(PortfolioAsset[] memory assets) private pure {
uint256 length = assets.length;
uint256[] memory ids = new uint256[](length);
for (uint256 k; k < length; k++) {
PortfolioAsset memory asset = assets[k];
// Prepopulate the ids to calculate just once
ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType);
}
// Uses insertion sort
uint256 i = 1;
while (i < length) {
uint256 j = i;
while (j > 0 && ids[j - 1] > ids[j]) {
// Swap j - 1 and j
(ids[j - 1], ids[j]) = (ids[j], ids[j - 1]);
(assets[j - 1], assets[j]) = (assets[j], assets[j - 1]);
j--;
}
i++;
}
}
function _loadAssetArray(address account, uint8 length)
private
view
returns (PortfolioAsset[] memory)
{
// This will overflow the storage pointer
require(length <= MAX_PORTFOLIO_ASSETS);
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
PortfolioAsset[] memory assets = new PortfolioAsset[](length);
for (uint256 i = 0; i < length; i++) {
PortfolioAssetStorage storage assetStorage = storageArray[i];
PortfolioAsset memory asset = assets[i];
uint256 slot;
assembly {
slot := assetStorage.slot
}
asset.currencyId = assetStorage.currencyId;
asset.maturity = assetStorage.maturity;
asset.assetType = assetStorage.assetType;
asset.notional = assetStorage.notional;
asset.storageSlot = slot;
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "./balances/BalanceHandler.sol";
import "./portfolio/BitmapAssetsHandler.sol";
import "./portfolio/PortfolioHandler.sol";
library AccountContextHandler {
using PortfolioHandler for PortfolioState;
bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF;
event AccountContextUpdate(address indexed account);
/// @notice Returns the account context of a given account
function getAccountContext(address account) internal view returns (AccountContext memory) {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
return store[account];
}
/// @notice Sets the account context of a given account
function setAccountContext(AccountContext memory accountContext, address account) internal {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
store[account] = accountContext;
emit AccountContextUpdate(account);
}
function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) {
return accountContext.bitmapCurrencyId != 0;
}
/// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows
/// an account to hold more fCash than a normal portfolio, except only in a single currency.
/// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if
/// it has no assets or debt so that we ensure no assets are left stranded.
/// @param accountContext refers to the account where the bitmap will be enabled
/// @param currencyId the id of the currency to enable
/// @param blockTime the current block time to set the next settle time
function enableBitmapForAccount(
AccountContext memory accountContext,
uint16 currencyId,
uint256 blockTime
) internal view {
require(!isBitmapEnabled(accountContext), "Cannot change bitmap");
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id");
// Account cannot have assets or debts
require(accountContext.assetArrayLength == 0, "Cannot have assets");
require(accountContext.hasDebt == 0x00, "Cannot have debt");
// Ensure that the active currency is set to false in the array so that there is no double
// counting during FreeCollateral
setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES);
accountContext.bitmapCurrencyId = currencyId;
// Setting this is required to initialize the assets bitmap
uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime);
require(nextSettleTime < type(uint40).max); // dev: blockTime overflow
accountContext.nextSettleTime = uint40(nextSettleTime);
}
/// @notice Returns true if the context needs to settle
function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) {
uint256 blockTime = block.timestamp;
if (isBitmapEnabled(accountContext)) {
// nextSettleTime will be set to utc0 after settlement so we
// settle if this is strictly less than utc0
return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime);
} else {
// 0 value occurs on an uninitialized account
// Assets mature exactly on the blockTime (not one second past) so in this
// case we settle on the block timestamp
return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime;
}
}
/// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account
/// context active currencies list.
/// @dev NOTE: this may be more efficient as a binary search since we know that the array
/// is sorted
function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId)
internal
pure
returns (bool)
{
require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
bytes18 currencies = accountContext.activeCurrencies;
if (accountContext.bitmapCurrencyId == currencyId) return true;
while (currencies != 0x00) {
uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS);
if (cid == currencyId) {
// Currency found, return if it is active in balances or not
return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES;
}
currencies = currencies << 16;
}
return false;
}
/// @notice Iterates through the active currency list and removes, inserts or does nothing
/// to ensure that the active currency list is an ordered byte array of uint16 currency ids
/// that refer to the currencies that an account is active in.
///
/// This is called to ensure that currencies are active when the account has a non zero cash balance,
/// a non zero nToken balance or a portfolio asset.
function setActiveCurrency(
AccountContext memory accountContext,
uint256 currencyId,
bool isActive,
bytes2 flags
) internal pure {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
// If the bitmapped currency is already set then return here. Turning off the bitmap currency
// id requires other logical handling so we will do it elsewhere.
if (isActive && accountContext.bitmapCurrencyId == currencyId) return;
bytes18 prefix;
bytes18 suffix = accountContext.activeCurrencies;
uint256 shifts;
/// There are six possible outcomes from this search:
/// 1. The currency id is in the list
/// - it must be set to active, do nothing
/// - it must be set to inactive, shift suffix and concatenate
/// 2. The current id is greater than the one in the search:
/// - it must be set to active, append to prefix and then concatenate the suffix,
/// ensure that we do not lose the last 2 bytes if set.
/// - it must be set to inactive, it is not in the list, do nothing
/// 3. Reached the end of the list:
/// - it must be set to active, check that the last two bytes are not set and then
/// append to the prefix
/// - it must be set to inactive, do nothing
while (suffix != 0x00) {
uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS));
// if matches and isActive then return, already in list
if (cid == currencyId && isActive) {
// set flag and return
accountContext.activeCurrencies =
accountContext.activeCurrencies |
(bytes18(flags) >> (shifts * 16));
return;
}
// if matches and not active then shift suffix to remove
if (cid == currencyId && !isActive) {
// turn off flag, if both flags are off then remove
suffix = suffix & ~bytes18(flags);
if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16;
accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16));
return;
}
// if greater than and isActive then insert into prefix
if (cid > currencyId && isActive) {
prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
// check that the total length is not greater than 9, meaning that the last
// two bytes of the active currencies array should be zero
require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies
// append the suffix
accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16));
return;
}
// if past the point of the currency id and not active, not in list
if (cid > currencyId && !isActive) return;
prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16));
suffix = suffix << 16;
shifts += 1;
}
// If reached this point and not active then return
if (!isActive) return;
// if end and isActive then insert into suffix, check max length
require(shifts < 9); // dev: AC: too many currencies
accountContext.activeCurrencies =
prefix |
(bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
}
function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) {
bytes18 result;
// This is required to clear the suffix as we append below
bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS;
uint256 shifts;
// This loop will append all currencies that are active in balances into the result.
while (suffix != 0x00) {
if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
// If any flags are active, then append.
result = result | (bytes18(bytes2(suffix)) >> shifts);
shifts += 16;
}
suffix = suffix << 16;
}
return result;
}
/// @notice Stores a portfolio array and updates the account context information, this method should
/// be used whenever updating a portfolio array except in the case of nTokens
function storeAssetsAndUpdateContext(
AccountContext memory accountContext,
address account,
PortfolioState memory portfolioState,
bool isLiquidation
) internal {
// Each of these parameters is recalculated based on the entire array of assets in store assets,
// regardless of whether or not they have been updated.
(bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) =
portfolioState.storeAssets(account);
accountContext.nextSettleTime = nextSettleTime;
require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets
accountContext.assetArrayLength = assetArrayLength;
// During liquidation it is possible for an array to go over the max amount of assets allowed due to
// liquidity tokens being withdrawn into fCash.
if (!isLiquidation) {
require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed
}
// Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning
// a negative fCash balance.
if (hasDebt) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
} else {
// Turns off the ASSET_DEBT flag
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
}
// Clear the active portfolio active flags and they will be recalculated in the next step
accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies);
uint256 lastCurrency;
while (portfolioCurrencies != 0) {
// Portfolio currencies will not have flags, it is just an byte array of all the currencies found
// in a portfolio. They are appended in a sorted order so we can compare to the previous currency
// and only set it if they are different.
uint256 currencyId = uint16(bytes2(portfolioCurrencies));
if (currencyId != lastCurrency) {
setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO);
}
lastCurrency = currencyId;
portfolioCurrencies = portfolioCurrencies << 16;
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
interface NotionalCallback {
function notionalCallback(address sender, address account, bytes calldata callbackdata) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetRate.sol";
import "./CashGroup.sol";
import "./DateTime.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Market {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
// Max positive value for a ABDK64x64 integer
int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF;
/// @notice Add liquidity to a market, assuming that it is initialized. If not then
/// this method will revert and the market must be initialized first.
/// Return liquidityTokens and negative fCash to the portfolio
function addLiquidity(MarketParameters memory market, int256 assetCash)
internal
returns (int256 liquidityTokens, int256 fCash)
{
require(market.totalLiquidity > 0, "M: zero liquidity");
if (assetCash == 0) return (0, 0);
require(assetCash > 0); // dev: negative asset cash
liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash);
// No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion.
fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash);
market.totalLiquidity = market.totalLiquidity.add(liquidityTokens);
market.totalfCash = market.totalfCash.add(fCash);
market.totalAssetCash = market.totalAssetCash.add(assetCash);
_setMarketStorageForLiquidity(market);
// Flip the sign to represent the LP's net position
fCash = fCash.neg();
}
/// @notice Remove liquidity from a market, assuming that it is initialized.
/// Return assetCash and positive fCash to the portfolio
function removeLiquidity(MarketParameters memory market, int256 tokensToRemove)
internal
returns (int256 assetCash, int256 fCash)
{
if (tokensToRemove == 0) return (0, 0);
require(tokensToRemove > 0); // dev: negative tokens to remove
assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity);
fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity);
market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove);
market.totalfCash = market.totalfCash.subNoNeg(fCash);
market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash);
_setMarketStorageForLiquidity(market);
}
function executeTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal returns (int256 netAssetCash) {
int256 netAssetCashToReserve;
(netAssetCash, netAssetCashToReserve) = calculateTrade(
market,
cashGroup,
fCashToAccount,
timeToMaturity,
marketIndex
);
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve);
}
/// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive
/// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory.
/// @param market the current market state
/// @param cashGroup cash group configuration parameters
/// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change
/// to the market is in the opposite direction.
/// @param timeToMaturity number of seconds until maturity
/// @return netAssetCash, netAssetCashToReserve
function calculateTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal view returns (int256, int256) {
// We return false if there is not enough fCash to support this trade.
// if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail
// if fCashToAccount < 0 and totalfCash > 0 then this will always pass
if (market.totalfCash <= fCashToAccount) return (0, 0);
// Calculates initial rate factors for the trade
(int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) =
getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex);
// Calculates the exchange rate from cash to fCash before any liquidity fees
// are applied
int256 preFeeExchangeRate;
{
bool success;
(preFeeExchangeRate, success) = _getExchangeRate(
market.totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashToAccount
);
if (!success) return (0, 0);
}
// Given the exchange rate, returns the net cash amounts to apply to each of the
// three relevant balances.
(int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) =
_getNetCashAmountsUnderlying(
cashGroup,
preFeeExchangeRate,
fCashToAccount,
timeToMaturity
);
// Signifies a failed net cash amount calculation
if (netCashToAccount == 0) return (0, 0);
{
// Set the new implied interest rate after the trade has taken effect, this
// will be used to calculate the next trader's interest rate.
market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount);
market.lastImpliedRate = getImpliedRate(
market.totalfCash,
totalCashUnderlying.add(netCashToMarket),
rateScalar,
rateAnchor,
timeToMaturity
);
// It's technically possible that the implied rate is actually exactly zero (or
// more accurately the natural log rounds down to zero) but we will still fail
// in this case. If this does happen we may assume that markets are not initialized.
if (market.lastImpliedRate == 0) return (0, 0);
}
return
_setNewMarketState(
market,
cashGroup.assetRate,
netCashToAccount,
netCashToMarket,
netCashToReserve
);
}
/// @notice Returns factors for calculating exchange rates
/// @return
/// rateScalar: a scalar value in rate precision that defines the slope of the line
/// totalCashUnderlying: the converted asset cash to underlying cash for calculating
/// the exchange rates for the trade
/// rateAnchor: an offset from the x axis to maintain interest rate continuity over time
function getExchangeRateFactors(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
uint256 timeToMaturity,
uint256 marketIndex
)
internal
pure
returns (
int256,
int256,
int256
)
{
int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity);
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// This would result in a divide by zero
if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0);
// Get the rate anchor given the market state, this will establish the baseline for where
// the exchange rate is set.
int256 rateAnchor;
{
bool success;
(rateAnchor, success) = _getRateAnchor(
market.totalfCash,
market.lastImpliedRate,
totalCashUnderlying,
rateScalar,
timeToMaturity
);
if (!success) return (0, 0, 0);
}
return (rateScalar, totalCashUnderlying, rateAnchor);
}
/// @dev Returns net asset cash amounts to the account, the market and the reserve
/// @return
/// netCashToAccount: this is a positive or negative amount of cash change to the account
/// netCashToMarket: this is a positive or negative amount of cash change in the market
// netCashToReserve: this is always a positive amount of cash accrued to the reserve
function _getNetCashAmountsUnderlying(
CashGroupParameters memory cashGroup,
int256 preFeeExchangeRate,
int256 fCashToAccount,
uint256 timeToMaturity
)
private
pure
returns (
int256,
int256,
int256
)
{
// Fees are specified in basis points which is an rate precision denomination. We convert this to
// an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply
// or divide depending on the side of the trade).
// tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity)
// tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity)
// cash = fCash / exchangeRate, exchangeRate > 1
int256 preFeeCashToAccount =
fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg();
int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity);
if (fCashToAccount > 0) {
// Lending
// Dividing reduces exchange rate, lending should receive less fCash for cash
int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee);
// It's possible that the fee pushes exchange rates into negative territory. This is not possible
// when borrowing. If this happens then the trade has failed.
if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0);
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate
// preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate)
// postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate)
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1)
// netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1)
// netFee = preFeeCashToAccount * (1 - feeExchangeRate)
// RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0
fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee));
} else {
// Borrowing
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1)
// netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate)
// NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number
// preFee * (1 - fee) / fee will be negative, use neg() to flip to positive
// RATE_PRECISION - fee will be negative
fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg();
}
int256 cashToReserve =
fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS);
return (
// postFeeCashToAccount = preFeeCashToAccount - fee
preFeeCashToAccount.sub(fee),
// netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve)
(preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(),
cashToReserve
);
}
/// @notice Sets the new market state
/// @return
/// netAssetCashToAccount: the positive or negative change in asset cash to the account
/// assetCashToReserve: the positive amount of cash that accrues to the reserve
function _setNewMarketState(
MarketParameters memory market,
AssetRateParameters memory assetRate,
int256 netCashToAccount,
int256 netCashToMarket,
int256 netCashToReserve
) private view returns (int256, int256) {
int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket);
// Set storage checks that total asset cash is above zero
market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket);
// Sets the trade time for the next oracle update
market.previousTradeTime = block.timestamp;
int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve);
int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount);
return (netAssetCashToAccount, assetCashToReserve);
}
/// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable
/// across time or markets but implied rates are. The goal here is to ensure that the implied rate
/// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied
/// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage
/// which will hurt the liquidity providers.
///
/// The rate anchor will update as the market rolls down to maturity. The calculation is:
/// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME)
/// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar
///
/// where:
/// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity')
/// (calculated when the last trade in the market was made)
/// @return the new rate anchor and a boolean that signifies success
function _getRateAnchor(
int256 totalfCash,
uint256 lastImpliedRate,
int256 totalCashUnderlying,
int256 rateScalar,
uint256 timeToMaturity
) internal pure returns (int256, bool) {
// This is the exchange rate at the new time to maturity
int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity);
if (newExchangeRate < Constants.RATE_PRECISION) return (0, false);
int256 rateAnchor;
{
// totalfCash / (totalfCash + totalCashUnderlying)
int256 proportion =
totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying));
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar
rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar));
}
return (rateAnchor, true);
}
/// @notice Calculates the current market implied rate.
/// @return the implied rate and a bool that is true on success
function getImpliedRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
uint256 timeToMaturity
) internal pure returns (uint256) {
// This will check for exchange rates < Constants.RATE_PRECISION
(int256 exchangeRate, bool success) =
_getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0);
if (!success) return 0;
// Uses continuous compounding to calculate the implied rate:
// ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity
int128 rate = ABDKMath64x64.fromInt(exchangeRate);
// Scales down to a floating point for LN
int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64);
// We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION
// inside getExchangeRate
int128 lnRateScaled = ABDKMath64x64.ln(rateScaled);
// Scales up to a fixed point
uint256 lnRate =
ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64));
// lnRate * IMPLIED_RATE_TIME / ttm
uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity);
// Implied rates over 429% will overflow, this seems like a safe assumption
if (impliedRate > type(uint32).max) return 0;
return impliedRate;
}
/// @notice Converts an implied rate to an exchange rate given a time to maturity. The
/// formula is E = e^rt
function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(
impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)
);
int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
int128 expResult = ABDKMath64x64.exp(expValueScaled);
int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64);
return ABDKMath64x64.toInt(expResultScaled);
}
/// @notice Returns the exchange rate between fCash and cash for the given market
/// Calculates the following exchange rate:
/// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor
/// where:
/// proportion = totalfCash / (totalfCash + totalUnderlyingCash)
/// @dev has an underscore to denote as private but is marked internal for the mock
function _getExchangeRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 fCashToAccount
) internal pure returns (int256, bool) {
int256 numerator = totalfCash.subNoNeg(fCashToAccount);
// This is the proportion scaled by Constants.RATE_PRECISION
// (totalfCash + fCash) / (totalfCash + totalCashUnderlying)
int256 proportion =
numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying));
// This limit is here to prevent the market from reaching extremely high interest rates via an
// excessively large proportion (high amounts of fCash relative to cash).
// Market proportion can only increase via borrowing (fCash is added to the market and cash is
// removed). Over time, the returns from asset cash will slightly decrease the proportion (the
// value of cash underlying in the market must be monotonically increasing). Therefore it is not
// possible for the proportion to go over max market proportion unless borrowing occurs.
if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false);
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// lnProportion / rateScalar + rateAnchor
int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor);
// Do not succeed if interest rates fall below 1
if (rate < Constants.RATE_PRECISION) {
return (0, false);
} else {
return (rate, true);
}
}
/// @dev This method calculates the log of the proportion inside the logit function which is
/// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with
/// fixed point precision and the ABDK library.
function _logProportion(int256 proportion) internal pure returns (int256, bool) {
// This will result in divide by zero, short circuit
if (proportion == Constants.RATE_PRECISION) return (0, false);
// Convert proportion to what is used inside the logit function (p / (1-p))
int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion));
// ABDK does not handle log of numbers that are less than 1, in order to get the right value
// scaled by RATE_PRECISION we use the log identity:
// (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION
int128 abdkProportion = ABDKMath64x64.fromInt(logitP);
// Here, abdk will revert due to negative log so abort
if (abdkProportion <= 0) return (0, false);
int256 result =
ABDKMath64x64.toInt(
ABDKMath64x64.mul(
ABDKMath64x64.sub(
ABDKMath64x64.ln(abdkProportion),
Constants.LOG_RATE_PRECISION_64x64
),
Constants.RATE_PRECISION_64x64
)
);
return (result, true);
}
/// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value
/// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example,
/// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates.
/// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then
/// be liquidated.
///
/// Oracle rates are calculated when the market is loaded from storage.
///
/// The oracle rate is a lagged weighted average over a short term price window. If we are past
/// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the
/// weighted average:
/// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow +
/// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow)
function _updateRateOracle(
uint256 previousTradeTime,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 rateOracleTimeWindow,
uint256 blockTime
) private pure returns (uint256) {
require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero
// This can occur when using a view function get to a market state in the past
if (previousTradeTime > blockTime) return lastImpliedRate;
uint256 timeDiff = blockTime.sub(previousTradeTime);
if (timeDiff > rateOracleTimeWindow) {
// If past the time window just return the lastImpliedRate
return lastImpliedRate;
}
// (currentTs - previousTs) / timeWindow
uint256 lastTradeWeight =
timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow);
// 1 - (currentTs - previousTs) / timeWindow
uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight);
uint256 newOracleRate =
(lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div(
uint256(Constants.RATE_PRECISION)
);
return newOracleRate;
}
function getOracleRate(
uint256 currencyId,
uint256 maturity,
uint256 rateOracleTimeWindow,
uint256 blockTime
) internal view returns (uint256) {
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
uint256 lastImpliedRate = marketStorage.lastImpliedRate;
uint256 oracleRate = marketStorage.oracleRate;
uint256 previousTradeTime = marketStorage.previousTradeTime;
// If the oracle rate is set to zero this can only be because the markets have past their settlement
// date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated
// during this time, but market initialization can be called by anyone so the actual time that this condition
// exists for should be quite short.
require(oracleRate > 0, "Market not initialized");
return
_updateRateOracle(
previousTradeTime,
lastImpliedRate,
oracleRate,
rateOracleTimeWindow,
blockTime
);
}
/// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method
/// which ensures that the rate oracle is set properly.
function _loadMarketStorage(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
bool needsLiquidity,
uint256 settlementDate
) private view {
// Market object always uses the most current reference time as the settlement date
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
bytes32 slot;
assembly {
slot := marketStorage.slot
}
market.storageSlot = slot;
market.maturity = maturity;
market.totalfCash = marketStorage.totalfCash;
market.totalAssetCash = marketStorage.totalAssetCash;
market.lastImpliedRate = marketStorage.lastImpliedRate;
market.oracleRate = marketStorage.oracleRate;
market.previousTradeTime = marketStorage.previousTradeTime;
if (needsLiquidity) {
market.totalLiquidity = marketStorage.totalLiquidity;
} else {
market.totalLiquidity = 0;
}
}
function _getMarketStoragePointer(
MarketParameters memory market
) private pure returns (MarketStorage storage marketStorage) {
bytes32 slot = market.storageSlot;
assembly {
marketStorage.slot := slot
}
}
function _setMarketStorageForLiquidity(MarketParameters memory market) internal {
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
// Oracle rate does not change on liquidity
uint32 storedOracleRate = marketStorage.oracleRate;
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
storedOracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function setMarketStorageForInitialize(
MarketParameters memory market,
uint256 currencyId,
uint256 settlementDate
) internal {
// On initialization we have not yet calculated the storage slot so we get it here.
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate];
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function _setTotalLiquidity(
MarketStorage storage marketStorage,
int256 totalLiquidity
) internal {
require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow
marketStorage.totalLiquidity = uint80(totalLiquidity);
}
function _setMarketStorage(
MarketStorage storage marketStorage,
int256 totalfCash,
int256 totalAssetCash,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 previousTradeTime
) private {
require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow
require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow
require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow
require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow
require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow
marketStorage.totalfCash = uint80(totalfCash);
marketStorage.totalAssetCash = uint80(totalAssetCash);
marketStorage.lastImpliedRate = uint32(lastImpliedRate);
marketStorage.oracleRate = uint32(oracleRate);
marketStorage.previousTradeTime = uint32(previousTradeTime);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately.
function loadMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow
) internal view {
// Always reference the current settlement date
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
loadMarketWithSettlementDate(
market,
currencyId,
maturity,
blockTime,
needsLiquidity,
rateOracleTimeWindow,
settlementDate
);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this
/// is mainly used in the InitializeMarketAction contract.
function loadMarketWithSettlementDate(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate);
market.oracleRate = _updateRateOracle(
market.previousTradeTime,
market.lastImpliedRate,
market.oracleRate,
rateOracleTimeWindow,
blockTime
);
}
function loadSettlementMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, true, settlementDate);
}
/// Uses Newton's method to converge on an fCash amount given the amount of
/// cash. The relation between cash and fcash is:
/// cashAmount * exchangeRate * fee + fCash = 0
/// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor
/// p = (totalfCash - fCash) / (totalfCash + totalCash)
/// if cashAmount < 0: fee = feeRate ^ -1
/// if cashAmount > 0: fee = feeRate
///
/// Newton's method is:
/// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash)
///
/// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash
///
/// (totalfCash + totalCash)
/// exchangeRate'(fCash) = - ------------------------------------------
/// (totalfCash - fCash) * (totalCash + fCash)
///
/// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29
///
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
///
/// NOTE: each iteration costs about 11.3k so this is only done via a view function.
function getfCashGivenCashAmount(
int256 totalfCash,
int256 netCashToAccount,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 feeRate,
int256 maxDelta
) internal pure returns (int256) {
require(maxDelta >= 0);
int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg();
for (uint8 i = 0; i < 250; i++) {
(int256 exchangeRate, bool success) =
_getExchangeRate(
totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashChangeToAccountGuess
);
require(success); // dev: invalid exchange rate
int256 delta =
_calculateDelta(
netCashToAccount,
totalfCash,
totalCashUnderlying,
rateScalar,
fCashChangeToAccountGuess,
exchangeRate,
feeRate
);
if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess;
fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta);
}
revert("No convergence");
}
/// @dev Calculates: f(fCash) / f'(fCash)
/// f(fCash) = cashAmount * exchangeRate * fee + fCash
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
function _calculateDelta(
int256 cashAmount,
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 fCashGuess,
int256 exchangeRate,
int256 feeRate
) private pure returns (int256) {
int256 derivative;
// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
// Precision: TOKEN_PRECISION ^ 2
int256 denominator =
rateScalar.mulInRatePrecision(
(totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess))
);
if (fCashGuess > 0) {
// Lending
exchangeRate = exchangeRate.divInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount / fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount
.mul(totalfCash.add(totalCashUnderlying))
.divInRatePrecision(feeRate);
} else {
// Borrowing
exchangeRate = exchangeRate.mulInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount * fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount.mulInRatePrecision(
feeRate.mul(totalfCash.add(totalCashUnderlying))
);
}
// 1 - numerator / denominator
// Precision: TOKEN_PRECISION
derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator));
// f(fCash) = cashAmount * exchangeRate * fee + fCash
// NOTE: exchangeRate at this point already has the fee taken into account
int256 numerator = cashAmount.mulInRatePrecision(exchangeRate);
numerator = numerator.add(fCashGuess);
// f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION
// here instead of RATE_PRECISION
return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Market.sol";
import "./AssetRate.sol";
import "./DateTime.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library CashGroup {
using SafeMath for uint256;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
// Bit number references for each parameter in the 32 byte word (0-indexed)
uint256 private constant MARKET_INDEX_BIT = 31;
uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30;
uint256 private constant TOTAL_FEE_BIT = 29;
uint256 private constant RESERVE_FEE_SHARE_BIT = 28;
uint256 private constant DEBT_BUFFER_BIT = 27;
uint256 private constant FCASH_HAIRCUT_BIT = 26;
uint256 private constant SETTLEMENT_PENALTY_BIT = 25;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24;
uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23;
// 7 bytes allocated, one byte per market for the liquidity token haircut
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22;
// 7 bytes allocated, one byte per market for the rate scalar
uint256 private constant RATE_SCALAR_FIRST_BIT = 15;
// Offsets for the bytes of the different parameters
uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8;
uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8;
uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8;
uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8;
uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8;
uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8;
uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8;
uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8;
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8;
uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8;
/// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies
/// the ln() portion of the liquidity curve as an inverse so it increases with time to
/// maturity. The effect of the rate scalar on slippage must decrease with time to maturity.
function getRateScalar(
CashGroupParameters memory cashGroup,
uint256 marketIndex,
uint256 timeToMaturity
) internal pure returns (int256) {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index
uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1);
int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION;
int256 rateScalar =
scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity));
// Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the
// division above.
require(rateScalar > 0); // dev: rate scalar underflow
return rateScalar;
}
/// @notice Haircut on liquidity tokens to account for the risk associated with changes in the
/// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100.
function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType)
internal
pure
returns (uint8)
{
require(
Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX
); // dev: liquidity haircut invalid asset type
uint256 offset =
LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX);
return uint8(uint256(cashGroup.data >> offset));
}
/// @notice Total trading fee denominated in RATE_PRECISION with basis point increments
function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT;
}
/// @notice Percentage of the total trading fee that goes to the reserve
function getReserveFeeShare(CashGroupParameters memory cashGroup)
internal
pure
returns (int256)
{
return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE));
}
/// @notice fCash haircut for valuation denominated in rate precision with five basis point increments
function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return
uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments
function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Time window factor for the rate oracle denominated in seconds with five minute increments.
function getRateOracleTimeWindow(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
// This is denominated in 5 minute increments in storage
return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES;
}
/// @notice Penalty rate for settling cash debts denominated in basis points
function getSettlementPenalty(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for positive fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for negative fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
function loadMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 marketIndex,
bool needsLiquidity,
uint256 blockTime
) internal view {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market");
uint256 maturity =
DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex));
market.loadMarket(
cashGroup.currencyId,
maturity,
blockTime,
needsLiquidity,
getRateOracleTimeWindow(cashGroup)
);
}
/// @notice Returns the linear interpolation between two market rates. The formula is
/// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity)
/// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate
function interpolateOracleRate(
uint256 shortMaturity,
uint256 longMaturity,
uint256 shortRate,
uint256 longRate,
uint256 assetMaturity
) internal pure returns (uint256) {
require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity
require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity
// It's possible that the rates are inverted where the short market rate > long market rate and
// we will get an underflow here so we check for that
if (longRate >= shortRate) {
return
(longRate - shortRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
.add(shortRate);
} else {
// In this case the slope is negative so:
// interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity)
// NOTE: this subtraction should never overflow, the linear interpolation between two points above zero
// cannot go below zero
return
shortRate.sub(
// This is reversed to keep it it positive
(shortRate - longRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
);
}
}
/// @dev Gets an oracle rate given any valid maturity.
function calculateOracleRate(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime
) internal view returns (uint256) {
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime);
uint256 timeWindow = getRateOracleTimeWindow(cashGroup);
if (!idiosyncratic) {
return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime);
} else {
uint256 referenceTime = DateTime.getReferenceTime(blockTime);
// DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic
uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex));
uint256 longRate =
Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime);
uint256 shortMaturity;
uint256 shortRate;
if (marketIndex == 1) {
// In this case the short market is the annualized asset supply rate
shortMaturity = blockTime;
shortRate = cashGroup.assetRate.getSupplyRate();
} else {
// Minimum value for marketIndex here is 2
shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1));
shortRate = Market.getOracleRate(
cashGroup.currencyId,
shortMaturity,
timeWindow,
blockTime
);
}
return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity);
}
}
function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) {
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
return store[currencyId];
}
/// @dev Helper method for validating maturities in ERC1155Action
function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) {
bytes32 data = _getCashGroupStorageBytes(currencyId);
return uint8(data[MARKET_INDEX_BIT]);
}
/// @notice Checks all cash group settings for invalid values and sets them into storage
function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup)
internal
{
// Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market.
// The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month
// fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash
// groups with 0 market index, it has no effect.
require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX,
"CG: invalid market index"
);
require(
cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid reserve share"
);
require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex);
require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex);
// This is required so that fCash liquidation can proceed correctly
require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS);
require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS);
// Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve
uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId);
require(
previousMaxMarketIndex <= cashGroup.maxMarketIndex,
"CG: market index cannot decrease"
);
// Per cash group settings
bytes32 data =
(bytes32(uint256(cashGroup.maxMarketIndex)) |
(bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) |
(bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) |
(bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) |
(bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) |
(bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) |
(bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) <<
LIQUIDATION_FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER));
// Per market group settings
for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) {
require(
cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid token haircut"
);
data =
data |
(bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) <<
(LIQUIDITY_TOKEN_HAIRCUT + i * 8));
}
for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) {
// Causes a divide by zero error
require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar");
data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8));
}
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
store[currencyId] = data;
}
/// @notice Deserialize the cash group storage bytes into a user friendly object
function deserializeCashGroupStorage(uint256 currencyId)
internal
view
returns (CashGroupSettings memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex));
uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex));
for (uint8 i = 0; i < maxMarketIndex; i++) {
tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]);
rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]);
}
return
CashGroupSettings({
maxMarketIndex: maxMarketIndex,
rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]),
totalFeeBPS: uint8(data[TOTAL_FEE_BIT]),
reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]),
debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]),
fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]),
settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]),
liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]),
liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]),
liquidityTokenHaircuts: tokenHaircuts,
rateScalars: rateScalars
});
}
function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate)
private
view
returns (CashGroupParameters memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
return
CashGroupParameters({
currencyId: currencyId,
maxMarketIndex: maxMarketIndex,
assetRate: assetRate,
data: data
});
}
/// @notice Builds a cash group using a view version of the asset rate
function buildCashGroupView(uint16 currencyId)
internal
view
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
/// @notice Builds a cash group using a stateful version of the asset rate
function buildCashGroupStateful(uint16 currencyId)
internal
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/notional/AssetRateAdapter.sol";
library AssetRate {
using SafeInt256 for int256;
event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate);
// Asset rates are in 1e18 decimals (cToken exchange rates), internal balances
// are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10
int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10;
/// @notice Converts an internal asset cash value to its underlying token value.
/// @param ar exchange rate object between asset and underlying
/// @param assetBalance amount to convert to underlying
function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rate * balance * internalPrecision / rateDecimals * underlyingPrecision
int256 underlyingBalance = ar.rate
.mul(assetBalance)
.div(ASSET_RATE_DECIMAL_DIFFERENCE)
.div(ar.underlyingDecimals);
return underlyingBalance;
}
/// @notice Converts an internal underlying cash value to its asset cash value
/// @param ar exchange rate object between asset and underlying
/// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision
function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rateDecimals * balance * underlyingPrecision / rate * internalPrecision
int256 assetBalance = underlyingBalance
.mul(ASSET_RATE_DECIMAL_DIFFERENCE)
.mul(ar.underlyingDecimals)
.div(ar.rate);
return assetBalance;
}
/// @notice Returns the current per block supply rate, is used when calculating oracle rates
/// for idiosyncratic fCash with a shorter duration than the 3 month maturity.
function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) {
// If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero.
if (address(ar.rateOracle) == address(0)) return 0;
uint256 rate = ar.rateOracle.getAnnualizedSupplyRate();
// Zero supply rate is valid since this is an interest rate, we do not divide by
// the supply rate so we do not get div by zero errors.
require(rate >= 0); // dev: invalid supply rate
return rate;
}
function _getAssetRateStorage(uint256 currencyId)
private
view
returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces)
{
mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage();
AssetRateStorage storage ar = store[currencyId];
rateOracle = AssetRateAdapter(ar.rateOracle);
underlyingDecimalPlaces = ar.underlyingDecimalPlaces;
}
/// @notice Gets an asset rate using a view function, does not accrue interest so the
/// exchange rate will not be up to date. Should only be used for non-stateful methods
function _getAssetRateView(uint256 currencyId)
private
view
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateView();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Gets an asset rate using a stateful function, accrues interest so the
/// exchange rate will be up to date for the current block.
function _getAssetRateStateful(uint256 currencyId)
private
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateStateful();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Returns an asset rate object using the view method
function buildAssetRateView(uint256 currencyId)
internal
view
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateView(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @notice Returns an asset rate object using the stateful method
function buildAssetRateStateful(uint256 currencyId)
internal
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateStateful(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @dev Gets a settlement rate object
function _getSettlementRateStorage(uint256 currencyId, uint256 maturity)
private
view
returns (
int256 settlementRate,
uint8 underlyingDecimalPlaces
)
{
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
settlementRate = rateStorage.settlementRate;
underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces;
}
/// @notice Returns a settlement rate object using the view method
function buildSettlementRateView(uint256 currencyId, uint256 maturity)
internal
view
returns (AssetRateParameters memory)
{
// prettier-ignore
(
int256 settlementRate,
uint8 underlyingDecimalPlaces
) = _getSettlementRateStorage(currencyId, maturity);
// Asset exchange rates cannot be zero
if (settlementRate == 0) {
// If settlement rate has not been set then we need to fetch it
// prettier-ignore
(
settlementRate,
/* address */,
underlyingDecimalPlaces
) = _getAssetRateView(currencyId);
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
/// @notice Returns a settlement rate object and sets the rate if it has not been set yet
function buildSettlementRateStateful(
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) internal returns (AssetRateParameters memory) {
(int256 settlementRate, uint8 underlyingDecimalPlaces) =
_getSettlementRateStorage(currencyId, maturity);
if (settlementRate == 0) {
// Settlement rate has not yet been set, set it in this branch
AssetRateAdapter rateOracle;
// If rate oracle == 0 then this will return the identity settlement rate
// prettier-ignore
(
settlementRate,
rateOracle,
underlyingDecimalPlaces
) = _getAssetRateStateful(currencyId);
if (address(rateOracle) != address(0)) {
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
// Only need to set settlement rates when the rate oracle is set (meaning the asset token has
// a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1
// rate since they are the same.
require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow
require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
rateStorage.blockTime = uint40(blockTime);
rateStorage.settlementRate = uint128(settlementRate);
rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces;
emit SetSettlementRate(currencyId, maturity, uint128(settlementRate));
}
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./PortfolioHandler.sol";
import "./BitmapAssetsHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../math/SafeInt256.sol";
/// @notice Helper library for transferring assets from one portfolio to another
library TransferAssets {
using AccountContextHandler for AccountContext;
using PortfolioHandler for PortfolioState;
using SafeInt256 for int256;
/// @notice Decodes asset ids
function decodeAssetId(uint256 id)
internal
pure
returns (
uint256 currencyId,
uint256 maturity,
uint256 assetType
)
{
assetType = uint8(id);
maturity = uint40(id >> 8);
currencyId = uint16(id >> 48);
}
/// @notice Encodes asset ids
function encodeAssetId(
uint256 currencyId,
uint256 maturity,
uint256 assetType
) internal pure returns (uint256) {
require(currencyId <= Constants.MAX_CURRENCIES);
require(maturity <= type(uint40).max);
require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX);
return
uint256(
(bytes32(uint256(uint16(currencyId))) << 48) |
(bytes32(uint256(uint40(maturity))) << 8) |
bytes32(uint256(uint8(assetType)))
);
}
/// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets
function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure {
for (uint256 i; i < assets.length; i++) {
assets[i].notional = assets[i].notional.neg();
}
}
/// @dev Useful method for hiding the logic of updating an account. WARNING: the account
/// context returned from this method may not be the same memory location as the account
/// context provided if the account is settled.
function placeAssetsInAccount(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal returns (AccountContext memory) {
// If an account has assets that require settlement then placing assets inside it
// may cause issues.
require(!accountContext.mustSettleAssets(), "Account must settle");
if (accountContext.isBitmapEnabled()) {
// Adds fCash assets into the account and finalized storage
BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets);
} else {
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
assets.length
);
// This will add assets in memory
portfolioState.addMultipleAssets(assets);
// This will store assets and update the account context in memory
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
return accountContext;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetHandler.sol";
import "./ExchangeRate.sol";
import "../markets/CashGroup.sol";
import "../AccountContextHandler.sol";
import "../balances/BalanceHandler.sol";
import "../portfolio/PortfolioHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenCalculations.sol";
import "../../math/SafeInt256.sol";
library FreeCollateral {
using SafeInt256 for int256;
using Bitmap for bytes;
using ExchangeRate for ETHRate;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
using nTokenHandler for nTokenPortfolio;
/// @dev This is only used within the library to clean up the stack
struct FreeCollateralFactors {
int256 netETHValue;
bool updateContext;
uint256 portfolioIndex;
CashGroupParameters cashGroup;
MarketParameters market;
PortfolioAsset[] portfolio;
AssetRateParameters assetRate;
nTokenPortfolio nToken;
}
/// @notice Checks if an asset is active in the portfolio
function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) {
return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO;
}
/// @notice Checks if currency balances are active in the account returns them if true
/// @return cash balance, nTokenBalance
function _getCurrencyBalances(address account, bytes2 currencyBytes)
private
view
returns (int256, int256)
{
if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// prettier-ignore
(
int256 cashBalance,
int256 nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, currencyId);
return (cashBalance, nTokenBalance);
}
return (0, 0);
}
/// @notice Calculates the nToken asset value with a haircut set by governance
/// @return the value of the account's nTokens after haircut, the nToken parameters
function _getNTokenHaircutAssetPV(
CashGroupParameters memory cashGroup,
nTokenPortfolio memory nToken,
int256 tokenBalance,
uint256 blockTime
) internal view returns (int256, bytes6) {
nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId);
nToken.cashGroup = cashGroup;
int256 nTokenAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// (tokenBalance * nTokenValue * haircut) / totalSupply
int256 nTokenHaircutAssetPV =
tokenBalance
.mul(nTokenAssetPV)
.mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE]))
.div(Constants.PERCENTAGE_DECIMALS)
.div(nToken.totalSupply);
// nToken.parameters is returned for use in liquidation
return (nTokenHaircutAssetPV, nToken.parameters);
}
/// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and
/// markets. The reason these are grouped together is because they both require storage reads of the same
/// values.
function _getPortfolioAndNTokenAssetValue(
FreeCollateralFactors memory factors,
int256 nTokenBalance,
uint256 blockTime
)
private
view
returns (
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
// If the next asset matches the currency id then we need to calculate the cash group value
if (
factors.portfolioIndex < factors.portfolio.length &&
factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId
) {
// netPortfolioValue is in asset cash
(netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue(
factors.portfolio,
factors.cashGroup,
factors.market,
blockTime,
factors.portfolioIndex
);
} else {
netPortfolioValue = 0;
}
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
nTokenParameters = 0;
}
}
/// @notice Returns balance values for the bitmapped currency
function _getBitmapBalanceValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
)
private
view
returns (
int256 cashBalance,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
int256 nTokenBalance;
// prettier-ignore
(
cashBalance,
nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId);
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
}
}
/// @notice Returns portfolio value for the bitmapped currency
function _getBitmapPortfolioValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
) private view returns (int256) {
(int256 netPortfolioValueUnderlying, bool bitmapHasDebt) =
BitmapAssetsHandler.getifCashNetPresentValue(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
blockTime,
factors.cashGroup,
true // risk adjusted
);
// Turns off has debt flag if it has changed
bool contextHasAssetDebt =
accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT;
if (bitmapHasDebt && !contextHasAssetDebt) {
// Turn on has debt
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
} else if (!bitmapHasDebt && contextHasAssetDebt) {
// Turn off has debt
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
}
// Return asset cash value
return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying);
}
function _updateNetETHValue(
uint256 currencyId,
int256 netLocalAssetValue,
FreeCollateralFactors memory factors
) private view returns (ETHRate memory) {
ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId);
// Converts to underlying first, ETH exchange rates are in underlying
factors.netETHValue = factors.netETHValue.add(
ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue))
);
return ethRate;
}
/// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account
/// context needs to be updated.
function getFreeCollateralStateful(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal returns (int256, bool) {
FreeCollateralFactors memory factors;
bool hasCashDebt;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
if (netCashBalance < 0) hasCashDebt = true;
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(account, currencyBytes);
if (netLocalAssetValue < 0) hasCashDebt = true;
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
// prettier-ignore
(
int256 netPortfolioAssetValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioAssetValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
// NOTE: we must set the proper assetRate when we updateNetETHValue
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValue, factors);
currencies = currencies << 16;
}
// Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e.
// they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of
// sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing
// an account to do an extra free collateral check to turn off this setting.
if (
accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT &&
!hasCashDebt
) {
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT;
factors.updateContext = true;
}
return (factors.netETHValue, factors.updateContext);
}
/// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips
/// all the update context logic.
function getFreeCollateralView(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal view returns (int256, int256[] memory) {
FreeCollateralFactors memory factors;
uint256 netLocalIndex;
int256[] memory netLocalAssetValues = new int256[](10);
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
netLocalAssetValues[netLocalIndex] = netCashBalance
.add(nTokenHaircutAssetValue)
.add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(
accountContext.bitmapCurrencyId,
netLocalAssetValues[netLocalIndex],
factors
);
netLocalIndex++;
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
int256 nTokenBalance;
(netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances(
account,
currencyBytes
);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupView(currencyId);
// prettier-ignore
(
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex]
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
factors.assetRate = AssetRate.buildAssetRateView(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors);
netLocalIndex++;
currencies = currencies << 16;
}
return (factors.netETHValue, netLocalAssetValues);
}
/// @notice Calculates the net value of a currency within a portfolio, this is a bit
/// convoluted to fit into the stack frame
function _calculateLiquidationAssetValue(
FreeCollateralFactors memory factors,
LiquidationFactors memory liquidationFactors,
bytes2 currencyBytes,
bool setLiquidationFactors,
uint256 blockTime
) private returns (int256) {
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(liquidationFactors.account, currencyBytes);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
(int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
// If collateralCurrencyId is set to zero then this is a local currency liquidation
if (setLiquidationFactors) {
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenParameters = nTokenParameters;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
}
} else {
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
return netLocalAssetValue;
}
/// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information.
function getLiquidationFactors(
address account,
AccountContext memory accountContext,
uint256 blockTime,
uint256 localCurrencyId,
uint256 collateralCurrencyId
) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) {
FreeCollateralFactors memory factors;
LiquidationFactors memory liquidationFactors;
// This is only set to reduce the stack size
liquidationFactors.account = account;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
(int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioBalance =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance);
factors.assetRate = factors.cashGroup.assetRate;
ETHRate memory ethRate =
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
// If the bitmap currency id can only ever be the local currency where debt is held.
// During enable bitmap we check that the account has no assets in their portfolio and
// no cash debts.
if (accountContext.bitmapCurrencyId == localCurrencyId) {
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// This will be the case during local currency or local fCash liquidation
if (collateralCurrencyId == 0) {
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers.
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
liquidationFactors.nTokenParameters = nTokenParameters;
}
}
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
// This next bit of code here is annoyingly structured to get around stack size issues
bool setLiquidationFactors;
{
uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
// Explicitly ensures that bitmap currency cannot be double counted
require(tempId != accountContext.bitmapCurrencyId);
setLiquidationFactors =
(tempId == localCurrencyId && collateralCurrencyId == 0) ||
tempId == collateralCurrencyId;
}
int256 netLocalAssetValue =
_calculateLiquidationAssetValue(
factors,
liquidationFactors,
currencyBytes,
setLiquidationFactors,
blockTime
);
uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors);
if (currencyId == collateralCurrencyId) {
// Ensure that this is set even if the cash group is not loaded, it will not be
// loaded if the account only has a cash balance and no nTokens or assets
liquidationFactors.collateralCashGroup.assetRate = factors.assetRate;
liquidationFactors.collateralAssetAvailable = netLocalAssetValue;
liquidationFactors.collateralETHRate = ethRate;
} else if (currencyId == localCurrencyId) {
// This branch will not be entered if bitmap is enabled
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers and it will have been set in
// _calculateLiquidationAssetValue above because the account must have fCash assets,
// there is no need to set cash group in this branch.
}
currencies = currencies << 16;
}
liquidationFactors.netETHValue = factors.netETHValue;
require(liquidationFactors.netETHValue < 0, "Sufficient collateral");
// Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash
// netting which will make further calculations incorrect.
if (accountContext.assetArrayLength > 0) {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
return (liquidationFactors, factors.portfolio);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../valuation/AssetHandler.sol";
import "../markets/Market.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
library SettlePortfolioAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
using PortfolioHandler for PortfolioState;
using AssetHandler for PortfolioAsset;
/// @dev Returns a SettleAmount array for the assets that will be settled
function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime)
private
pure
returns (SettleAmount[] memory)
{
uint256 currenciesSettled;
uint256 lastCurrencyId = 0;
if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0);
// Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio
// NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause
// a revert, must wrap in an unchecked.
for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// Assets settle on exactly blockTime
if (asset.getSettlementDate() > blockTime) continue;
// Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this
// will work for the first asset
if (lastCurrencyId != asset.currencyId) {
lastCurrencyId = asset.currencyId;
currenciesSettled++;
}
}
// Actual currency ids will be set as we loop through the portfolio and settle assets
SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled);
if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId;
return settleAmounts;
}
/// @notice Settles a portfolio array
function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime)
internal
returns (SettleAmount[] memory)
{
AssetRateParameters memory settlementRate;
SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime);
MarketParameters memory market;
if (settleAmounts.length == 0) return settleAmounts;
uint256 settleAmountIndex;
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
uint256 settleDate = asset.getSettlementDate();
// Settlement date is on block time exactly
if (settleDate > blockTime) continue;
// On the first loop the lastCurrencyId is already set.
if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) {
// New currency in the portfolio
settleAmountIndex += 1;
settleAmounts[settleAmountIndex].currencyId = asset.currencyId;
}
int256 assetCash;
if (asset.assetType == Constants.FCASH_ASSET_TYPE) {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
assetCash = settlementRate.convertFromUnderlying(asset.notional);
portfolioState.deleteAsset(i);
} else if (AssetHandler.isLiquidityToken(asset.assetType)) {
Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate);
int256 fCash;
(assetCash, fCash) = market.removeLiquidity(asset.notional);
// Assets mature exactly on block time
if (asset.maturity > blockTime) {
// If fCash has not yet matured then add it to the portfolio
_settleLiquidityTokenTofCash(portfolioState, i, fCash);
} else {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
// If asset has matured then settle fCash to asset cash
assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash));
portfolioState.deleteAsset(i);
}
}
settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex]
.netCashChange
.add(assetCash);
}
return settleAmounts;
}
/// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future
function _settleLiquidityTokenTofCash(
PortfolioState memory portfolioState,
uint256 index,
int256 fCash
) private pure {
PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index];
// If the liquidity token's maturity is still in the future then we change the entry to be
// an idiosyncratic fCash entry with the net fCash amount.
if (index != 0) {
// Check to see if the previous index is the matching fCash asset, this will be the case when the
// portfolio is sorted
PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1];
if (
fCashAsset.currencyId == liquidityToken.currencyId &&
fCashAsset.maturity == liquidityToken.maturity &&
fCashAsset.assetType == Constants.FCASH_ASSET_TYPE
) {
// This fCash asset has not matured if we are settling to fCash
fCashAsset.notional = fCashAsset.notional.add(fCash);
fCashAsset.storageState = AssetStorageState.Update;
portfolioState.deleteAsset(index);
}
}
// We are going to delete this asset anyway, convert to an fCash position
liquidityToken.assetType = Constants.FCASH_ASSET_TYPE;
liquidityToken.notional = fCash;
liquidityToken.storageState = AssetStorageState.Update;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../markets/AssetRate.sol";
import "../../global/LibStorage.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
/**
* Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash
* at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues
* to correctly reference all actual maturities. fCash asset notional values are stored in *absolute*
* time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime.
* Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on
* newSettleTime and the absolute times (maturities) that the previous bitmap references.
*/
library SettleBitmapAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Bitmap for bytes32;
/// @notice Given a bitmap for a cash group and timestamps, will settle all assets
/// that have matured and remap the bitmap to correspond to the current time.
function settleBitmappedCashGroup(
address account,
uint256 currencyId,
uint256 oldSettleTime,
uint256 blockTime
) internal returns (int256 totalAssetCash, uint256 newSettleTime) {
bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId);
// This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and
// `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason
// that lastSettleBit is inclusive is that it refers to newSettleTime which always less
// than the current block time.
newSettleTime = DateTime.getTimeUTC0(blockTime);
// If newSettleTime == oldSettleTime lastSettleBit will be zero
require(newSettleTime >= oldSettleTime); // dev: new settle time before previous
// Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until
// the closest maturity that is less than newSettleTime.
(uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime);
if (lastSettleBit == 0) return (totalAssetCash, newSettleTime);
// Returns the next bit that is set in the bitmap
uint256 nextBitNum = bitmap.getNextBitNum();
while (nextBitNum != 0 && nextBitNum <= lastSettleBit) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
totalAssetCash = totalAssetCash.add(
_settlefCashAsset(account, currencyId, maturity, blockTime)
);
// Turn the bit off now that it is settled
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
bytes32 newBitmap;
while (nextBitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
(uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity);
require(isValid); // dev: invalid new bit num
newBitmap = newBitmap.setBit(newBitNum, true);
// Turn the bit off now that it is remapped
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap);
}
/// @dev Stateful settlement function to settle a bitmapped asset. Deletes the
/// asset from storage after calculating it.
function _settlefCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) private returns (int256 assetCash) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
int256 notional = store[account][currencyId][maturity].notional;
// Gets the current settlement rate or will store a new settlement rate if it does not
// yet exist.
AssetRateParameters memory rate =
AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime);
assetCash = rate.convertFromUnderlying(notional);
delete store[account][currencyId][maturity];
return assetCash;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../markets/DateTime.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AssetHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
function isLiquidityToken(uint256 assetType) internal pure returns (bool) {
return
assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX;
}
/// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method
/// calculates the settlement date for any PortfolioAsset.
function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) {
require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type
// 3 month tokens and fCash tokens settle at maturity
if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity;
uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1);
// Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is:
// maturity = tRef + marketLength
// Here we calculate:
// tRef = (maturity - marketLength) + 90 days
return asset.maturity.sub(marketLength).add(Constants.QUARTER);
}
/// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity.
/// The formula is: e^(-rate * timeToMaturity).
function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME));
expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue));
expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64);
int256 discountFactor = ABDKMath64x64.toInt(expValue);
return discountFactor;
}
/// @notice Present value of an fCash asset without any risk adjustments.
function getPresentfCashValue(
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate);
require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more
/// heavily than the oracle rate given and vice versa for negative fCash.
function getRiskAdjustedPresentfCashValue(
CashGroupParameters memory cashGroup,
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor;
if (notional > 0) {
// If fCash is positive then discounting by a higher rate will result in a smaller
// discount factor (e ^ -x), meaning a lower positive fCash value.
discountFactor = getDiscountFactor(
timeToMaturity,
oracleRate.add(cashGroup.getfCashHaircut())
);
} else {
uint256 debtBuffer = cashGroup.getDebtBuffer();
// If the adjustment exceeds the oracle rate we floor the value of the fCash
// at the notional value. We don't want to require the account to hold more than
// absolutely required.
if (debtBuffer >= oracleRate) return notional;
discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer);
}
require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Returns the non haircut claims on cash and fCash by the liquidity token.
function getCashClaims(PortfolioAsset memory token, MarketParameters memory market)
internal
pure
returns (int256 assetCash, int256 fCash)
{
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims
assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity);
fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity);
}
/// @notice Returns the haircut claims on cash and fCash
function getHaircutCashClaims(
PortfolioAsset memory token,
MarketParameters memory market,
CashGroupParameters memory cashGroup
) internal pure returns (int256 assetCash, int256 fCash) {
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims
require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch
// This won't overflow, the liquidity token haircut is stored as an uint8
int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType));
assetCash =
_calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity);
fCash =
_calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity);
return (assetCash, fCash);
}
/// @dev This is here to clean up the stack in getHaircutCashClaims
function _calcToken(
int256 numerator,
int256 tokens,
int256 haircut,
int256 liquidity
) private pure returns (int256) {
return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity);
}
/// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists)
function getLiquidityTokenValue(
uint256 index,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
PortfolioAsset[] memory assets,
uint256 blockTime,
bool riskAdjusted
) internal view returns (int256, int256) {
PortfolioAsset memory liquidityToken = assets[index];
{
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(
cashGroup.maxMarketIndex,
liquidityToken.maturity,
blockTime
);
// Liquidity tokens can never be idiosyncratic
require(!idiosyncratic); // dev: idiosyncratic liquidity token
// This market will always be initialized, if a liquidity token exists that means the
// market has some liquidity in it.
cashGroup.loadMarket(market, marketIndex, true, blockTime);
}
int256 assetCashClaim;
int256 fCashClaim;
if (riskAdjusted) {
(assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup);
} else {
(assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market);
}
// Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and
// in that case we know the previous asset will be the matching fCash asset
if (index > 0) {
PortfolioAsset memory maybefCash = assets[index - 1];
if (
maybefCash.assetType == Constants.FCASH_ASSET_TYPE &&
maybefCash.currencyId == liquidityToken.currencyId &&
maybefCash.maturity == liquidityToken.maturity
) {
// Net off the fCashClaim here and we will discount it to present value in the second pass.
// WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio!
maybefCash.notional = maybefCash.notional.add(fCashClaim);
// This state will prevent the fCash asset from being stored.
maybefCash.storageState = AssetStorageState.RevertIfStored;
return (assetCashClaim, 0);
}
}
// If not matching fCash asset found then get the pv directly
if (riskAdjusted) {
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
fCashClaim,
liquidityToken.maturity,
blockTime,
market.oracleRate
);
return (assetCashClaim, pv);
} else {
int256 pv =
getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate);
return (assetCashClaim, pv);
}
}
/// @notice Returns present value of all assets in the cash group as asset cash and the updated
/// portfolio index where the function has ended.
/// @return the value of the cash group in asset cash
function getNetCashGroupValue(
PortfolioAsset[] memory assets,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 blockTime,
uint256 portfolioIndex
) internal view returns (int256, uint256) {
int256 presentValueAsset;
int256 presentValueUnderlying;
// First calculate value of liquidity tokens because we need to net off fCash value
// before discounting to present value
for (uint256 i = portfolioIndex; i < assets.length; i++) {
if (!isLiquidityToken(assets[i].assetType)) continue;
if (assets[i].currencyId != cashGroup.currencyId) break;
(int256 assetCashClaim, int256 pv) =
getLiquidityTokenValue(
i,
cashGroup,
market,
assets,
blockTime,
true // risk adjusted
);
presentValueAsset = presentValueAsset.add(assetCashClaim);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
uint256 j = portfolioIndex;
for (; j < assets.length; j++) {
PortfolioAsset memory a = assets[j];
if (a.assetType != Constants.FCASH_ASSET_TYPE) continue;
// If we hit a different currency id then we've accounted for all assets in this currency
// j will mark the index where we don't have this currency anymore
if (a.currencyId != cashGroup.currencyId) break;
uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime);
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
a.notional,
a.maturity,
blockTime,
oracleRate
);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
presentValueAsset = presentValueAsset.add(
cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying)
);
return (presentValueAsset, j);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
import "./Constants.sol";
import "../../interfaces/notional/IRewarder.sol";
import "../../interfaces/aave/ILendingPool.sol";
library LibStorage {
/// @dev Offset for the initial slot in lib storage, gives us this number of storage slots
/// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it.
uint256 private constant STORAGE_SLOT_BASE = 1000000;
/// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX
/// in practice. It is possible to exceed that value during liquidation up to 14 potential assets.
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @dev Storage IDs for storage buckets. Each id maps to an internal storage
/// slot used for a particular mapping
/// WARNING: APPEND ONLY
enum StorageId {
Unused,
AccountStorage,
nTokenContext,
nTokenAddress,
nTokenDeposit,
nTokenInitialization,
Balance,
Token,
SettlementRate,
CashGroup,
Market,
AssetsBitmap,
ifCashBitmap,
PortfolioArray,
// WARNING: this nTokenTotalSupply storage object was used for a buggy version
// of the incentives calculation. It should only be used for accounts who have
// not claimed before the migration
nTokenTotalSupply_deprecated,
AssetRate,
ExchangeRate,
nTokenTotalSupply,
SecondaryIncentiveRewarder,
LendingPool
}
/// @dev Mapping from an account address to account context
function getAccountStorage() internal pure
returns (mapping(address => AccountContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AccountStorage);
assembly { store.slot := slot }
}
/// @dev Mapping from an nToken address to nTokenContext
function getNTokenContextStorage() internal pure
returns (mapping(address => nTokenContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenContext);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to nTokenAddress
function getNTokenAddressStorage() internal pure
returns (mapping(uint256 => address) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenAddress);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to uint32 fixed length array of
/// deposit factors. Deposit shares and leverage thresholds are stored striped to
/// reduce the number of storage reads.
function getNTokenDepositStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenDeposit);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to fixed length array of initialization factors,
/// stored striped like deposit shares.
function getNTokenInitStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenInitialization);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currencyId to it's balance storage for that currency
function getBalanceStorage() internal pure
returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Balance);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to a boolean for underlying or asset token to
/// the TokenStorage
function getTokenStorage() internal pure
returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Token);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its corresponding SettlementRate
function getSettlementRateStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SettlementRate);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its tightly packed cash group parameters
function getCashGroupStorage() internal pure
returns (mapping(uint256 => bytes32) storage store)
{
uint256 slot = _getStorageSlot(StorageId.CashGroup);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to settlement date for a market
function getMarketStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Market);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its assets bitmap
function getAssetsBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => bytes32)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetsBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance
function getifCashBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ifCashBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to its fixed length array of portfolio assets
function getPortfolioArrayStorage() internal pure
returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.PortfolioArray);
assembly { store.slot := slot }
}
function getDeprecatedNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated);
assembly { store.slot := slot }
}
/// @dev Mapping from nToken address to its total supply values
function getNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and asset for trading
/// and free collateral. Mapping is from currency id to rate storage object.
function getAssetRateStorage() internal pure
returns (mapping(uint256 => AssetRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetRate);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and ETH for free
/// collateral purposes. Mapping is from currency id to rate storage object.
function getExchangeRateStorage() internal pure
returns (mapping(uint256 => ETHRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ExchangeRate);
assembly { store.slot := slot }
}
/// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists
function getSecondaryIncentiveRewarder() internal pure
returns (mapping(address => IRewarder) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder);
assembly { store.slot := slot }
}
/// @dev Returns the address of the lending pool
function getLendingPool() internal pure returns (LendingPoolStorage storage store) {
uint256 slot = _getStorageSlot(StorageId.LendingPool);
assembly { store.slot := slot }
}
/// @dev Get the storage slot given a storage ID.
/// @param storageId An entry in `StorageId`
/// @return slot The storage slot.
function _getStorageSlot(StorageId storageId)
private
pure
returns (uint256 slot)
{
// This should never overflow with a reasonable `STORAGE_SLOT_EXP`
// because Solidity will do a range check on `storageId` during the cast.
return uint256(storageId) + STORAGE_SLOT_BASE;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../AccountContextHandler.sol";
import "../markets/CashGroup.sol";
import "../valuation/AssetHandler.sol";
import "../../math/Bitmap.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library BitmapAssetsHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using Bitmap for bytes32;
using CashGroup for CashGroupParameters;
using AccountContextHandler for AccountContext;
function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) {
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
return store[account][currencyId];
}
function setAssetsBitmap(
address account,
uint256 currencyId,
bytes32 assetsBitmap
) internal {
require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets");
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
store[account][currencyId] = assetsBitmap;
}
function getifCashNotional(
address account,
uint256 currencyId,
uint256 maturity
) internal view returns (int256 notional) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
return store[account][currencyId][maturity].notional;
}
/// @notice Adds multiple assets to a bitmap portfolio
function addMultipleifCashAssets(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal {
require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set
uint256 currencyId = accountContext.bitmapCurrencyId;
for (uint256 i; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets
require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets
int256 finalNotional;
finalNotional = addifCashAsset(
account,
currencyId,
asset.maturity,
accountContext.nextSettleTime,
asset.notional
);
if (finalNotional < 0)
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
}
}
/// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory
/// but not in storage.
/// @return the updated assets bitmap and the final notional amount
function addifCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 nextSettleTime,
int256 notional
) internal returns (int256) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
(uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity);
require(isExact); // dev: invalid maturity in set ifcash asset
if (assetsBitmap.isBitSet(bitNum)) {
// Bit is set so we read and update the notional amount
int256 finalNotional = notional.add(fCashSlot.notional);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
// If the new notional is zero then turn off the bit
if (finalNotional == 0) {
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
setAssetsBitmap(account, currencyId, assetsBitmap);
return finalNotional;
}
if (notional != 0) {
// Bit is not set so we turn it on and update the mapping directly, no read required.
require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(notional);
assetsBitmap = assetsBitmap.setBit(bitNum, true);
setAssetsBitmap(account, currencyId, assetsBitmap);
}
return notional;
}
/// @notice Returns the present value of an asset
function getPresentValue(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256) {
int256 notional = getifCashNotional(account, currencyId, maturity);
// In this case the asset has matured and the total value is just the notional amount
if (maturity <= blockTime) {
return notional;
} else {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
if (riskAdjusted) {
return AssetHandler.getRiskAdjustedPresentfCashValue(
cashGroup,
notional,
maturity,
blockTime,
oracleRate
);
} else {
return AssetHandler.getPresentfCashValue(
notional,
maturity,
blockTime,
oracleRate
);
}
}
}
function getNetPresentValueFromBitmap(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted,
bytes32 assetsBitmap
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 pv = getPresentValue(
account,
currencyId,
maturity,
blockTime,
cashGroup,
riskAdjusted
);
totalValueUnderlying = totalValueUnderlying.add(pv);
if (pv < 0) hasDebt = true;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
}
/// @notice Get the net present value of all the ifCash assets
function getifCashNetPresentValue(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
return getNetPresentValueFromBitmap(
account,
currencyId,
nextSettleTime,
blockTime,
cashGroup,
riskAdjusted,
assetsBitmap
);
}
/// @notice Returns the ifCash assets as an array
function getifCashArray(
address account,
uint256 currencyId,
uint256 nextSettleTime
) internal view returns (PortfolioAsset[] memory) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
uint256 index = assetsBitmap.totalBitsSet();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 notional = getifCashNotional(account, currencyId, maturity);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notional;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../interfaces/chainlink/AggregatorV2V3Interface.sol";
import "../../interfaces/notional/AssetRateAdapter.sol";
/// @notice Different types of internal tokens
/// - UnderlyingToken: underlying asset for a cToken (except for Ether)
/// - cToken: Compound interest bearing token
/// - cETH: Special handling for cETH tokens
/// - Ether: the one and only
/// - NonMintable: tokens that do not have an underlying (therefore not cTokens)
/// - aToken: Aave interest bearing tokens
enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken}
/// @notice Specifies the different trade action types in the system. Each trade action type is
/// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the
/// 32 byte trade action object. The schemas for each trade action type are defined below.
enum TradeActionType {
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused)
Lend,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused)
Borrow,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
AddLiquidity,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
RemoveLiquidity,
// (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused)
PurchaseNTokenResidual,
// (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle)
SettleCashDebt
}
/// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades
enum DepositActionType {
// No deposit action
None,
// Deposit asset cash, depositActionAmount is specified in asset cash external precision
DepositAsset,
// Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token
// external precision
DepositUnderlying,
// Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of
// nTokens into the account
DepositAssetAndMintNToken,
// Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens
DepositUnderlyingAndMintNToken,
// Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action
// because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert.
RedeemNToken,
// Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in
// Notional internal 8 decimal precision.
ConvertCashToNToken
}
/// @notice Used internally for PortfolioHandler state
enum AssetStorageState {NoChange, Update, Delete, RevertIfStored}
/****** Calldata objects ******/
/// @notice Defines a balance action for batchAction
struct BalanceAction {
// Deposit action to take (if any)
DepositActionType actionType;
uint16 currencyId;
// Deposit action amount must correspond to the depositActionType, see documentation above.
uint256 depositActionAmount;
// Withdraw an amount of asset cash specified in Notional internal 8 decimal precision
uint256 withdrawAmountInternalPrecision;
// If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash
// residual left from trading.
bool withdrawEntireCashBalance;
// If set to true, will redeem asset cash to the underlying token on withdraw.
bool redeemToUnderlying;
}
/// @notice Defines a balance action with a set of trades to do as well
struct BalanceActionWithTrades {
DepositActionType actionType;
uint16 currencyId;
uint256 depositActionAmount;
uint256 withdrawAmountInternalPrecision;
bool withdrawEntireCashBalance;
bool redeemToUnderlying;
// Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation
bytes32[] trades;
}
/****** In memory objects ******/
/// @notice Internal object that represents settled cash balances
struct SettleAmount {
uint256 currencyId;
int256 netCashChange;
}
/// @notice Internal object that represents a token
struct Token {
address tokenAddress;
bool hasTransferFee;
int256 decimals;
TokenType tokenType;
uint256 maxCollateralBalance;
}
/// @notice Internal object that represents an nToken portfolio
struct nTokenPortfolio {
CashGroupParameters cashGroup;
PortfolioState portfolioState;
int256 totalSupply;
int256 cashBalance;
uint256 lastInitializedTime;
bytes6 parameters;
address tokenAddress;
}
/// @notice Internal object used during liquidation
struct LiquidationFactors {
address account;
// Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision
int256 netETHValue;
// Amount of net local currency asset cash before haircuts and buffers available
int256 localAssetAvailable;
// Amount of net collateral currency asset cash before haircuts and buffers available
int256 collateralAssetAvailable;
// Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based
// on liquidation type
int256 nTokenHaircutAssetValue;
// nToken parameters for calculating liquidation amount
bytes6 nTokenParameters;
// ETH exchange rate from local currency to ETH
ETHRate localETHRate;
// ETH exchange rate from collateral currency to ETH
ETHRate collateralETHRate;
// Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required
AssetRateParameters localAssetRate;
// Used during currency liquidations if the account has liquidity tokens
CashGroupParameters collateralCashGroup;
// Used during currency liquidations if it is only a calculation, defaults to false
bool isCalculation;
}
/// @notice Internal asset array portfolio state
struct PortfolioState {
// Array of currently stored assets
PortfolioAsset[] storedAssets;
// Array of new assets to add
PortfolioAsset[] newAssets;
uint256 lastNewAssetIndex;
// Holds the length of stored assets after accounting for deleted assets
uint256 storedAssetLength;
}
/// @notice In memory ETH exchange rate used during free collateral calculation.
struct ETHRate {
// The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle
int256 rateDecimals;
// The exchange rate from base to ETH (if rate invert is required it is already done)
int256 rate;
// Amount of buffer as a multiple with a basis of 100 applied to negative balances.
int256 buffer;
// Amount of haircut as a multiple with a basis of 100 applied to positive balances
int256 haircut;
// Liquidation discount as a multiple with a basis of 100 applied to the exchange rate
// as an incentive given to liquidators.
int256 liquidationDiscount;
}
/// @notice Internal object used to handle balance state during a transaction
struct BalanceState {
uint16 currencyId;
// Cash balance stored in balance state at the beginning of the transaction
int256 storedCashBalance;
// nToken balance stored at the beginning of the transaction
int256 storedNTokenBalance;
// The net cash change as a result of asset settlement or trading
int256 netCashChange;
// Net asset transfers into or out of the account
int256 netAssetTransferInternalPrecision;
// Net token transfers into or out of the account
int256 netNTokenTransfer;
// Net token supply change from minting or redeeming
int256 netNTokenSupplyChange;
// The last time incentives were claimed for this currency
uint256 lastClaimTime;
// Accumulator for incentives that the account no longer has a claim over
uint256 accountIncentiveDebt;
}
/// @dev Asset rate used to convert between underlying cash and asset cash
struct AssetRateParameters {
// Address of the asset rate oracle
AssetRateAdapter rateOracle;
// The exchange rate from base to quote (if invert is required it is already done)
int256 rate;
// The decimals of the underlying, the rate converts to the underlying decimals
int256 underlyingDecimals;
}
/// @dev Cash group when loaded into memory
struct CashGroupParameters {
uint16 currencyId;
uint256 maxMarketIndex;
AssetRateParameters assetRate;
bytes32 data;
}
/// @dev A portfolio asset when loaded in memory
struct PortfolioAsset {
// Asset currency id
uint256 currencyId;
uint256 maturity;
// Asset type, fCash or liquidity token.
uint256 assetType;
// fCash amount or liquidity token amount
int256 notional;
// Used for managing portfolio asset state
uint256 storageSlot;
// The state of the asset for when it is written to storage
AssetStorageState storageState;
}
/// @dev Market object as represented in memory
struct MarketParameters {
bytes32 storageSlot;
uint256 maturity;
// Total amount of fCash available for purchase in the market.
int256 totalfCash;
// Total amount of cash available for purchase in the market.
int256 totalAssetCash;
// Total amount of liquidity tokens (representing a claim on liquidity) in the market.
int256 totalLiquidity;
// This is the previous annualized interest rate in RATE_PRECISION that the market traded
// at. This is used to calculate the rate anchor to smooth interest rates over time.
uint256 lastImpliedRate;
// Time lagged version of lastImpliedRate, used to value fCash assets at market rates while
// remaining resistent to flash loan attacks.
uint256 oracleRate;
// This is the timestamp of the previous trade
uint256 previousTradeTime;
}
/****** Storage objects ******/
/// @dev Token object in storage:
/// 20 bytes for token address
/// 1 byte for hasTransferFee
/// 1 byte for tokenType
/// 1 byte for tokenDecimals
/// 9 bytes for maxCollateralBalance (may not always be set)
struct TokenStorage {
// Address of the token
address tokenAddress;
// Transfer fees will change token deposit behavior
bool hasTransferFee;
TokenType tokenType;
uint8 decimalPlaces;
// Upper limit on how much of this token the contract can hold at any time
uint72 maxCollateralBalance;
}
/// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes.
struct ETHRateStorage {
// Address of the rate oracle
AggregatorV2V3Interface rateOracle;
// The decimal places of precision that the rate oracle uses
uint8 rateDecimalPlaces;
// True of the exchange rate must be inverted
bool mustInvert;
// NOTE: both of these governance values are set with BUFFER_DECIMALS precision
// Amount of buffer to apply to the exchange rate for negative balances.
uint8 buffer;
// Amount of haircut to apply to the exchange rate for positive balances
uint8 haircut;
// Liquidation discount in percentage point terms, 106 means a 6% discount
uint8 liquidationDiscount;
}
/// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes.
struct AssetRateStorage {
// Address of the rate oracle
AssetRateAdapter rateOracle;
// The decimal places of the underlying asset
uint8 underlyingDecimalPlaces;
}
/// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts
/// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there
/// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the
/// length.
struct CashGroupSettings {
// Index of the AMMs on chain that will be made available. Idiosyncratic fCash
// that is dated less than the longest AMM will be tradable.
uint8 maxMarketIndex;
// Time window in 5 minute increments that the rate oracle will be averaged over
uint8 rateOracleTimeWindow5Min;
// Total fees per trade, specified in BPS
uint8 totalFeeBPS;
// Share of the fees given to the protocol, denominated in percentage
uint8 reserveFeeShare;
// Debt buffer specified in 5 BPS increments
uint8 debtBuffer5BPS;
// fCash haircut specified in 5 BPS increments
uint8 fCashHaircut5BPS;
// If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This
// is the basis points for the penalty rate that will be added the current 3 month oracle rate.
uint8 settlementPenaltyRate5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationfCashHaircut5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationDebtBuffer5BPS;
// Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100
uint8[] liquidityTokenHaircuts;
// Rate scalar used to determine the slippage of the market
uint8[] rateScalars;
}
/// @dev Holds account level context information used to determine settlement and
/// free collateral actions. Total storage is 28 bytes
struct AccountContext {
// Used to check when settlement must be triggered on an account
uint40 nextSettleTime;
// For lenders that never incur debt, we use this flag to skip the free collateral check.
bytes1 hasDebt;
// Length of the account's asset array
uint8 assetArrayLength;
// If this account has bitmaps set, this is the corresponding currency id
uint16 bitmapCurrencyId;
// 9 total active currencies possible (2 bytes each)
bytes18 activeCurrencies;
}
/// @dev Holds nToken context information mapped via the nToken address, total storage is
/// 16 bytes
struct nTokenContext {
// Currency id that the nToken represents
uint16 currencyId;
// Annual incentive emission rate denominated in WHOLE TOKENS (multiply by
// INTERNAL_TOKEN_PRECISION to get the actual rate)
uint32 incentiveAnnualEmissionRate;
// The last block time at utc0 that the nToken was initialized at, zero if it
// has never been initialized
uint32 lastInitializedTime;
// Length of the asset array, refers to the number of liquidity tokens an nToken
// currently holds
uint8 assetArrayLength;
// Each byte is a specific nToken parameter
bytes5 nTokenParameters;
// Reserved bytes for future usage
bytes15 _unused;
// Set to true if a secondary rewarder is set
bool hasSecondaryRewarder;
}
/// @dev Holds account balance information, total storage 32 bytes
struct BalanceStorage {
// Number of nTokens held by the account
uint80 nTokenBalance;
// Last time the account claimed their nTokens
uint32 lastClaimTime;
// Incentives that the account no longer has a claim over
uint56 accountIncentiveDebt;
// Cash balance of the account
int88 cashBalance;
}
/// @dev Holds information about a settlement rate, total storage 25 bytes
struct SettlementRateStorage {
uint40 blockTime;
uint128 settlementRate;
uint8 underlyingDecimalPlaces;
}
/// @dev Holds information about a market, total storage is 42 bytes so this spans
/// two storage words
struct MarketStorage {
// Total fCash in the market
uint80 totalfCash;
// Total asset cash in the market
uint80 totalAssetCash;
// Last annualized interest rate the market traded at
uint32 lastImpliedRate;
// Last recorded oracle rate for the market
uint32 oracleRate;
// Last time a trade was made
uint32 previousTradeTime;
// This is stored in slot + 1
uint80 totalLiquidity;
}
struct ifCashStorage {
// Notional amount of fCash at the slot, limited to int128 to allow for
// future expansion
int128 notional;
}
/// @dev A single portfolio asset in storage, total storage of 19 bytes
struct PortfolioAssetStorage {
// Currency Id for the asset
uint16 currencyId;
// Maturity of the asset
uint40 maturity;
// Asset type (fCash or Liquidity Token marker)
uint8 assetType;
// Notional
int88 notional;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes. This is the deprecated version
struct nTokenTotalSupplyStorage_deprecated {
// Total supply of the nToken
uint96 totalSupply;
// Integral of the total supply used for calculating the average total supply
uint128 integralTotalSupply;
// Last timestamp the supply value changed, used for calculating the integralTotalSupply
uint32 lastSupplyChangeTime;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes.
struct nTokenTotalSupplyStorage {
// Total supply of the nToken
uint96 totalSupply;
// How many NOTE incentives should be issued per nToken in 1e18 precision
uint128 accumulatedNOTEPerNToken;
// Last timestamp when the accumulation happened
uint32 lastAccumulatedTime;
}
/// @dev Used in view methods to return account balances in a developer friendly manner
struct AccountBalance {
uint16 currencyId;
int256 cashBalance;
int256 nTokenBalance;
uint256 lastClaimTime;
uint256 accountIncentiveDebt;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title All shared constants for the Notional system should be declared here.
library Constants {
uint8 internal constant CETH_DECIMAL_PLACES = 8;
// Token precision used for all internal balances, TokenHandler library ensures that we
// limit the dust amount caused by precision mismatches
int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;
uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18;
// ETH will be initialized as the first currency
uint256 internal constant ETH_CURRENCY_ID = 1;
uint8 internal constant ETH_DECIMAL_PLACES = 18;
int256 internal constant ETH_DECIMALS = 1e18;
// Used to prevent overflow when converting decimal places to decimal precision values via
// 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this
// constraint when storing decimal places in governance.
uint256 internal constant MAX_DECIMAL_PLACES = 36;
// Address of the reserve account
address internal constant RESERVE = address(0);
// Most significant bit
bytes32 internal constant MSB =
0x8000000000000000000000000000000000000000000000000000000000000000;
// Each bit set in this mask marks where an active market should be in the bitmap
// if the first bit refers to the reference time. Used to detect idiosyncratic
// fcash in the nToken accounts
bytes32 internal constant ACTIVE_MARKETS_MASK = (
MSB >> ( 90 - 1) | // 3 month
MSB >> (105 - 1) | // 6 month
MSB >> (135 - 1) | // 1 year
MSB >> (147 - 1) | // 2 year
MSB >> (183 - 1) | // 5 year
MSB >> (211 - 1) | // 10 year
MSB >> (251 - 1) // 20 year
);
// Basis for percentages
int256 internal constant PERCENTAGE_DECIMALS = 100;
// Max number of traded markets, also used as the maximum number of assets in a portfolio array
uint256 internal constant MAX_TRADED_MARKET_INDEX = 7;
// Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral
// for a bitmap portfolio
uint256 internal constant MAX_BITMAP_ASSETS = 20;
uint256 internal constant FIVE_MINUTES = 300;
// Internal date representations, note we use a 6/30/360 week/month/year convention here
uint256 internal constant DAY = 86400;
// We use six day weeks to ensure that all time references divide evenly
uint256 internal constant WEEK = DAY * 6;
uint256 internal constant MONTH = WEEK * 5;
uint256 internal constant QUARTER = MONTH * 3;
uint256 internal constant YEAR = QUARTER * 4;
// These constants are used in DateTime.sol
uint256 internal constant DAYS_IN_WEEK = 6;
uint256 internal constant DAYS_IN_MONTH = 30;
uint256 internal constant DAYS_IN_QUARTER = 90;
// Offsets for each time chunk denominated in days
uint256 internal constant MAX_DAY_OFFSET = 90;
uint256 internal constant MAX_WEEK_OFFSET = 360;
uint256 internal constant MAX_MONTH_OFFSET = 2160;
uint256 internal constant MAX_QUARTER_OFFSET = 7650;
// Offsets for each time chunk denominated in bits
uint256 internal constant WEEK_BIT_OFFSET = 90;
uint256 internal constant MONTH_BIT_OFFSET = 135;
uint256 internal constant QUARTER_BIT_OFFSET = 195;
// This is a constant that represents the time period that all rates are normalized by, 360 days
uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY;
// Number of decimal places that rates are stored in, equals 100%
int256 internal constant RATE_PRECISION = 1e9;
// One basis point in RATE_PRECISION terms
uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000);
// Used to when calculating the amount to deleverage of a market when minting nTokens
uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT;
// Used for scaling cash group factors
uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT;
// Used for residual purchase incentive and cash withholding buffer
uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT;
// This is the ABDK64x64 representation of RATE_PRECISION
// RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION)
int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000;
int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176;
// Limit the market proportion so that borrowing cannot hit extremely high interest rates
int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100;
uint8 internal constant FCASH_ASSET_TYPE = 1;
// Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed)
uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2;
uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8;
// Used for converting bool to bytes1, solidity does not have a native conversion
// method for this
bytes1 internal constant BOOL_FALSE = 0x00;
bytes1 internal constant BOOL_TRUE = 0x01;
// Account context flags
bytes1 internal constant HAS_ASSET_DEBT = 0x01;
bytes1 internal constant HAS_CASH_DEBT = 0x02;
bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000;
bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000;
bytes2 internal constant UNMASK_FLAGS = 0x3FFF;
uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS);
// Equal to 100% of all deposit amounts for nToken liquidity across fCash markets.
int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8;
// nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned
// in nTokenHandler. Each constant represents a position in the byte array.
uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0;
uint8 internal constant CASH_WITHHOLDING_BUFFER = 1;
uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2;
uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3;
uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4;
// Liquidation parameters
// Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account
// requires more collateral to be liquidated
int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40;
// Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens
int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30;
// Pause Router liquidation enabled states
bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01;
bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02;
bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04;
bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library DateTime {
using SafeMath for uint256;
/// @notice Returns the current reference time which is how all the AMM dates are calculated.
function getReferenceTime(uint256 blockTime) internal pure returns (uint256) {
require(blockTime >= Constants.QUARTER);
return blockTime - (blockTime % Constants.QUARTER);
}
/// @notice Truncates a date to midnight UTC time
function getTimeUTC0(uint256 time) internal pure returns (uint256) {
require(time >= Constants.DAY);
return time - (time % Constants.DAY);
}
/// @notice These are the predetermined market offsets for trading
/// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group.
function getTradedMarket(uint256 index) internal pure returns (uint256) {
if (index == 1) return Constants.QUARTER;
if (index == 2) return 2 * Constants.QUARTER;
if (index == 3) return Constants.YEAR;
if (index == 4) return 2 * Constants.YEAR;
if (index == 5) return 5 * Constants.YEAR;
if (index == 6) return 10 * Constants.YEAR;
if (index == 7) return 20 * Constants.YEAR;
revert("Invalid index");
}
/// @notice Determines if the maturity falls on one of the valid on chain market dates.
function isValidMarketMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
if (maturity % Constants.QUARTER != 0) return false;
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true;
}
return false;
}
/// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case.
function isValidMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
uint256 tRef = DateTime.getReferenceTime(blockTime);
uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex));
// Cannot trade past max maturity
if (maturity > maxMaturity) return false;
// prettier-ignore
(/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity);
return isValid;
}
/// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic
/// will return the nearest market index that is larger than the maturity.
/// @return uint marketIndex, bool isIdiosyncratic
function getMarketIndex(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (uint256, bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i));
// If market matches then is not idiosyncratic
if (marketMaturity == maturity) return (i, false);
// Returns the market that is immediately greater than the maturity
if (marketMaturity > maturity) return (i, true);
}
revert("CG: no market found");
}
/// @notice Given a bit number and the reference time of the first bit, returns the bit number
/// of a given maturity.
/// @return bitNum and a true or false if the maturity falls on the exact bit
function getBitNumFromMaturity(uint256 blockTime, uint256 maturity)
internal
pure
returns (uint256, bool)
{
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
// Maturities must always divide days evenly
if (maturity % Constants.DAY != 0) return (0, false);
// Maturity cannot be in the past
if (blockTimeUTC0 >= maturity) return (0, false);
// Overflow check done above
// daysOffset has no remainders, checked above
uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY;
// These if statements need to fall through to the next one
if (daysOffset <= Constants.MAX_DAY_OFFSET) {
return (daysOffset, true);
} else if (daysOffset <= Constants.MAX_WEEK_OFFSET) {
// (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0
// (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion
// This returns the offset from the previous max offset in days
uint256 offsetInDays =
daysOffset -
Constants.MAX_DAY_OFFSET +
(blockTimeUTC0 % Constants.WEEK) /
Constants.DAY;
return (
// This converts the offset in days to its corresponding bit position, truncating down
// if it does not divide evenly into DAYS_IN_WEEK
Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK,
(offsetInDays % Constants.DAYS_IN_WEEK) == 0
);
} else if (daysOffset <= Constants.MAX_MONTH_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_WEEK_OFFSET +
(blockTimeUTC0 % Constants.MONTH) /
Constants.DAY;
return (
Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH,
(offsetInDays % Constants.DAYS_IN_MONTH) == 0
);
} else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_MONTH_OFFSET +
(blockTimeUTC0 % Constants.QUARTER) /
Constants.DAY;
return (
Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER,
(offsetInDays % Constants.DAYS_IN_QUARTER) == 0
);
}
// This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20
// year max maturity
return (256, false);
}
/// @notice Given a bit number and a block time returns the maturity that the bit number
/// should reference. Bit numbers are one indexed.
function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum)
internal
pure
returns (uint256)
{
require(bitNum != 0); // dev: cash group get maturity from bit num is zero
require(bitNum <= 256); // dev: cash group get maturity from bit num overflow
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
uint256 firstBit;
if (bitNum <= Constants.WEEK_BIT_OFFSET) {
return blockTimeUTC0 + bitNum * Constants.DAY;
} else if (bitNum <= Constants.MONTH_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_DAY_OFFSET * Constants.DAY -
// This backs up to the day that is divisible by a week
(blockTimeUTC0 % Constants.WEEK);
return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK;
} else if (bitNum <= Constants.QUARTER_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_WEEK_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.MONTH);
return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH;
} else {
firstBit =
blockTimeUTC0 +
Constants.MAX_MONTH_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.QUARTER);
return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER;
}
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (63 - (x >> 64));
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
if (xx >= 0x100) { xx >>= 8; r <<= 4; }
if (xx >= 0x10) { xx >>= 4; r <<= 2; }
if (xx >= 0x8) { r <<= 1; }
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128 (r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
// SPDX-License-Identifier: GPL-v3
pragma solidity >=0.7.0;
/// @notice Used as a wrapper for tokens that are interest bearing for an
/// underlying token. Follows the cToken interface, however, can be adapted
/// for other interest bearing tokens.
interface AssetRateAdapter {
function token() external view returns (address);
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function underlying() external view returns (address);
function getExchangeRateStateful() external returns (int256);
function getExchangeRateView() external view returns (int256);
function getAnnualizedSupplyRate() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
interface IRewarder {
function claimRewards(
address account,
uint16 currencyId,
uint256 nTokenBalanceBefore,
uint256 nTokenBalanceAfter,
int256 netNTokenSupplyChange,
uint256 NOTETokensClaimed
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
struct LendingPoolStorage {
ILendingPool lendingPool;
}
interface ILendingPool {
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (ReserveData memory);
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TokenHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenSupply.sol";
import "../../math/SafeInt256.sol";
import "../../external/MigrateIncentives.sol";
import "../../../interfaces/notional/IRewarder.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Incentives {
using SafeMath for uint256;
using SafeInt256 for int256;
/// @notice Calculates the total incentives to claim including those claimed under the previous
/// less accurate calculation. Once an account is migrated it will only claim incentives under
/// the more accurate regime
function calculateIncentivesToClaim(
BalanceState memory balanceState,
address tokenAddress,
uint256 accumulatedNOTEPerNToken,
uint256 finalNTokenBalance
) internal view returns (uint256 incentivesToClaim) {
if (balanceState.lastClaimTime > 0) {
// If lastClaimTime is set then the account had incentives under the
// previous regime. Will calculate the final amount of incentives to claim here
// under the previous regime.
incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation(
tokenAddress,
balanceState.storedNTokenBalance.toUint(),
balanceState.lastClaimTime,
// In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under
// the old calculation
balanceState.accountIncentiveDebt
);
// This marks the account as migrated and lastClaimTime will no longer be used
balanceState.lastClaimTime = 0;
// This value will be set immediately after this, set this to zero so that the calculation
// establishes a new baseline.
balanceState.accountIncentiveDebt = 0;
}
// If an account was migrated then they have no accountIncentivesDebt and should accumulate
// incentives based on their share since the new regime calculation started.
// If an account is just initiating their nToken balance then storedNTokenBalance will be zero
// and they will have no incentives to claim.
// This calculation uses storedNTokenBalance which is the balance of the account up until this point,
// this is important to ensure that the account does not claim for nTokens that they will mint or
// redeem on a going forward basis.
// The calculation below has the following precision:
// storedNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION
incentivesToClaim = incentivesToClaim.add(
balanceState.storedNTokenBalance.toUint()
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.sub(balanceState.accountIncentiveDebt)
);
// Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion
// of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance
// here instead of storedNTokenBalance to mark the overall incentives claim that the account
// does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt
// because accumulatedNOTEPerNToken is already an aggregated value.
// The calculation below has the following precision:
// finalNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION
balanceState.accountIncentiveDebt = finalNTokenBalance
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION);
}
/// @notice Incentives must be claimed every time nToken balance changes.
/// @dev BalanceState.accountIncentiveDebt is updated in place here
function claimIncentives(
BalanceState memory balanceState,
address account,
uint256 finalNTokenBalance
) internal returns (uint256 incentivesToClaim) {
uint256 blockTime = block.timestamp;
address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId);
// This will updated the nToken storage and return what the accumulatedNOTEPerNToken
// is up until this current block time in 1e18 precision
uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply(
tokenAddress,
balanceState.netNTokenSupplyChange,
blockTime
);
incentivesToClaim = calculateIncentivesToClaim(
balanceState,
tokenAddress,
accumulatedNOTEPerNToken,
finalNTokenBalance
);
// If a secondary incentive rewarder is set, then call it
IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress);
if (address(rewarder) != address(0)) {
rewarder.claimRewards(
account,
balanceState.currencyId,
// When this method is called from finalize, the storedNTokenBalance has not
// been updated to finalNTokenBalance yet so this is the balance before the change.
balanceState.storedNTokenBalance.toUint(),
finalNTokenBalance,
// When the rewarder is called, totalSupply has been updated already so may need to
// adjust its calculation using the net supply change figure here. Supply change
// may be zero when nTokens are transferred.
balanceState.netNTokenSupplyChange,
incentivesToClaim
);
}
if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../global/Deployments.sol";
import "./protocols/AaveHandler.sol";
import "./protocols/CompoundHandler.sol";
import "./protocols/GenericToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @notice Handles all external token transfers and events
library TokenHandler {
using SafeInt256 for int256;
using SafeMath for uint256;
function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][false];
tokenStorage.maxCollateralBalance = maxCollateralBalance;
}
function getAssetToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, false);
}
function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, true);
}
/// @notice Gets token data for a particular currency id, if underlying is set to true then returns
/// the underlying token. (These may not always exist)
function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][underlying];
return
Token({
tokenAddress: tokenStorage.tokenAddress,
hasTransferFee: tokenStorage.hasTransferFee,
// No overflow, restricted on storage
decimals: int256(10**tokenStorage.decimalPlaces),
tokenType: tokenStorage.tokenType,
maxCollateralBalance: tokenStorage.maxCollateralBalance
});
}
/// @notice Sets a token for a currency id.
function setToken(
uint256 currencyId,
bool underlying,
TokenStorage memory tokenStorage
) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) {
// Hardcoded parameters for ETH just to make sure we don't get it wrong.
TokenStorage storage ts = store[currencyId][true];
ts.tokenAddress = address(0);
ts.hasTransferFee = false;
ts.tokenType = TokenType.Ether;
ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES;
ts.maxCollateralBalance = 0;
return;
}
// Check token address
require(tokenStorage.tokenAddress != address(0), "TH: address is zero");
// Once a token is set we cannot override it. In the case that we do need to do change a token address
// then we should explicitly upgrade this method to allow for a token to be changed.
Token memory token = _getToken(currencyId, underlying);
require(
token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0),
"TH: token cannot be reset"
);
require(0 < tokenStorage.decimalPlaces
&& tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals");
// Validate token type
require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once
if (underlying) {
// Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily
// during mint and redeem actions.
require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance
require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent
} else {
require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent
}
if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) {
// Set the approval for the underlying so that we can mint cTokens or aTokens
Token memory underlyingToken = getUnderlyingToken(currencyId);
// cTokens call transfer from the tokenAddress, but aTokens use the LendingPool
// to initiate all transfers
address approvalAddress = tokenStorage.tokenType == TokenType.cToken ?
tokenStorage.tokenAddress :
address(LibStorage.getLendingPool().lendingPool);
// ERC20 tokens should return true on success for an approval, but Tether
// does not return a value here so we use the NonStandard interface here to
// check that the approval was successful.
IEIP20NonStandard(underlyingToken.tokenAddress).approve(
approvalAddress,
type(uint256).max
);
GenericToken.checkReturnCode();
}
store[currencyId][underlying] = tokenStorage;
}
/**
* @notice If a token is mintable then will mint it. At this point we expect to have the underlying
* balance in the contract already.
* @param assetToken the asset token to mint
* @param underlyingAmountExternal the amount of underlying to transfer to the mintable token
* @return the amount of asset tokens minted, will always be a positive integer
*/
function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) {
// aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this
// value in internal accounting since it will not allow individual users to accrue aToken interest. Use the
// scaledBalanceOf function call instead for internal accounting.
bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
if (assetToken.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
AaveHandler.mint(underlyingToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
CompoundHandler.mint(assetToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cETH) {
CompoundHandler.mintCETH(assetToken);
} else {
revert(); // dev: non mintable token
}
uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
// This is the starting and ending balance in external precision
return SafeInt256.toInt(endingBalance.sub(startingBalance));
}
/**
* @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance
* to the account
* @param assetToken asset token to redeem
* @param currencyId the currency id of the token
* @param account account to transfer the underlying to
* @param assetAmountExternal the amount to transfer in asset token denomination and external precision
* @return the actual amount of underlying tokens transferred. this is used as a return value back to the
* user, is not used for internal accounting purposes
*/
function redeem(
Token memory assetToken,
uint256 currencyId,
address account,
uint256 assetAmountExternal
) internal returns (int256) {
uint256 transferAmount;
if (assetToken.tokenType == TokenType.cETH) {
transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal);
} else {
Token memory underlyingToken = getUnderlyingToken(currencyId);
if (assetToken.tokenType == TokenType.aToken) {
transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal);
} else {
revert(); // dev: non redeemable token
}
}
// Use the negative value here to signify that assets have left the protocol
return SafeInt256.toInt(transferAmount).neg();
}
/// @notice Handles transfers into and out of the system denominated in the external token decimal
/// precision.
function transfer(
Token memory token,
address account,
uint256 currencyId,
int256 netTransferExternal
) internal returns (int256 actualTransferExternal) {
// This will be true in all cases except for deposits where the token has transfer fees. For
// aTokens this value is set before convert from scaled balances to principal plus interest
actualTransferExternal = netTransferExternal;
if (token.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
// aTokens need to be converted when we handle the transfer since the external balance format
// is not the same as the internal balance format that we use
netTransferExternal = AaveHandler.convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
netTransferExternal
);
}
if (netTransferExternal > 0) {
// Deposits must account for transfer fees.
int256 netDeposit = _deposit(token, account, uint256(netTransferExternal));
// If an aToken has a transfer fee this will still return a balance figure
// in scaledBalanceOf terms due to the selector
if (token.hasTransferFee) actualTransferExternal = netDeposit;
} else if (token.tokenType == TokenType.Ether) {
// netTransferExternal can only be negative or zero at this point
GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg()));
} else {
GenericToken.safeTransferOut(
token.tokenAddress,
account,
// netTransferExternal is zero or negative here
uint256(netTransferExternal.neg())
);
}
}
/// @notice Handles token deposits into Notional. If there is a transfer fee then we must
/// calculate the net balance after transfer. Amounts are denominated in the destination token's
/// precision.
function _deposit(
Token memory token,
address account,
uint256 amount
) private returns (int256) {
uint256 startingBalance;
uint256 endingBalance;
bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
if (token.hasTransferFee) {
startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
GenericToken.safeTransferIn(token.tokenAddress, account, amount);
if (token.hasTransferFee || token.maxCollateralBalance > 0) {
// If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably
// the correct behavior because if collateral accrues interest over time we should not somehow go over the
// maxCollateralBalance due to the passage of time.
endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
if (token.maxCollateralBalance > 0) {
int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance));
// Max collateral balance is stored as uint72, no overflow
require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance
}
// Math is done in uint inside these statements and will revert on negative
if (token.hasTransferFee) {
return SafeInt256.toInt(endingBalance.sub(startingBalance));
} else {
return SafeInt256.toInt(amount);
}
}
function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) {
// If token decimals > INTERNAL_TOKEN_PRECISION:
// on deposit: resulting dust will accumulate to protocol
// on withdraw: protocol may lose dust amount. However, withdraws are only calculated based
// on a conversion from internal token precision to external token precision so therefore dust
// amounts cannot be specified for withdraws.
// If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the
// end of amount and will not result in dust.
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals);
}
function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) {
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
// If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount
// by adding a number of zeros to the end and will not result in dust.
// If token decimals < INTERNAL_TOKEN_PRECISION:
// on deposit: Deposits are specified in external token precision and there is no loss of precision when
// tokens are converted from external to internal precision
// on withdraw: this calculation will round down such that the protocol retains the residual cash balance
return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION);
}
function transferIncentive(address account, uint256 tokensToTransfer) internal {
GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "./Bitmap.sol";
/**
* Packs an uint value into a "floating point" storage slot. Used for storing
* lastClaimIntegralSupply values in balance storage. For these values, we don't need
* to maintain exact precision but we don't want to be limited by storage size overflows.
*
* A floating point value is defined by the 48 most significant bits and an 8 bit number
* of bit shifts required to restore its precision. The unpacked value will always be less
* than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1.
*/
library FloatingPoint56 {
function packTo56Bits(uint256 value) internal pure returns (uint56) {
uint256 bitShift;
// If the value is over the uint48 max value then we will shift it down
// given the index of the most significant bit. We store this bit shift
// in the least significant byte of the 56 bit slot available.
if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47);
uint256 shiftedValue = value >> bitShift;
return uint56((shiftedValue << 8) | bitShift);
}
function unpackFrom56Bits(uint256 value) internal pure returns (uint256) {
// The least significant 8 bits will be the amount to bit shift
uint256 bitShift = uint256(uint8(value));
return ((value >> 8) << bitShift);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenSupply.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenHandler {
using SafeInt256 for int256;
/// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning
/// two constants to each other.
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @notice Returns an account context object that is specific to nTokens.
function getNTokenContext(address tokenAddress)
internal
view
returns (
uint16 currencyId,
uint256 incentiveAnnualEmissionRate,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
)
{
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
currencyId = context.currencyId;
incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate;
lastInitializedTime = context.lastInitializedTime;
assetArrayLength = context.assetArrayLength;
parameters = context.nTokenParameters;
}
/// @notice Returns the nToken token address for a given currency
function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) {
mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage();
return store[currencyId];
}
/// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be
/// reset once this is set.
function setNTokenAddress(uint16 currencyId, address tokenAddress) internal {
mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage();
require(addressStore[currencyId] == address(0), "PT: token address exists");
mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage();
nTokenContext storage context = contextStore[tokenAddress];
require(context.currencyId == 0, "PT: currency exists");
// This will initialize all other context slots to zero
context.currencyId = currencyId;
addressStore[currencyId] = tokenAddress;
}
/// @notice Set nToken token collateral parameters
function setNTokenCollateralParameters(
address tokenAddress,
uint8 residualPurchaseIncentive10BPS,
uint8 pvHaircutPercentage,
uint8 residualPurchaseTimeBufferHours,
uint8 cashWithholdingBuffer10BPS,
uint8 liquidationHaircutPercentage
) internal {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut");
// The pv haircut percentage must be less than the liquidation percentage or else liquidators will not
// get profit for liquidating nToken.
require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut");
// Ensure that the cash withholding buffer is greater than the residual purchase incentive or
// the nToken may not have enough cash to pay accounts to buy its negative ifCash
require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts");
bytes5 parameters =
(bytes5(uint40(residualPurchaseIncentive10BPS)) |
(bytes5(uint40(pvHaircutPercentage)) << 8) |
(bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) |
(bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) |
(bytes5(uint40(liquidationHaircutPercentage)) << 32));
// Set the parameters
context.nTokenParameters = parameters;
}
/// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different
/// contract, aside from the native NOTE token incentives.
function setSecondaryRewarder(
uint16 currencyId,
IRewarder rewarder
) internal {
address tokenAddress = nTokenAddress(currencyId);
// nToken must exist for a secondary rewarder
require(tokenAddress != address(0));
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
// Setting the rewarder to address(0) will disable it. We use a context setting here so that
// we can save a storage read before getting the rewarder
context.hasSecondaryRewarder = (address(rewarder) != address(0));
LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder;
}
/// @notice Returns the secondary rewarder if it is set
function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
if (context.hasSecondaryRewarder) {
return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress];
} else {
return IRewarder(address(0));
}
}
function setArrayLengthAndInitializedTime(
address tokenAddress,
uint8 arrayLength,
uint256 lastInitializedTime
) internal {
require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.lastInitializedTime = uint32(lastInitializedTime);
context.assetArrayLength = arrayLength;
}
/// @notice Returns the array of deposit shares and leverage thresholds for nTokens
function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory depositShares, int256[] memory leverageThresholds)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
(depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false);
}
/// @notice Sets the deposit parameters
/// @dev We pack the values in alternating between the two parameters into either one or two
// storage slots depending on the number of markets. This is to save storage reads when we use the parameters.
function setDepositParameters(
uint256 currencyId,
uint32[] calldata depositShares,
uint32[] calldata leverageThresholds
) internal {
require(
depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX,
"PT: deposit share length"
);
require(depositShares.length == leverageThresholds.length, "PT: leverage share length");
uint256 shareSum;
for (uint256 i; i < depositShares.length; i++) {
// This cannot overflow in uint 256 with 9 max slots
shareSum = shareSum + depositShares[i];
require(
leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION,
"PT: leverage threshold"
);
}
// Total deposit share must add up to 100%
require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum");
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
_setParameters(depositParameters, depositShares, leverageThresholds);
}
/// @notice Sets the initialization parameters for the markets, these are read only when markets
/// are initialized
function setInitializationParameters(
uint256 currencyId,
uint32[] calldata annualizedAnchorRates,
uint32[] calldata proportions
) internal {
require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length");
require(proportions.length == annualizedAnchorRates.length, "PT: proportions length");
for (uint256 i; i < proportions.length; i++) {
// Proportions must be between zero and the rate precision
require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero");
require(
proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION,
"PT: invalid proportion"
);
}
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
_setParameters(initParameters, annualizedAnchorRates, proportions);
}
/// @notice Returns the array of initialization parameters for a given currency.
function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory annualizedAnchorRates, int256[] memory proportions)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
(annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true);
}
function _getParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint256 maxMarketIndex,
bool noUnset
) private view returns (int256[] memory, int256[] memory) {
uint256 index = 0;
int256[] memory array1 = new int256[](maxMarketIndex);
int256[] memory array2 = new int256[](maxMarketIndex);
for (uint256 i; i < maxMarketIndex; i++) {
array1[i] = slot[index];
index++;
array2[i] = slot[index];
index++;
if (noUnset) {
require(array1[i] > 0 && array2[i] > 0, "PT: init value zero");
}
}
return (array1, array2);
}
function _setParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint32[] calldata array1,
uint32[] calldata array2
) private {
uint256 index = 0;
for (uint256 i = 0; i < array1.length; i++) {
slot[index] = array1[i];
index++;
slot[index] = array2[i];
index++;
}
}
function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
nToken.tokenAddress = nTokenAddress(currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
) = getNTokenContext(nToken.tokenAddress);
// prettier-ignore
(
uint256 totalSupply,
/* accumulatedNOTEPerNToken */,
/* lastAccumulatedTime */
) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress);
nToken.lastInitializedTime = lastInitializedTime;
nToken.totalSupply = int256(totalSupply);
nToken.parameters = parameters;
nToken.portfolioState = PortfolioHandler.buildPortfolioState(
nToken.tokenAddress,
assetArrayLength,
0
);
// prettier-ignore
(
nToken.cashBalance,
/* nTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId);
}
/// @notice Uses buildCashGroupStateful
function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId)
internal
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
}
/// @notice Uses buildCashGroupView
function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupView(currencyId);
}
/// @notice Returns the next settle time for the nToken which is 1 quarter away
function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) {
if (nToken.lastInitializedTime == 0) return 0;
return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenSupply {
using SafeInt256 for int256;
using SafeMath for uint256;
/// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating
/// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead.
function getStoredNTokenSupplyFactors(address tokenAddress)
internal
view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
totalSupply = nTokenStorage.totalSupply;
// NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken
// must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead
accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken;
lastAccumulatedTime = nTokenStorage.lastAccumulatedTime;
}
/// @notice Returns the updated accumulated NOTE per nToken for calculating incentives
function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime)
internal view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
(
totalSupply,
accumulatedNOTEPerNToken,
lastAccumulatedTime
) = getStoredNTokenSupplyFactors(tokenAddress);
// nToken totalSupply is never allowed to drop to zero but we check this here to avoid
// divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not
// zero to avoid a massive accumulation amount on initialization.
if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) {
// prettier-ignore
(
/* currencyId */,
uint256 emissionRatePerYear,
/* initializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(tokenAddress);
uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE(
// Emission rate is denominated in whole tokens, scale to 1e8 decimals here
emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)),
// Time since last accumulation (overflow checked above)
blockTime - lastAccumulatedTime,
totalSupply
);
accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken);
require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow
}
}
/// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision
function _calculateAdditionalNOTE(
uint256 emissionRatePerYear,
uint256 timeSinceLastAccumulation,
uint256 totalSupply
)
private
pure
returns (uint256)
{
// If we use 18 decimal places as the accumulation precision then we will overflow uint128 when
// a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max
// NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe
// using 18 decimal places and uint128 storage slot
// timeSinceLastAccumulation (SECONDS)
// accumulatedNOTEPerSharePrecision (1e18)
// emissionRatePerYear (INTERNAL_TOKEN_PRECISION)
// DIVIDE BY
// YEAR (SECONDS)
// totalSupply (INTERNAL_TOKEN_PRECISION)
return timeSinceLastAccumulation
.mul(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.mul(emissionRatePerYear)
.div(Constants.YEAR)
// totalSupply > 0 is checked in the calling function
.div(totalSupply);
}
/// @notice Updates the nToken token supply amount when minting or redeeming.
/// @param tokenAddress address of the nToken
/// @param netChange positive or negative change to the total nToken supply
/// @param blockTime current block time
/// @return accumulatedNOTEPerNToken updated to the given block time
function changeNTokenSupply(
address tokenAddress,
int256 netChange,
uint256 blockTime
) internal returns (uint256) {
(
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
/* uint256 lastAccumulatedTime */
) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime);
// Update storage variables
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
int256 newTotalSupply = int256(totalSupply).add(netChange);
// We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to
// exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check.
require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow
nTokenStorage.totalSupply = uint96(newTotalSupply);
// NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what
// the user would see if querying the view function
nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken);
require(blockTime < type(uint32).max); // dev: block time overflow
nTokenStorage.lastAccumulatedTime = uint32(blockTime);
return accumulatedNOTEPerNToken;
}
/// @notice Called by governance to set the new emission rate
function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal {
// Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the
// emission rate
changeNTokenSupply(tokenAddress, 0, blockTime);
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.incentiveAnnualEmissionRate = newEmissionsRate;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "../internal/nToken/nTokenHandler.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @notice Deployed library for migration of incentives from the old (inaccurate) calculation
* to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate
* calculation is inside `Incentives.sol` and this library holds the legacy calculation. System
* migration code can be found in `MigrateIncentivesFix.sol`
*/
library MigrateIncentives {
using SafeMath for uint256;
/// @notice Calculates the claimable incentives for a particular nToken and account in the
/// previous regime. This should only ever be called ONCE for an account / currency combination
/// to get the incentives accrued up until the migration date.
function migrateAccountFromPreviousCalculation(
address tokenAddress,
uint256 nTokenBalance,
uint256 lastClaimTime,
uint256 lastClaimIntegralSupply
) external view returns (uint256) {
(
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) = _getMigratedIncentiveValues(tokenAddress);
// This if statement should never be true but we return 0 just in case
if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0;
// No overflow here, checked above. All incentives are claimed up until finalMigrationTime
// using the finalTotalIntegralSupply. Both these values are set on migration and will not
// change.
uint256 timeSinceMigration = finalMigrationTime - lastClaimTime;
// (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR
uint256 incentiveRate =
timeSinceMigration
.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
// Migration emission rate is stored as is, denominated in whole tokens
.mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
.div(Constants.YEAR);
// Returns the average supply using the integral of the total supply.
uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration);
if (avgTotalSupply == 0) return 0;
uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply);
// incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8
incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION));
return incentivesToClaim;
}
function _getMigratedIncentiveValues(
address tokenAddress
) private view returns (
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) {
mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress];
// The total supply value is overridden as emissionRatePerYear during the initialization
finalEmissionRatePerYear = d_nTokenStorage.totalSupply;
finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply;
finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce
/// gas costs for immutable addresses. They must be updated per environment that Notional
/// is deployed to.
library Deployments {
address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../../global/Types.sol";
import "../../../global/LibStorage.sol";
import "../../../math/SafeInt256.sol";
import "../TokenHandler.sol";
import "../../../../interfaces/aave/IAToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AaveHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
int256 internal constant RAY = 1e27;
int256 internal constant halfRAY = RAY / 2;
bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector;
/**
* @notice Mints an amount of aTokens corresponding to the the underlying.
* @param underlyingToken address of the underlying token to pass to Aave
* @param underlyingAmountExternal amount of underlying to deposit, in external precision
*/
function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal {
// In AaveV3 this method is renamed to supply() but deposit() is still available for
// backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755
// We use deposit here so that mainnet-fork tests against Aave v2 will pass.
LibStorage.getLendingPool().lendingPool.deposit(
underlyingToken.tokenAddress,
underlyingAmountExternal,
address(this),
0
);
}
/**
* @notice Redeems and sends an amount of aTokens to the specified account
* @param underlyingToken address of the underlying token to pass to Aave
* @param account account to receive the underlying
* @param assetAmountExternal amount of aTokens in scaledBalanceOf terms
*/
function redeem(
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
underlyingAmountExternal = convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
SafeInt256.toInt(assetAmountExternal)
).toUint();
LibStorage.getLendingPool().lendingPool.withdraw(
underlyingToken.tokenAddress,
underlyingAmountExternal,
account
);
}
/**
* @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest)
* and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional
* claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will
* receive future Aave interest.
* @dev There is no loss of precision within this function since it does the exact same calculation as Aave.
* @param currencyId is the currency id
* @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must
* be positive in this function, this method is only called when depositing aTokens directly
* @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will
* be in external precision.
*/
function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0);
Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress);
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
int256 halfIndex = index / 2;
// Overflow will occur when: (a * RAY + halfIndex) > int256.max
require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY);
// if index is zero then this will revert
return (assetAmountExternal * RAY + halfIndex) / index;
}
/**
* @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision)
* and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest
* that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions.
* @dev There is no loss of precision because this does exactly what Aave's calculation would do
* @param underlyingToken token address of the underlying asset
* @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from
* Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or
* withdrawn (negative).
* @return netBalanceExternal the Aave balanceOf equivalent as a signed integer
*/
function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) {
if (netScaledBalanceExternal == 0) return 0;
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken);
// Use the absolute value here so that the halfRay rounding is applied correctly for negative values
int256 abs = netScaledBalanceExternal.abs();
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
// Overflow will occur when: (abs * index + halfRay) > int256.max
// Here the first term is computed at compile time so it just does a division. If index is zero then
// solidity will revert.
require(abs <= (type(int256).max - halfRAY) / index);
int256 absScaled = (abs * index + halfRAY) / RAY;
return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg();
}
/// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is
/// always positive even though we are converting to a signed int
function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) {
return
SafeInt256.toInt(
LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./GenericToken.sol";
import "../../../../interfaces/compound/CErc20Interface.sol";
import "../../../../interfaces/compound/CEtherInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../global/Types.sol";
library CompoundHandler {
using SafeMath for uint256;
// Return code for cTokens that represents no error
uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0;
function mintCETH(Token memory token) internal {
// Reverts on error
CEtherInterface(token.tokenAddress).mint{value: msg.value}();
}
function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) {
uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint");
}
function redeemCETH(
Token memory assetToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = address(this).balance;
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = address(this).balance;
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.transferNativeTokenOut(account, underlyingAmountExternal);
}
function redeem(
Token memory assetToken,
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../../../../interfaces/IEIP20NonStandard.sol";
library GenericToken {
bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector;
/**
* @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows
* for overriding the balanceOf selector to use scaledBalanceOf for aTokens
*/
function checkBalanceViaSelector(
address token,
address account,
bytes4 balanceOfSelector
) internal returns (uint256 balance) {
(bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account));
require(success);
(balance) = abi.decode(returnData, (uint256));
}
function transferNativeTokenOut(
address account,
uint256 amount
) internal {
// This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying
// ETH they will have to withdraw the cETH token and then redeem it manually.
payable(account).transfer(amount);
}
function safeTransferOut(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transfer(account, amount);
checkReturnCode();
}
function safeTransferIn(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transferFrom(account, address(this), amount);
checkReturnCode();
}
function checkReturnCode() internal pure {
bool success;
uint256[1] memory result;
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
success := 1 // set success to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(result, 0, 32)
success := mload(result) // Set `success = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "ERC20");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IAToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
function symbol() external view returns (string memory);
}
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
interface IATokenFull is IScaledBalanceToken, IERC20 {
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
import "./CTokenInterface.sol";
interface CErc20Interface {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CEtherInterface {
function mint() external payable;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface IEIP20NonStandard {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
*/
function approve(address spender, uint256 amount) external;
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CTokenInterface {
/*** User Interface ***/
function underlying() external view returns (address);
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) external view returns (uint);
function exchangeRateCurrent() external returns (uint);
function exchangeRateStored() external view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() external returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/Types.sol";
import "../global/Constants.sol";
/// @notice Helper methods for bitmaps, they are big-endian and 1-indexed.
library Bitmap {
/// @notice Set a bit on or off in a bitmap, index is 1-indexed
function setBit(
bytes32 bitmap,
uint256 index,
bool setOn
) internal pure returns (bytes32) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
if (setOn) {
return bitmap | (Constants.MSB >> (index - 1));
} else {
return bitmap & ~(Constants.MSB >> (index - 1));
}
}
/// @notice Check if a bit is set
function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB;
}
/// @notice Count the total bits set
function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) {
uint256 x = uint256(bitmap);
x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555);
x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333);
x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4);
x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F);
x = x + (x >> 16);
x = x + (x >> 32);
x = x + (x >> 64);
return (x & 0xFF) + (x >> 128 & 0xFF);
}
// Does a binary search over x to get the position of the most significant bit
function getMSB(uint256 x) internal pure returns (uint256 msb) {
// If x == 0 then there is no MSB and this method will return zero. That would
// be the same as the return value when x == 1 (MSB is zero indexed), so instead
// we have this require here to ensure that the values don't get mixed up.
require(x != 0); // dev: get msb zero value
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
msb += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
msb += 64;
}
if (x >= 0x100000000) {
x >>= 32;
msb += 32;
}
if (x >= 0x10000) {
x >>= 16;
msb += 16;
}
if (x >= 0x100) {
x >>= 8;
msb += 8;
}
if (x >= 0x10) {
x >>= 4;
msb += 4;
}
if (x >= 0x4) {
x >>= 2;
msb += 2;
}
if (x >= 0x2) msb += 1; // No need to shift xc anymore
}
/// @dev getMSB returns a zero indexed bit number where zero is the first bit counting
/// from the right (little endian). Asset Bitmaps are counted from the left (big endian)
/// and one indexed.
function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) {
// Short circuit the search if bitmap is all zeros
if (bitmap == 0x00) return 0;
return 255 - getMSB(uint256(bitmap)) + 1;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../balances/TokenHandler.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/chainlink/AggregatorV2V3Interface.sol";
library ExchangeRate {
using SafeInt256 for int256;
/// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are
/// always applied in this method.
/// @param er exchange rate object from base to ETH
/// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION
function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) {
int256 multiplier = balance > 0 ? er.haircut : er.buffer;
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals)
// Therefore the result is in ethDecimals
int256 result =
balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div(
er.rateDecimals
);
return result;
}
/// @notice Converts the balance denominated in ETH to the equivalent value in a base currency.
/// Buffers and haircuts ARE NOT applied in this method.
/// @param er exchange rate object from base to ETH
/// @param balance amount (denominated in ETH) to convert
function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) {
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals / rateDecimals
int256 result = balance.mul(er.rateDecimals).div(er.rate);
return result;
}
/// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in
/// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals
/// @param baseER base exchange rate struct
/// @param quoteER quote exchange rate struct
function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER)
internal
pure
returns (int256)
{
return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate);
}
/// @notice Returns an ETHRate object used to calculate free collateral
function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) {
mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage();
ETHRateStorage storage ethStorage = store[currencyId];
int256 rateDecimals;
int256 rate;
if (currencyId == Constants.ETH_CURRENCY_ID) {
// ETH rates will just be 1e18, but will still have buffers, haircuts,
// and liquidation discounts
rateDecimals = Constants.ETH_DECIMALS;
rate = Constants.ETH_DECIMALS;
} else {
// prettier-ignore
(
/* roundId */,
rate,
/* uint256 startedAt */,
/* updatedAt */,
/* answeredInRound */
) = ethStorage.rateOracle.latestRoundData();
require(rate > 0, "Invalid rate");
// No overflow, restricted on storage
rateDecimals = int256(10**ethStorage.rateDecimalPlaces);
if (ethStorage.mustInvert) {
rate = rateDecimals.mul(rateDecimals).div(rate);
}
}
return
ETHRate({
rateDecimals: rateDecimals,
rate: rate,
buffer: ethStorage.buffer,
haircut: ethStorage.haircut,
liquidationDiscount: ethStorage.liquidationDiscount
});
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
library nTokenCalculations {
using Bitmap for bytes32;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using CashGroup for CashGroupParameters;
/// @notice Returns the nToken present value denominated in asset terms.
function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256)
{
int256 totalAssetPV;
int256 totalUnderlyingPV;
{
uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken);
// If the first asset maturity has passed (the 3 month), this means that all the LTs must
// be settled except the 6 month (which is now the 3 month). We don't settle LTs except in
// initialize markets so we calculate the cash value of the portfolio here.
if (nextSettleTime <= blockTime) {
// NOTE: this condition should only be present for a very short amount of time, which is the window between
// when the markets are no longer tradable at quarter end and when the new markets have been initialized.
// We time travel back to one second before maturity to value the liquidity tokens. Although this value is
// not strictly correct the different should be quite slight. We do this to ensure that free collateral checks
// for withdraws and liquidations can still be processed. If this condition persists for a long period of time then
// the entire protocol will have serious problems as markets will not be tradable.
blockTime = nextSettleTime - 1;
}
}
// This is the total value in liquid assets
(int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime);
// Then get the total value in any idiosyncratic fCash residuals (if they exist)
bytes32 ifCashBits = getNTokenifCashBits(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
int256 ifCashResidualUnderlyingPV = 0;
if (ifCashBits != 0) {
// Non idiosyncratic residuals have already been accounted for
(ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
false, // nToken present value calculation does not use risk adjusted values
ifCashBits
);
}
// Return the total present value denominated in asset terms
return totalAssetValueInMarkets
.add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV))
.add(nToken.cashBalance);
}
/**
* @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts
* in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken
* portfolio.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to
* the account's share of the total supply
* @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually
* withdrawn from markets
*/
function _getProportionalLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem
) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) {
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
tokensToWithdraw = new int256[](numMarkets);
netfCash = new int256[](numMarkets);
for (uint256 i = 0; i < numMarkets; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply);
}
}
/**
* @notice Returns the number of liquidity tokens to withdraw from each market if the nToken
* has idiosyncratic residuals during nToken redeem. In this case the redeemer will take
* their cash from the rest of the fCash markets, redeeming around the nToken.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param blockTime block time
* @param ifCashBits the bits in the bitmap that represent ifCash assets
* @return tokensToWithdraw array of tokens to withdraw from each corresponding market
* @return netfCash array of netfCash amounts to go back to the account
*/
function getLiquidityTokenWithdraw(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
uint256 blockTime,
bytes32 ifCashBits
) internal view returns (int256[] memory, int256[] memory) {
// If there are no ifCash bits set then this will just return the proportion of all liquidity tokens
if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem);
(
int256 totalAssetValueInMarkets,
int256[] memory netfCash
) = getNTokenMarketValue(nToken, blockTime);
int256[] memory tokensToWithdraw = new int256[](netfCash.length);
// NOTE: this total portfolio asset value does not include any cash balance the nToken may hold.
// The redeemer will always get a proportional share of this cash balance and therefore we don't
// need to account for it here when we calculate the share of liquidity tokens to withdraw. We are
// only concerned with the nToken's portfolio assets in this method.
int256 totalPortfolioAssetValue;
{
// Returns the risk adjusted net present value for the idiosyncratic residuals
(int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
true, // use risk adjusted here to assess a penalty for withdrawing around the residual
ifCashBits
);
// NOTE: we do not include cash balance here because the account will always take their share
// of the cash balance regardless of the residuals
totalPortfolioAssetValue = totalAssetValueInMarkets.add(
nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV)
);
}
// Loops through each liquidity token and calculates how much the redeemer can withdraw to get
// the requisite amount of present value after adjusting for the ifCash residual value that is
// not accessible via redemption.
for (uint256 i = 0; i < tokensToWithdraw.length; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
// Redeemer's baseline share of the liquidity tokens based on total supply:
// redeemerShare = totalTokens * nTokensToRedeem / totalSupply
// Scalar factor to account for residual value (need to inflate the tokens to withdraw
// proportional to the value locked up in ifCash residuals):
// scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets
// Final math equals:
// tokensToWithdraw = redeemerShare * scalarFactor
// tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue)
// / (totalAssetValueInMarkets * totalSupply)
tokensToWithdraw[i] = totalTokens
.mul(nTokensToRedeem)
.mul(totalPortfolioAssetValue);
tokensToWithdraw[i] = tokensToWithdraw[i]
.div(totalAssetValueInMarkets)
.div(nToken.totalSupply);
// This is the share of net fcash that will be credited back to the account
netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens);
}
return (tokensToWithdraw, netfCash);
}
/// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by
/// the liquidity tokens held in each market and their corresponding fCash positions. The formula
/// can be described as:
/// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash))
/// where netfCash = fCashClaim + fCash
/// and fCash refers the the fCash position at the corresponding maturity
function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256 totalAssetValue, int256[] memory netfCash)
{
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
netfCash = new int256[](numMarkets);
MarketParameters memory market;
for (uint256 i = 0; i < numMarkets; i++) {
// Load the corresponding market into memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i];
uint256 maturity = liquidityToken.maturity;
// Get the fCash claims and fCash assets. We do not use haircut versions here because
// nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied
// at the end of the calculation to the entire PV instead).
(int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market);
// fCash is denominated in underlying
netfCash[i] = fCashClaim.add(
BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
maturity
)
);
// This calculates for a single liquidity token:
// assetCashClaim + convertToAssetCash(pv(netfCash))
int256 netAssetValueInMarket = assetCashClaim.add(
nToken.cashGroup.assetRate.convertFromUnderlying(
AssetHandler.getPresentfCashValue(
netfCash[i],
maturity,
blockTime,
// No need to call cash group for oracle rate, it is up to date here
// and we are assured to be referring to this market.
market.oracleRate
)
)
);
// Calculate the running total
totalAssetValue = totalAssetValue.add(netAssetValueInMarket);
}
}
/// @notice Returns just the bits in a bitmap that are idiosyncratic
function getNTokenifCashBits(
address tokenAddress,
uint256 currencyId,
uint256 lastInitializedTime,
uint256 blockTime,
uint256 maxMarketIndex
) internal view returns (bytes32) {
// If max market index is less than or equal to 2, there are never ifCash assets by construction
if (maxMarketIndex <= 2) return bytes32(0);
bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId);
// Handles the case when there are no assets at the first initialization
if (assetsBitmap == 0) return assetsBitmap;
uint256 tRef = DateTime.getReferenceTime(blockTime);
if (tRef == lastInitializedTime) {
// This is a more efficient way to turn off ifCash assets in the common case when the market is
// initialized immediately
return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK);
} else {
// In this branch, initialize markets has occurred past the time above. It would occur in these
// two scenarios (both should be exceedingly rare):
// 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef)
// 2. somehow initialize markets has been delayed for more than 24 hours
for (uint i = 1; i <= maxMarketIndex; i++) {
// In this loop we get the maturity of each active market and turn off the corresponding bit
// one by one. It is less efficient than the option above.
uint256 maturity = tRef + DateTime.getTradedMarket(i);
(uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity);
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
return assetsBitmap;
}
}
} | Stateful settlement function to settle a bitmapped asset. Deletes the asset from storage after calculating it. Gets the current settlement rate or will store a new settlement rate if it does not yet exist. | function _settlefCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) private returns (int256 assetCash) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
int256 notional = store[account][currencyId][maturity].notional;
AssetRateParameters memory rate =
AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime);
assetCash = rate.convertFromUnderlying(notional);
delete store[account][currencyId][maturity];
return assetCash;
}
| 12,410 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./ERC721Min.sol";
contract OwnableDelegateProxy {}
contract OpenSeaProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract NFTSales is Ownable, ERC721Min, ReentrancyGuard {
using Strings for uint256;
using SafeERC20 for IERC20;
address public immutable proxyRegistryAddress; // opensea proxy
mapping(address => bool) proxyToApproved; // proxy allowance for interaction with future contract
string private _contractURI;
string private _tokenBaseURI = ""; // SET TO THE METADATA URI
address private treasuryAddress = 0x14891CD5d3Aa2D858b1daEB1eDeEAB605eebcFCb;
bool useBaseUriOnly = true;
mapping(uint256 => string) public TokenURIMap; // allows for assigning individual/unique metada per token
struct NftType {
uint16 purchaseCount;
uint16 maxPerAddress;
uint16 maxPerMint;
uint16 maxPerAddressForThree;
uint16 maxMint;
uint16 maxMintForOne;
uint16 maxMintForThree;
bool saleActive;
uint256 price;
uint256 priceForThree;
mapping(address => uint256) PurchasesByAddress;
string uri;
}
struct FeeRecipient {
address recipient;
uint256 basisPoints;
}
mapping(uint256 => FeeRecipient) public FeeRecipients;
uint256 feeRecipientCount;
uint256 totalFeeBasisPoints;
mapping(uint256 => NftType) public NftTypes;
uint256 public nftTypeCount;
bool public transferDisabled;
mapping(uint256 => uint256) public NftIdToNftType;
constructor() ERC721Min("ASSASSIN-8 UTILITY NFT", "ASS8U") {
proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
}
function totalSupply() external view returns(uint256) {
return _owners.length;
}
// ** - CORE - ** //
function buyOne(uint256 nftTypeId) external payable {
require(NftTypes[nftTypeId].saleActive, "SALE_CLOSED");
require(NftTypes[nftTypeId].price == msg.value, "INCORRECT_ETH");
require(NftTypes[nftTypeId].maxMintForOne > NftTypes[nftTypeId].purchaseCount, "EXCEED_MAX_SALE_SUPPLY");
require(NftTypes[nftTypeId].maxPerAddress == 0 ||
NftTypes[nftTypeId].PurchasesByAddress[_msgSender()] < NftTypes[nftTypeId].maxPerAddress, "EXCEED_MAX_PER_USER");
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin();
if (NftTypes[nftTypeId].maxPerAddress > 0) NftTypes[nftTypeId].PurchasesByAddress[_msgSender()]++;
NftTypes[nftTypeId].purchaseCount++;
}
function buyThree(uint256 nftTypeId) external payable {
require(NftTypes[nftTypeId].saleActive, "SALE_CLOSED");
require(NftTypes[nftTypeId].priceForThree == msg.value, "INCORRECT_ETH");
require(NftTypes[nftTypeId].maxMintForThree > NftTypes[nftTypeId].purchaseCount, "EXCEED_MAX_SALE_SUPPLY");
require(NftTypes[nftTypeId].maxPerAddress == 0 ||
NftTypes[nftTypeId].PurchasesByAddress[_msgSender()] < NftTypes[nftTypeId].maxPerAddressForThree, "EXCEED_MAX_PER_USER");
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin();
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin();
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin();
if (NftTypes[nftTypeId].maxPerAddress > 0) {
NftTypes[nftTypeId].PurchasesByAddress[_msgSender()] += 3;
}
NftTypes[nftTypeId].purchaseCount += 3;
}
function buy(uint256 nftTypeId, uint16 amount) external payable {
require(NftTypes[nftTypeId].saleActive, "SALE_CLOSED");
require(NftTypes[nftTypeId].price * amount == msg.value, "INCORRECT_ETH");
require(NftTypes[nftTypeId].maxMint > NftTypes[nftTypeId].purchaseCount + amount, "EXCEED_MAX_SALE_SUPPLY");
require(amount < NftTypes[nftTypeId].maxPerMint, "EXCEED_MAX_PER_MINT");
require(NftTypes[nftTypeId].maxPerAddress > 0 ||
NftTypes[nftTypeId].PurchasesByAddress[_msgSender()] + amount - 1 < NftTypes[nftTypeId].maxPerAddress, "EXCEED_MAX_PER_USER");
for (uint256 i = 0; i < amount; i++) {
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin();
}
NftTypes[nftTypeId].purchaseCount += amount;
}
// ** - PROXY - ** //
function mintOne(address receiver, uint256 nftTypeId) external onlyProxy {
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin2(receiver);
}
function mintThree(address receiver, uint256 nftTypeId) external onlyProxy {
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin2(receiver);
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin2(receiver);
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin2(receiver);
}
function mint(address receiver, uint256 nftTypeId, uint256 tokenQuantity) external onlyProxy {
for (uint256 i = 0; i < tokenQuantity; i++) {
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin2(receiver);
}
}
function getNftTokenIdForUserForNftType(address user, uint nftType) external view returns(uint) {
uint result;
uint bal = balanceOf(user);
for (uint x = 0; x < bal; x++) {
uint id = tokenOfOwnerByIndex(user, x);
if (NftIdToNftType[id] == nftType) {
return id;
}
}
return result;
}
function userHasNftType(address user, uint nftType) external view returns(bool) {
uint bal = balanceOf(user);
for (uint x = 0; x < bal; x++) {
uint id = tokenOfOwnerByIndex(user, x);
if (NftIdToNftType[id] == nftType) return true;
}
return false;
}
// ** - ADMIN - ** //
function addFeeRecipient(address recipient, uint256 basisPoints) external onlyOwner {
feeRecipientCount++;
FeeRecipients[feeRecipientCount].recipient = recipient;
FeeRecipients[feeRecipientCount].basisPoints = basisPoints;
totalFeeBasisPoints += basisPoints;
}
function editFeeRecipient(uint256 id, address recipient, uint256 basisPoints) external onlyOwner {
require(id <= feeRecipientCount, "INVALID_ID");
totalFeeBasisPoints = totalFeeBasisPoints - FeeRecipients[feeRecipientCount].basisPoints + basisPoints;
FeeRecipients[feeRecipientCount].recipient = recipient;
FeeRecipients[feeRecipientCount].basisPoints = basisPoints;
}
function distributeETH() public {
require(treasuryAddress != address(0), "TREASURY_NOT_SET");
uint256 bal = address(this).balance;
for(uint256 x = 1; x <= feeRecipientCount; x++) {
uint256 amount = bal * FeeRecipients[x].basisPoints / totalFeeBasisPoints;
amount = amount > address(this).balance ? address(this).balance : amount;
(bool sent, ) = FeeRecipients[x].recipient.call{value: amount}("");
require(sent, "FAILED_SENDING_FUNDS");
}
emit DistributeETH(_msgSender(), bal);
}
function withdrawETH() public {
require(treasuryAddress != address(0), "TREASURY_NOT_SET");
uint256 bal = address(this).balance;
(bool sent, ) = treasuryAddress.call{value: bal}("");
require(sent, "FAILED_SENDING_FUNDS");
emit WithdrawETH(_msgSender(), bal);
}
function withdraw(address _token) external nonReentrant {
require(_msgSender() == owner() || _msgSender() == treasuryAddress, "NOT_ALLOWED");
require(treasuryAddress != address(0), "TREASURY_NOT_SET");
IERC20(_token).safeTransfer(
treasuryAddress,
IERC20(_token).balanceOf(address(this))
);
}
function gift(uint256 nftTypeId, address[] calldata receivers, uint256[] memory amounts) external onlyOwner {
for (uint256 x = 0; x < receivers.length; x++) {
for (uint256 i = 0; i < amounts[x]; i++) {
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin2(receivers[x]);
}
}
}
// ** - NFT Types - ** //
function addNftType(uint16 _maxMint, uint16 _maxPerMint, uint256 _price,
uint16 _maxPerAddress, bool _saleActive, string calldata _uri) external onlyOwner
{
nftTypeCount++;
NftTypes[nftTypeCount].maxMint = _maxMint+1;
NftTypes[nftTypeCount].maxMintForOne = _maxMint;
NftTypes[nftTypeCount].maxMintForThree = _maxMint-2;
NftTypes[nftTypeCount].maxPerMint = _maxPerMint;
NftTypes[nftTypeCount].price = _price;
NftTypes[nftTypeCount].priceForThree = _price * 3;
NftTypes[nftTypeCount].maxPerAddress = _maxPerAddress > 0 ? _maxPerAddress : NftTypes[nftTypeCount].maxPerAddress;
NftTypes[nftTypeCount].maxPerAddressForThree = _maxPerAddress > 1 ? _maxPerAddress - 2 : NftTypes[nftTypeCount].maxPerAddress;
NftTypes[nftTypeCount].saleActive = _saleActive;
NftTypes[nftTypeCount].uri = _uri;
}
function toggleSaleActive(uint256 nftTypeId) external onlyOwner {
NftTypes[nftTypeId].saleActive = !NftTypes[nftTypeId].saleActive;
}
function setMaxPerMint(uint256 nftTypeId, uint16 maxPerMint) external onlyOwner {
NftTypes[nftTypeId].maxPerMint = maxPerMint;
}
function setMaxMint(uint256 nftTypeId, uint16 maxMint_) external onlyOwner {
NftTypes[nftTypeId].maxMint = maxMint_ + 1;
NftTypes[nftTypeId].maxMintForOne = maxMint_;
NftTypes[nftTypeId].maxMintForThree = maxMint_ - 2;
}
function setMaxPerAddress(uint256 nftTypeId, uint16 _maxPerAddress) external onlyOwner {
NftTypes[nftTypeId].maxPerAddress = _maxPerAddress > 0 ? _maxPerAddress : 0;
NftTypes[nftTypeId].maxPerAddressForThree = _maxPerAddress > 1 ? _maxPerAddress - 2 : NftTypes[nftTypeCount].maxPerAddress;
}
function setPrice(uint256 nftTypeId, uint256 _price) external onlyOwner {
NftTypes[nftTypeId].price = _price;
NftTypes[nftTypeId].priceForThree = _price * 3;
}
function setNftTypeUri(uint256 nftTypeId, string calldata uri) external onlyOwner {
NftTypes[nftTypeId].uri = uri;
}
// to avoid opensea listing costs
function isApprovedForAll(address _owner, address operator) public view override returns (bool) {
OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyRegistryAddress);
if (
address(proxyRegistry.proxies(_owner)) == operator ||
proxyToApproved[operator]
) return true;
return super.isApprovedForAll(_owner, operator);
}
function flipProxyState(address proxyAddress) public onlyOwner {
proxyToApproved[proxyAddress] = !proxyToApproved[proxyAddress];
}
// ** - SETTERS - ** //
function setVaultAddress(address addr) external onlyOwner {
treasuryAddress = addr;
}
function setContractURI(string calldata URI) external onlyOwner {
_contractURI = URI;
}
function setBaseURI(string calldata URI) external onlyOwner {
_tokenBaseURI = URI;
}
// ** - MISC - ** //
function contractURI() public view returns (string memory) {
return _contractURI;
}
function toggleUseBaseUri() external onlyOwner {
useBaseUriOnly = !useBaseUriOnly;
}
function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if (bytes(TokenURIMap[tokenId]).length > 0) return TokenURIMap[tokenId];
if (bytes(NftTypes[NftIdToNftType[tokenId]].uri).length > 0) return NftTypes[NftIdToNftType[tokenId]].uri;
if (useBaseUriOnly) return _tokenBaseURI;
return bytes(_tokenBaseURI).length > 0
? string(abi.encodePacked(_tokenBaseURI, tokenId.toString()))
: "";
}
function setTokenUri(uint256 tokenId, string calldata uri) external onlyOwner {
TokenURIMap[tokenId] = uri;
}
function isOwnerOf(address account, uint256[] calldata _tokenIds) external view returns (bool) {
for (uint256 i; i < _tokenIds.length; ++i) {
if (_owners[_tokenIds[i]] != account) return false;
}
return true;
}
function setTransferDisabled(bool _transferDisabled) external onlyOwner {
transferDisabled = _transferDisabled;
}
function setStakingContract(address stakingContract) external onlyOwner {
_setStakingContract(stakingContract);
}
function unStake(uint256 tokenId) external onlyOwner {
_unstake(tokenId);
}
function batchSafeTransferFrom(address _from, address _to, uint256[] memory _tokenIds, bytes memory data_) public override {
require(!transferDisabled || _msgSender() == owner() || proxyToApproved[_msgSender()], "TRANSFER_DISABLED");
super.batchSafeTransferFrom(_from, _to, _tokenIds, data_);
}
function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds) public override {
require(!transferDisabled || _msgSender() == owner() || proxyToApproved[_msgSender()], "TRANSFER_DISABLED");
super.batchTransferFrom(_from, _to, _tokenIds);
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override {
require(!transferDisabled || _msgSender() == owner() || proxyToApproved[_msgSender()], "TRANSFER_DISABLED");
super.safeTransferFrom(from, to, tokenId, _data);
}
function transferFrom(address from, address to, uint256 tokenId) public override {
require(!transferDisabled || _msgSender() == owner() || proxyToApproved[_msgSender()], "TRANSFER_DISABLED");
super.transferFrom(from, to, tokenId);
}
modifier onlyProxy() {
require(proxyToApproved[_msgSender()] == true, "onlyProxy");
_;
}
event DistributeETH(address indexed sender, uint256 indexed balance);
event WithdrawETH(address indexed sender, uint256 indexed balance);
}
// 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 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Address.sol";
abstract contract ERC721Min is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
address[] internal _owners;
// 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"
);
uint256 count = 0;
uint256 length = _owners.length;
for (uint256 i = 0; i < length; ++i) {
if (owner == _owners[i]) {
++count;
}
}
delete length;
return count;
}
function getOwnerCount() external view returns(uint256) {
return _owners.length;
}
/**
* @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 {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Min.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);
}
function batchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIds
) public virtual {
for (uint256 i = 0; i < _tokenIds.length; i++) {
transferFrom(_from, _to, _tokenIds[i]);
}
}
function batchSafeTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIds,
bytes memory data_
) public virtual {
for (uint256 i = 0; i < _tokenIds.length; i++) {
safeTransferFrom(_from, _to, _tokenIds[i], 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 tokenId < _owners.length && _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 = ERC721Min.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), "MINT_TO_ZERO");
require(!_exists(tokenId), "TOKEN_MINTED");
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
function _mintMin() internal virtual {
_owners.push(_msgSender());
emit Transfer(address(0), _msgSender(), _owners.length - 1);
}
// check to != address(0) in calling function
function _mintMin2(address to) internal virtual {
_owners.push(to);
emit Transfer(address(0), to, _owners.length - 1);
}
/**
* @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 = ERC721Min.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_owners[tokenId] = address(0);
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(
ERC721Min.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);
_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(ERC721Min.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
mapping(uint256 => bool) _isStaked;
address internal stakingContract;
function _setStakingContract(address _stakingContract) internal virtual {
stakingContract = _stakingContract;
}
modifier onlyStakingContract() {
require(
_msgSender() == stakingContract,
"ONLY_STAKING_CONTRACT"
);
_;
}
function isStaked(uint256 tokenId) external view returns(bool) {
return _isStaked[tokenId];
}
function stake(address user, uint256 tokenId) external onlyStakingContract {
require(ownerOf(tokenId) == user, "NOT_OWNER");
require(!_isStaked[tokenId], "ALREADY_STAKED");
_isStaked[tokenId] = !_isStaked[tokenId];
}
/* should only be called by contract owner */
function _unstake(uint256 tokenId) internal virtual {
_isStaked[tokenId] = false;
}
function unstake(address user, uint256 tokenId) external onlyStakingContract {
require(ownerOf(tokenId) == user, "NOT_OWNER");
_isStaked[tokenId] = false;
}
function tokenOfOwnerByIndex(address account, uint256 index) public view returns (uint256) {
uint256 foundCount;
for (uint256 i; i < _owners.length; ++i) {
if (_owners[i] == account) {
if (foundCount == index) return i;
foundCount++;
}
}
require(foundCount > 0, "NONE_FOUND");
revert("OUT_OF_INDEX");
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (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);
} | 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 = ERC721Min.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
| 451,974 |
pragma solidity ^0.6.0;
contract initializable5 { //inject NONSTANDARD NAMING
bool private initialized;
bool private initializing;
modifier INITIALIZER65() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
}
function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING
}
function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA22() 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;
}
uint256[50] private __gap;
}
contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING
address private _owner;
event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
__OWNABLE_INIT_UNCHAINED84();
}
function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER78();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED52(address(0), msgSender);
}
function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER81() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED52(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED52(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
library safemath14 { //inject NONSTANDARD NAMING
function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB60(a, b, "SafeMath: subtraction overflow");
}
function SUB60(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 MUL16(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 DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV54(a, b, "SafeMath: division by zero");
}
function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD56(a, b, "SafeMath: modulo by zero");
}
function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
interface ierc2086 { //inject NONSTANDARD NAMING
function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library console87 { //inject NONSTANDARD NAMING
address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address36;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG40() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log()"));
}
function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOG40(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
interface iuniswapv2factory11 { //inject NONSTANDARD NAMING
event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO47() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO7(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING
}
contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING
using safemath14 for uint256;
function INITIALIZE58( //inject NONSTANDARD NAMING
address _NANOCOREAddress,
address _WETHAddress,
address _uniswapFactory
) public INITIALIZER65 {
ownableupgradesafe25.__OWNABLE_INIT13();
nanocoreTokenAddress = _NANOCOREAddress;
WETHAddress = _WETHAddress;
tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress);
feePercentX100 = 15;
paused = false; // We start paused until sync post LGE happens.
}
address tokenUniswapPair;
iuniswapv2factory11 public uniswapFactory;
address internal WETHAddress;
address nanocoreTokenAddress;
address nanocoreVaultAddress;
uint8 public feePercentX100; // max 255 = 25.5% artificial clamp
uint256 public lastTotalSupplyOfLPTokens;
bool paused;
// Pausing transfers of the token
function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING
paused = _pause;
}
function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING
feePercentX100 = _feeMultiplier;
}
function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING
nanocoreVaultAddress = _nanocoreVaultAddress;
}
function SYNC99() public { //inject NONSTANDARD NAMING
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING
address sender,
address recipient, // unusued maybe use din future
uint256 amount
) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount)
{
require(paused == false, "FEE APPROVER: Transfers Paused");
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
// console.log("sender is " , sender);
// console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair);
// console.log("Old LP supply", lastTotalSupplyOfLPTokens);
// console.log("Current LP supply", _LPSupplyOfPairTotal);
if(sender == tokenUniswapPair)
require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden");
// console.log('Sender is pair' , sender == tokenUniswapPair);
// console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal);
if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop
console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it)
transferToFeeDistributorAmount = 0;
transferToAmount = amount;
}
else {
console87.LOG40("Normal fee transfer");
transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000);
transferToAmount = amount.SUB60(transferToFeeDistributorAmount);
}
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
} | inject NONSTANDARD NAMING | function LOG40(uint p0, address p1, bool p2) internal view { | 1,018,910 |
// https://t.me/MiniMillionTokenHolders
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.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);
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address lpPair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address lpPair);
function allPairs(uint) external view returns (address lpPair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address lpPair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event 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;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
pragma solidity ^0.8.0;
/**
* @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);
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.8.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, IERC20Metadata, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _liquidityHolders;
mapping (address => bool) private _isBlacklisted;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint256 private startingSupply = 500_000;
uint256 private _total = startingSupply * 10**18;
// UNI ROUTER
address private _routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public burnAddress = 0x000000000000000000000000000000000000dEaD;
IUniswapV2Router02 public dexRouter;
address private lpPair;
// Max TX amount is 1% of the total supply.
uint256 private maxTxPercent = 1; // Less fields to edit
uint256 private maxTxDivisor = 100;
uint256 private _maxTxAmount = (_total * maxTxPercent) / maxTxDivisor;
uint256 private _previousMaxTxAmount = _maxTxAmount;
uint256 public maxTxAmountUI = (startingSupply * maxTxPercent) / maxTxDivisor; // Actual amount for UI's
// Maximum wallet size is 2% of the total supply.
uint256 private maxWalletPercent = 2; // Less fields to edit
uint256 private maxWalletDivisor = 100;
uint256 private _maxWalletSize = (_total * maxWalletPercent) / maxWalletDivisor;
uint256 private _previousMaxWalletSize = _maxWalletSize;
uint256 public maxWalletSizeUI = (startingSupply * maxWalletPercent) / maxWalletDivisor; // Actual amount for UI's
bool private sniperProtection = true;
bool public _hasLiqBeenAdded = false;
uint256 private _liqAddBlock = 0;
uint256 private _liqAddStamp = 0;
uint256 public snipeBlockAmt;
uint256 public snipersCaught = 0;
event SniperCaught(address sniperAddress);
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_, uint256 initialSupply, address owner, uint256 _snipeBlockAmt) {
_name = name_;
_symbol = symbol_;
_liquidityHolders[msg.sender] = true;
snipeBlockAmt = _snipeBlockAmt;
IUniswapV2Router02 _dexRouter = IUniswapV2Router02(_routerAddress);
lpPair = IUniswapV2Factory(_dexRouter.factory())
.createPair(address(this), _dexRouter.WETH());
_totalSupply += initialSupply;
_balances[owner] += initialSupply;
emit Transfer(address(0), owner, initialSupply);
}
/**
* @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");
_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");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function _hasLimits(address from, address to) private view returns (bool) {
return !_liquidityHolders[to]
&& !_liquidityHolders[from]
&& to != burnAddress
&& to != address(0);
}
function _checkLiquidityAdd(address from, address to) private {
require(!_hasLiqBeenAdded, "Liquidity already added and marked.");
if (!_hasLimits(from, to) && to == lpPair) {
_hasLiqBeenAdded = true;
_liqAddBlock = block.number;
}
}
/**
* @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");
if(_hasLimits(sender, recipient))
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_hasLimits(sender, recipient)
&& recipient != _routerAddress
&& recipient != lpPair
) {
uint256 contractBalanceRecepient = balanceOf(recipient);
require(contractBalanceRecepient + amount <= _maxWalletSize, "Transfer amount exceeds the maxWalletSize.");
}
_beforeTokenTransfer(sender, recipient);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/**
* @dev 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));
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function isBlacklisted(address account) public view returns (bool) {
return _isBlacklisted[account];
}
function setBlacklist(address account, bool enabled) external onlyOwner() {
require(_isBlacklisted[account] != enabled);
_isBlacklisted[account] = enabled;
}
function setSniperProtectionEnabled(bool enabled) external onlyOwner() {
require(enabled != sniperProtection, "Already set.");
sniperProtection = enabled;
}
/**
* @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 sender, address recipient) internal virtual {
// Failsafe, disable the whole system if needed.
if (sniperProtection){
// If sender is a sniper address, reject the transfer.
if (isBlacklisted(sender) || isBlacklisted(recipient)) {
revert("Sniper rejected.");
}
// Check if this is the liquidity adding tx to startup.
if (!_hasLiqBeenAdded) {
_checkLiquidityAdd(sender, recipient);
if (!_hasLiqBeenAdded && _hasLimits(sender, recipient)) {
revert("Only owner can transfer at this time.");
}
} else {
if (_liqAddBlock > 0
&& sender == lpPair
&& _hasLimits(sender, recipient)
) {
if (block.number - _liqAddBlock < snipeBlockAmt) {
_isBlacklisted[recipient] = true;
snipersCaught ++;
emit SniperCaught(recipient);
}
}
}
}
}
function setMaxTxPercent(uint256 percent, uint256 divisor) external onlyOwner() {
require(divisor <= 10000); // Cannot set lower than 0.01%
_maxTxAmount = _total.mul(percent).div(
divisor // Division by divisor, makes it mutable.
);
maxTxAmountUI = startingSupply.mul(percent).div(divisor);
}
function setMaxWalletSize(uint256 percent, uint256 divisor) external onlyOwner() {
require(divisor <= 1000); // Cannot set lower than 0.1%
_maxWalletSize = _total.mul(percent).div(
divisor // Division by divisor, makes it mutable.
);
maxWalletSizeUI = startingSupply.mul(percent).div(divisor);
}
}
// File: @openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol
pragma solidity ^0.8.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
}
// File: @openzeppelin/contracts/token/ERC20/presets/ERC20PresetFixedSupply.sol
pragma solidity ^0.8.0;
/**
* @dev {ERC20} token, including:
*
* - Preminted initial supply
* - Ability for holders to burn (destroy) their tokens
* - No access control mechanism (for minting/pausing) and hence no governance
*
* This contract uses {ERC20Burnable} to include burn capabilities - head to
* its documentation for details.
*
* _Available since v3.4._
*/
contract ERC20PresetFixedSupply is ERC20Burnable {
/**
* @dev Mints `initialSupply` amount of token and transfers them to `owner`.
*
* See {ERC20-constructor}.
*/
constructor(
string memory name,
string memory symbol,
uint256 initialSupply,
address owner,
uint256 snipeBlockAmt
) ERC20(name, symbol, initialSupply, owner, snipeBlockAmt) {}
}
// File: contracts/million.sol
// Million token
pragma solidity ^0.8.0;
contract MMM is ERC20PresetFixedSupply {
string private _name = "Mini Million";
string private _symbol = "MMM";
uint256 private initialSupply = 500_000;
uint256 private _decMul = 18;
uint256 _tTotal = initialSupply * 10 ** _decMul;
constructor() ERC20PresetFixedSupply(_name, _symbol, _tTotal, msg.sender, 2) {
}
} | 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.adocusing-hooks[Using Hooks]./ Failsafe, disable the whole system if needed. If sender is a sniper address, reject the transfer. Check if this is the liquidity adding tx to startup. | function _beforeTokenTransfer(address sender, address recipient) internal virtual {
if (sniperProtection){
if (isBlacklisted(sender) || isBlacklisted(recipient)) {
revert("Sniper rejected.");
}
if (!_hasLiqBeenAdded) {
_checkLiquidityAdd(sender, recipient);
if (!_hasLiqBeenAdded && _hasLimits(sender, recipient)) {
revert("Only owner can transfer at this time.");
}
if (_liqAddBlock > 0
&& sender == lpPair
&& _hasLimits(sender, recipient)
) {
if (block.number - _liqAddBlock < snipeBlockAmt) {
_isBlacklisted[recipient] = true;
snipersCaught ++;
emit SniperCaught(recipient);
}
}
}
}
}
| 48,728 |
pragma solidity ^0.4.23;
import "./DateTime.sol";
import "./GuesserStorage.sol";
import "./libraries/SafeMath.sol";
/**
* @title GuesserCore
* @dev GuessCore contract to vote and create events in the Guesser platform.
*/
contract GuesserCore is DateTime {
using SafeMath for uint; // Using the safe math library
GuesserStorage guesserStorage;
/**
* @dev constructor. Sets the guesserStorage address for the
* Eternal Storage Pattern
*/
constructor (address _guesserStorageAddress) public {
guesserStorage = GuesserStorage(_guesserStorageAddress);
}
/* @dev Function to get the actual state of a event
* @param _index uint256 the 'page' of the events you want. The first 10, the second 10th, the third...
* @param _address address the person from whom you want the events
* @return bytes32 state of the event
*/
function getEventItemState (uint256 _index) public view returns (bytes32) {
bytes32 _state;
uint256 _votes = guesserStorage.getGuessOptionVotes(_index, 1) +
guesserStorage.getGuessOptionVotes(_index, 2);
uint256 _validations = guesserStorage.getGuessOptionValidation(_index, 1) +
guesserStorage.getGuessOptionValidation(_index, 2);
uint256 _half = (_votes/2) + 1;
if (!DateTime.dateDue(guesserStorage.getGuessFinalDate(_index)))
_state = "voting";
else if (DateTime.dateDue(guesserStorage.getGuessFinalDate(_index)) &&
!DateTime.dateDue(guesserStorage.getGuessValidationDate(_index)) &&
_votes != 0)
_state = "waiting";
else if(DateTime.dateDue(guesserStorage.getGuessValidationDate(_index)) &&
_validations < _half && _votes != 0)
_state = "validating";
else
_state = "passed";
return _state;
}
function percent(uint numerator, uint denominator, uint precision) public pure returns(uint quotient) {
// TODO: caution, check safe-to-multiply here
uint _numerator = numerator * 10 ** (precision+1);
// with rounding of last digit
uint _quotient = ((_numerator / denominator) + 5) / 10;
return ( _quotient);
}
/**
* @dev Returns the length of the guesses array.
* @return A uint256 with the actual length of the array of guesses
*/
function getGuessesLength() public view returns (uint256){
return guesserStorage.getGuessLength();
}
/* @dev Function that tells you the profits a Guess has
* @dev Get the profits a guess has in its vault
* @param _guess uint256 the event to ask for the profits of
* @return bool the profits the guess asked has
*/
function getGuessProfits (uint256 _guess) public view returns (uint128) {
// Does the guess exists?
require(_guess < guesserStorage.getGuessLength());
if (guesserStorage.getGuessVotersLength(_guess) == 0) {
return 0;
}
uint128 _profits = 0;
for(uint256 _voterIndex = 0; _voterIndex < guesserStorage.getGuessVotersLength(_guess); _voterIndex++) {
// Adding to profits the amount of eth
address _voter = guesserStorage.getGuessVoter(_guess, _voterIndex);
_profits += guesserStorage.getGuessVotersOption(_guess, _voter, 1) +
guesserStorage.getGuessVotersOption(_guess, _voter, 2);
}
return _profits;
}
/* @dev Function that tells you the profits of an option in a guess
* @dev Get the profits a guess has in its vault
* @param _guess uint256 the event to ask for the profits of
* @param _option uint256 the option you want to check
* @return bool the profits the guess asked has
*/
function getGuessProfitsByOption (uint256 _guess, uint8 _option) public view returns (uint128) {
// Does the guess exists?
require(_guess <= guesserStorage.getGuessLength() - 1);
// Is the option valid?
require(_option == 1 || _option == 2);
if (guesserStorage.getGuessVotersLength(_guess) == 0) {
return 0;
}
uint128 _profits = 0;
address _address;
for(uint256 _voterIndex = 0; _voterIndex < guesserStorage.getGuessVotersLength(_guess); _voterIndex++) {
// Option has to be the correct or 3, which means the user voted both options
_address = guesserStorage.getGuessVoter(_guess, _voterIndex);
if(guesserStorage.getGuessVotersOption(_guess, _address, 0) == _option ||
guesserStorage.getGuessVotersOption(_guess, _address, 0) == 3) {
_profits += guesserStorage.getGuessVotersOption(_guess, _address, _option);
}
}
return _profits;
}
function getGuessWinner (uint256 _guess) public view returns (uint8) {
// TODO: If there is a match, add one more validator
if (guesserStorage.getGuessOptionValidation(_guess, 1) > guesserStorage.getGuessOptionValidation(_guess, 2)) {
return 1; // The winner is the first one
} else {
return 2; // The winner is the second one
}
}
}
| Function to get the actual state of a event _index uint256 the 'page' of the events you want. The first 10, the second 10th, the third... _address address the person from whom you want the events return bytes32 state of the event/ | function getEventItemState (uint256 _index) public view returns (bytes32) {
bytes32 _state;
uint256 _votes = guesserStorage.getGuessOptionVotes(_index, 1) +
guesserStorage.getGuessOptionVotes(_index, 2);
uint256 _validations = guesserStorage.getGuessOptionValidation(_index, 1) +
guesserStorage.getGuessOptionValidation(_index, 2);
uint256 _half = (_votes/2) + 1;
if (!DateTime.dateDue(guesserStorage.getGuessFinalDate(_index)))
_state = "voting";
else if (DateTime.dateDue(guesserStorage.getGuessFinalDate(_index)) &&
!DateTime.dateDue(guesserStorage.getGuessValidationDate(_index)) &&
_votes != 0)
_state = "waiting";
else if(DateTime.dateDue(guesserStorage.getGuessValidationDate(_index)) &&
_validations < _half && _votes != 0)
_state = "validating";
else
_state = "passed";
return _state;
}
| 6,396,383 |
pragma solidity ^0.4.24;
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Contactable token
* @dev Basic version of a contactable contract, allowing the owner to provide a string with their
* contact information.
*/
contract Contactable is Ownable {
string public contactInformation;
/**
* @dev Allows the owner to set a string with their contact information.
* @param _info The contact information to attach to the contract.
*/
function setContactInformation(string _info) public onlyOwner {
contactInformation = _info;
}
}
contract IERC223Basic {
function balanceOf(address _owner) public constant returns (uint);
function transfer(address _to, uint _value) public;
function transfer(address _to, uint _value, bytes _data) public;
event Transfer(
address indexed from,
address indexed to,
uint value,
bytes data
);
}
contract IERC223 is IERC223Basic {
function allowance(address _owner, address _spender)
public view returns (uint);
function transferFrom(address _from, address _to, uint _value, bytes _data)
public;
function approve(address _spender, uint _value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
contract IERC223BasicReceiver {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract IERC223Receiver is IERC223BasicReceiver {
function receiveApproval(address _owner, uint _value) public;
}
/**
* @title Basic contract that will hold ERC223 tokens
*/
contract ERC223BasicReceiver is IERC223BasicReceiver {
event TokensReceived(address sender, address origin, uint value, bytes data);
/**
* @dev Standard ERC223 function that will handle incoming token transfers
* @param _from address the tokens owner
* @param _value uint the sent tokens amount
* @param _data bytes metadata
*/
function tokenFallback(address _from, uint _value, bytes _data) public {
require(_from != address(0));
emit TokensReceived(msg.sender, _from, _value, _data);
}
}
/**
* @title Contract that will hold ERC223 tokens
*/
contract ERC223Receiver is ERC223BasicReceiver, IERC223Receiver {
event ApprovalReceived(address sender, address owner, uint value);
/**
* @dev Function that will handle incoming token approvals
* @param _owner address the tokens owner
* @param _value uint the approved tokens amount
*/
function receiveApproval(address _owner, uint _value) public {
require(_owner != address(0));
emit ApprovalReceived(msg.sender, _owner, _value);
}
}
/**
* @title Contract that can hold and transfer ERC-223 tokens
*/
contract Fund is ERC223Receiver, Contactable {
IERC223 public token;
string public fundName;
/**
* @dev Constructor that sets the initial contract parameters
* @param _token ERC223 address of the ERC-223 token
* @param _fundName string the fund name
*/
constructor(IERC223 _token, string _fundName) public {
require(address(_token) != address(0));
token = _token;
fundName = _fundName;
}
/**
* @dev ERC-20 compatible function to transfer tokens
* @param _to address the tokens recepient
* @param _value uint amount of the tokens to be transferred
*/
function transfer(address _to, uint _value) public onlyOwner {
token.transfer(_to, _value);
}
/**
* @dev Function to transfer tokens
* @param _to address the tokens recepient
* @param _value uint amount of the tokens to be transferred
* @param _data bytes metadata
*/
function transfer(address _to, uint _value, bytes _data) public onlyOwner {
token.transfer(_to, _value, _data);
}
/**
* @dev Function to transfer tokens from the approved `msg.sender` account
* @param _from address the tokens owner
* @param _to address the tokens recepient
* @param _value uint amount of the tokens to be transferred
* @param _data bytes metadata
*/
function transferFrom(
address _from,
address _to,
uint _value,
bytes _data
)
public
onlyOwner
{
token.transferFrom(_from, _to, _value, _data);
}
/**
* @dev Function to approve account to spend owned tokens
* @param _spender address the tokens spender
* @param _value uint amount of the tokens to be approved
*/
function approve(address _spender, uint _value) public onlyOwner {
token.approve(_spender, _value);
}
}
/**
* @title HEdpAY
*/
contract Hedpay is IERC223, Contactable {
using AddressUtils for address;
using SafeMath for uint;
string public constant name = "HEdpAY";
string public constant symbol = "Hdp.ф";
uint8 public constant decimals = 4;
uint8 public constant secondPhaseBonus = 33;
uint8[3] public thirdPhaseBonus = [10, 15, 20];
uint public constant totalSupply = 10000000000000;
uint public constant secondPhaseStartTime = 1537401600; //20.09.2018
uint public constant secondPhaseEndTime = 1540943999; //30.10.2018
uint public constant thirdPhaseStartTime = 1540944000;//31.10.2018
uint public constant thirdPhaseEndTime = 1543622399;//30.11.2018
uint public constant cap = 200000 ether;
uint public constant goal = 25000 ether;
uint public constant rate = 100;
uint public constant minimumWeiAmount = 100 finney;
uint public constant salePercent = 14;
uint public constant bonusPercent = 1;
uint public constant teamPercent = 2;
uint public constant preSalePercent = 3;
uint public creationTime;
uint public weiRaised;
uint public tokensSold;
uint public buyersCount;
uint public saleAmount;
uint public bonusAmount;
uint public teamAmount;
uint public preSaleAmount;
uint public unsoldTokens;
address public teamAddress = 0x7d4E738477B6e8BaF03c4CB4944446dA690f76B5;
Fund public reservedFund;
mapping (address => uint) internal balances;
mapping (address => mapping (address => uint)) internal allowed;
mapping (address => uint) internal bonuses;
/**
* @dev Constructor that sets initial contract parameters
*/
constructor() public {
balances[owner] = totalSupply;
creationTime = block.timestamp;
saleAmount = totalSupply.div(100).mul(salePercent).mul(
10 ** uint(decimals)
);
bonusAmount = totalSupply.div(100).mul(bonusPercent).mul(
10 ** uint(decimals)
);
teamAmount = totalSupply.div(100).mul(teamPercent).mul(
10 ** uint(decimals)
);
preSaleAmount = totalSupply.div(100).mul(preSalePercent).mul(
10 ** uint(decimals)
);
}
/**
* @dev Gets an account tokens balance
* @param _owner address the tokens owner
* @return uint the specified address owned tokens amount
*/
function balanceOf(address _owner) public view returns (uint) {
require(_owner != address(0));
return balances[_owner];
}
/**
* @dev Gets the specified accounts approval value
* @param _owner address the tokens owner
* @param _spender address the tokens spender
* @return uint the specified accounts spending tokens amount
*/
function allowance(address _owner, address _spender)
public view returns (uint)
{
require(_owner != address(0));
require(_spender != address(0));
return allowed[_owner][_spender];
}
/**
* @dev Checks whether the ICO has started
* @return bool true if the crowdsale began
*/
function hasStarted() public view returns (bool) {
return block.timestamp >= secondPhaseStartTime;
}
/**
* @dev Checks whether the ICO has ended
* @return bool `true` if the crowdsale is over
*/
function hasEnded() public view returns (bool) {
return block.timestamp > thirdPhaseEndTime;
}
/**
* @dev Checks whether the cap has reached
* @return bool `true` if the cap has reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Gets the current tokens amount can be purchased for the specified
* @dev wei amount
* @param _weiAmount uint wei amount
* @return uint tokens amount
*/
function getTokenAmount(uint _weiAmount) public pure returns (uint) {
return _weiAmount.mul(rate).div((18 - uint(decimals)) ** 10);
}
/**
* @dev Gets the current tokens amount can be purchased for the specified
* @dev wei amount (including bonuses)
* @param _weiAmount uint wei amount
* @return uint tokens amount
*/
function getTokenAmountBonus(uint _weiAmount)
public view returns (uint)
{
if (hasStarted() && secondPhaseEndTime >= block.timestamp) {
return(
getTokenAmount(_weiAmount).
add(
getTokenAmount(_weiAmount).
div(100).
mul(uint(secondPhaseBonus))
)
);
} else if (thirdPhaseStartTime <= block.timestamp && !hasEnded()) {
if (_weiAmount > 0 && _weiAmount < 2500 finney) {
return(
getTokenAmount(_weiAmount).
add(
getTokenAmount(_weiAmount).
div(100).
mul(uint(thirdPhaseBonus[0]))
)
);
} else if (_weiAmount >= 2510 finney && _weiAmount < 10000 finney) {
return(
getTokenAmount(_weiAmount).
add(
getTokenAmount(_weiAmount).
div(100).
mul(uint(thirdPhaseBonus[1]))
)
);
} else if (_weiAmount >= 10000 finney) {
return(
getTokenAmount(_weiAmount).
add(
getTokenAmount(_weiAmount).
div(100).
mul(uint(thirdPhaseBonus[2]))
)
);
}
} else {
return getTokenAmount(_weiAmount);
}
}
/**
* @dev Gets an account tokens bonus
* @param _owner address the tokens owner
* @return uint owned tokens bonus
*/
function bonusOf(address _owner) public view returns (uint) {
require(_owner != address(0));
return bonuses[_owner];
}
/**
* @dev Gets an account tokens balance without freezed part of the bonuses
* @param _owner address the tokens owner
* @return uint owned tokens amount without freezed bonuses
*/
function balanceWithoutFreezedBonus(address _owner)
public view returns (uint)
{
require(_owner != address(0));
if (block.timestamp >= thirdPhaseEndTime.add(90 days)) {
if (bonusOf(_owner) < 10000) {
return balanceOf(_owner);
} else {
return balanceOf(_owner).sub(bonuses[_owner].div(2));
}
} else if (block.timestamp >= thirdPhaseEndTime.add(180 days)) {
return balanceOf(_owner);
} else {
return balanceOf(_owner).sub(bonuses[_owner]);
}
}
/**
* @dev ERC-20 compatible function to transfer tokens
* @param _to address the tokens recepient
* @param _value uint amount of the tokens to be transferred
*/
function transfer(address _to, uint _value) public {
transfer(_to, _value, "");
}
/**
* @dev Function to transfer tokens
* @param _to address the tokens recepient
* @param _value uint amount of the tokens to be transferred
* @param _data bytes metadata
*/
function transfer(address _to, uint _value, bytes _data) public {
require(_value <= balanceWithoutFreezedBonus(msg.sender));
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
_safeTransfer(msg.sender, _to, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
}
/**
* @dev Function to transfer tokens from the approved `msg.sender` account
* @param _from address the tokens owner
* @param _to address the tokens recepient
* @param _value uint amount of the tokens to be transferred
* @param _data bytes metadata
*/
function transferFrom(
address _from,
address _to,
uint _value,
bytes _data
)
public
{
require(_from != address(0));
require(_to != address(0));
require(_value <= allowance(_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);
_safeTransfer(_from, _to, _value, _data);
emit Transfer(_from, _to, _value, _data);
emit Approval(_from, msg.sender, allowance(_from, msg.sender));
}
/**
* @dev Function to approve account to spend owned tokens
* @param _spender address the tokens spender
* @param _value uint amount of the tokens to be approved
*/
function approve(address _spender, uint _value) public {
require(_spender != address(0));
require(_value <= balanceWithoutFreezedBonus(msg.sender));
allowed[msg.sender][_spender] = _value;
_safeApprove(_spender, _value);
emit Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to increase spending tokens amount
* @param _spender address the tokens spender
* @param _value uint increase tokens amount
*/
function increaseApproval(address _spender, uint _value) public {
require(_spender != address(0));
require(
allowance(msg.sender, _spender).add(_value) <=
balanceWithoutFreezedBonus(msg.sender)
);
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_value);
_safeApprove(_spender, allowance(msg.sender, _spender));
emit Approval(msg.sender, _spender, allowance(msg.sender, _spender));
}
/**
* @dev Function to decrease spending tokens amount
* @param _spender address the tokens spender
* @param _value uint decrease tokens amount
*/
function decreaseApproval(address _spender, uint _value) public {
require(_spender != address(0));
require(_value <= allowance(msg.sender, _spender));
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].sub(_value);
_safeApprove(_spender, allowance(msg.sender, _spender));
emit Approval(msg.sender, _spender, allowance(msg.sender, _spender));
}
/**
* @dev Function to set an account bonus
* @param _owner address the tokens owner
* @param _value uint bonus tokens amount
*/
function setBonus(address _owner, uint _value, bool preSale)
public onlyOwner
{
require(_owner != address(0));
require(_value <= balanceOf(_owner));
require(bonusAmount > 0);
require(_value <= bonusAmount);
bonuses[_owner] = _value;
if (preSale) {
preSaleAmount = preSaleAmount.sub(_value);
transfer(_owner, _value, abi.encode("transfer the bonus"));
} else {
if (_value <= bonusAmount) {
bonusAmount = bonusAmount.sub(_value);
transfer(_owner, _value, abi.encode("transfer the bonus"));
}
}
}
/**
* @dev Function to refill balance of the specified account
* @param _to address the tokens recepient
* @param _weiAmount uint amount of the tokens to be transferred
*/
function refill(address _to, uint _weiAmount) public onlyOwner {
require(_preValidateRefill(_to, _weiAmount));
setBonus(
_to,
getTokenAmountBonus(_weiAmount).sub(
getTokenAmount(_weiAmount)
),
false
);
buyersCount = buyersCount.add(1);
saleAmount = saleAmount.sub(getTokenAmount(_weiAmount));
transfer(_to, getTokenAmount(_weiAmount), abi.encode("refill"));
}
/**
* @dev Function to refill balances of the specified accounts
* @param _to address[] the tokens recepients
* @param _weiAmount uint[] amounts of the tokens to be transferred
*/
function refillArray(address[] _to, uint[] _weiAmount) public onlyOwner {
require(_to.length == _weiAmount.length);
for (uint i = 0; i < _to.length; i++) {
refill(_to[i], _weiAmount[i]);
}
}
/**
* @dev Function that transfers tokens to team address
*/
function setTeamFund() public onlyOwner{
transfer(
teamAddress,
teamAmount,
abi.encode("transfer reserved for team tokens to the team fund")
);
teamAmount = 0;
}
/**
* @dev Function to finalize the sale and define reservedFund
* @param _reservedFund fund that holds unsold tokens
*/
function finalize(Fund _reservedFund) public onlyOwner {
require(saleAmount > 0);
transfer(
address(_reservedFund),
saleAmount,
abi.encode("transfer reserved for team tokens to the team fund")
);
saleAmount = 0;
}
/**
* @dev Internal function to call the `tokenFallback` if the tokens
* @dev recepient is the smart-contract. If the contract doesn't implement
* @dev this function transaction fails
* @param _from address the tokens owner
* @param _to address the tokens recepient (perhaps the contract)
* @param _value uint amount of the tokens to be transferred
* @param _data bytes metadata
*/
function _safeTransfer(
address _from,
address _to,
uint _value,
bytes _data
)
internal
{
if (_to.isContract()) {
IERC223BasicReceiver receiver = IERC223BasicReceiver(_to);
receiver.tokenFallback(_from, _value, _data);
}
}
/**
* @dev Internal function to call the `receiveApproval` if the tokens
* @dev recepient is the smart-contract. If the contract doesn't implement
* @dev this function transaction fails
* @param _spender address the tokens recepient (perhaps the contract)
* @param _value uint amount of the tokens to be approved
*/
function _safeApprove(address _spender, uint _value) internal {
if (_spender.isContract()) {
IERC223Receiver receiver = IERC223Receiver(_spender);
receiver.receiveApproval(msg.sender, _value);
}
}
/**
* @dev Internal function to prevalidate refill before execution
* @param _to address the tokens recepient
* @param _weiAmount uint amount of the tokens to be transferred
* @return bool `true` if the refill can be executed
*/
function _preValidateRefill(address _to, uint _weiAmount)
internal view returns (bool)
{
return(
hasStarted() && _weiAmount > 0 && weiRaised.add(_weiAmount) <= cap
&& _to != address(0) && _weiAmount >= minimumWeiAmount &&
getTokenAmount(_weiAmount) <= saleAmount
);
}
} | Gets the current tokens amount can be purchased for the specified wei amount (including bonuses) _weiAmount uint wei amount return uint tokens amount/ | function getTokenAmountBonus(uint _weiAmount)
public view returns (uint)
{
if (hasStarted() && secondPhaseEndTime >= block.timestamp) {
return(
getTokenAmount(_weiAmount).
add(
getTokenAmount(_weiAmount).
div(100).
mul(uint(secondPhaseBonus))
)
);
if (_weiAmount > 0 && _weiAmount < 2500 finney) {
return(
getTokenAmount(_weiAmount).
add(
getTokenAmount(_weiAmount).
div(100).
mul(uint(thirdPhaseBonus[0]))
)
);
return(
getTokenAmount(_weiAmount).
add(
getTokenAmount(_weiAmount).
div(100).
mul(uint(thirdPhaseBonus[1]))
)
);
return(
getTokenAmount(_weiAmount).
add(
getTokenAmount(_weiAmount).
div(100).
mul(uint(thirdPhaseBonus[2]))
)
);
}
return getTokenAmount(_weiAmount);
}
}
| 435,410 |
pragma solidity ^0.6.6;
pragma experimental ABIEncoderV2;
import "../node_modules/@openzeppelin/contracts/access/Ownable.sol";
import "../node_modules/@openzeppelin/contracts/math/SafeMath.sol";
import "../node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../node_modules/@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../node_modules/@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./IStacker.sol";
contract Stacker is IStacker, Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
event AdapterAdded(address adapter, address gateway);
event AdapterRemoved(address adapter, address gateway);
event CallExecuted(
uint256 stackId,
address callAdapter,
string callSig,
bytes callArgs,
address[] incomingAssets,
uint256[] incomingAmounts,
address[] outgoingAssets,
uint256[] outgoingAmounts
);
event StackExecuted(
address indexed sender,
uint256 stackId,
address[] spendAssets,
uint256[] spendAssetBalances,
address[] callAdapters,
string[] callSigs,
bytes[] callArgs,
address[] paidOutAssets,
uint256[] paidOutAmounts
);
// CONSTANTS
address public constant override ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// STORAGE
uint256 public stackId;
mapping (address => address) public adapterToGateway;
EnumerableSet.AddressSet internal adapters;
EnumerableSet.AddressSet internal usedAssets;
// MODIFIERS
modifier onlyDelegated() {
require(msg.sender == address(this), "Sender must be this contract");
_;
}
// EXTERNAL FUNCTIONS
// Needed to receive ETH from adapters
receive() external payable {}
function addAdapter(address _adapter, address _gateway) external onlyOwner {
require(EnumerableSet.add(adapters, _adapter), "addAdapter: Adapter already added");
adapterToGateway[_adapter] = _gateway;
emit AdapterAdded(_adapter, _gateway);
}
/// @dev This is for flash loan hooks to run.
/// _spendAssets are the flash loaned assets.
/// Last call in the stack should be to pay back the flash loan.
function executeStackNoPayout(
address[] memory _spendAssets,
uint256[] memory _spendAssetBalances,
address[] memory _callAdapters,
string[] memory _callSigs,
bytes[] memory _callArgs
)
public // TODO: Getting stack error when `external`
override
payable
{
// Only adapter can make this call
require(
EnumerableSet.contains(adapters, msg.sender),
"executeStackNoPayout: Only an adapter can call this function"
);
__custodyAssets(_spendAssets, _spendAssetBalances);
__executeCalls(_callAdapters, _callSigs, _callArgs);
}
/// @dev All `call-` prefixed param arrays are the same length, and each index represents a call in the stack
function executeStack(
address[] memory _spendAssets,
uint256[] memory _spendAssetBalances,
address[] memory _callAdapters,
string[] memory _callSigs,
bytes[] memory _callArgs
)
public // TODO: Getting stack error when `external`
override
payable
{
__validateExecuteStackInputs(
_spendAssets,
_spendAssetBalances,
_callAdapters,
_callSigs,
_callArgs
);
__custodyAssets(_spendAssets, _spendAssetBalances);
__executeCalls(_callAdapters, _callSigs, _callArgs);
(
address[] memory paidOutAssets,
uint256[] memory paidOutAmounts
) = __payoutBalances();
emit StackExecuted(
msg.sender,
stackId,
_spendAssets,
_spendAssetBalances,
_callAdapters,
_callSigs,
_callArgs,
paidOutAssets,
paidOutAmounts
);
// Increment stackId
stackId++;
}
function removeAdapter(address _adapter) external onlyOwner {
address gateway = adapterToGateway[_adapter];
delete adapterToGateway[_adapter];
emit AdapterRemoved(_adapter, gateway);
}
// PRIVATE FUNCTIONS
function __custodyAssets(address[] memory _assets, uint256[] memory _amounts) private {
for (uint256 i = 0; i < _assets.length; i++) {
if (_assets[i] == ETH_ADDRESS) {
require(
payable(address(this)).balance >= _amounts[i],
"executeStack: Not enough ETH sent"
);
}
else {
IERC20(_assets[i]).safeTransferFrom(
msg.sender,
address(this),
_amounts[i]
);
}
EnumerableSet.add(usedAssets, _assets[i]);
}
}
function __executeCall(
address _callAdapter,
string memory _callSig,
bytes memory _callArgs
)
private
{
// Record balances prior to call
uint256[] memory preBalances = __preProcessCall();
// Make the call
(
bool success,
bytes memory returnData
) = _callAdapter.delegatecall(
abi.encodeWithSignature(_callSig, adapterToGateway[_callAdapter], _callArgs)
);
require(success, string(returnData));
address[] memory receivedAssets = abi.decode(returnData, (address[]));
// Post-process call to get incoming/outgoing assets
(
address[] memory incomingAssets,
uint256[] memory incomingAmounts,
address[] memory outgoingAssets,
uint256[] memory outgoingAmounts
) = __postProcessCall(preBalances, receivedAssets);
emit CallExecuted(
stackId,
_callAdapter,
_callSig,
_callArgs,
incomingAssets,
incomingAmounts,
outgoingAssets,
outgoingAmounts
);
}
function __executeCalls(
address[] memory _callAdapters,
string[] memory _callSigs,
bytes[] memory _callArgs
)
private
{
for (uint256 i = 0; i < _callAdapters.length; i++) {
__executeCall(_callAdapters[i], _callSigs[i], _callArgs[i]);
}
}
function __payoutBalances()
private
returns (address[] memory paidOutAssets_, uint256[] memory paidOutAmounts_)
{
uint256 assetsCount = EnumerableSet.length(usedAssets);
address[] memory assets = new address[](assetsCount);
uint256[] memory balances = new uint256[](assetsCount);
// Calc assets to pay and store assets and balances in memory
uint256 assetsToPayCount;
for (uint256 i = 0; i < assetsCount; i++) {
address asset = EnumerableSet.at(usedAssets, i);
assets[i] = asset;
uint256 balance;
if (asset == ETH_ADDRESS) {
balance = payable(address(this)).balance;
}
else {
balance = IERC20(asset).balanceOf(address(this));
}
if (balance > 0) {
balances[i] = balance;
assetsToPayCount++;
}
}
paidOutAssets_ = new address[](assetsToPayCount);
paidOutAmounts_ = new uint256[](assetsToPayCount);
// Pay out assets
uint256 paidAssetsCount;
for (uint256 i = 0; i < assetsCount; i++) {
address asset = assets[i];
uint256 balance = balances[i];
EnumerableSet.remove(usedAssets, asset);
if (balance == 0) continue;
if (asset == ETH_ADDRESS) {
(bool success,) = msg.sender.call{value: balance}("");
require(success, "__payoutBalances: Eth transfer to sender failed");
}
else {
IERC20(asset).safeTransfer(msg.sender, balance);
}
// Add to return values
paidOutAssets_[paidAssetsCount] = asset;
paidOutAmounts_[paidAssetsCount] = balance;
paidAssetsCount++;
}
assert(EnumerableSet.length(usedAssets) == 0);
}
function __preProcessCall() private view returns (uint256[] memory preBalances_) {
preBalances_ = new uint256[](EnumerableSet.length(usedAssets));
for (uint256 i = 0; i < preBalances_.length; i++) {
address asset = EnumerableSet.at(usedAssets, i);
if (asset == ETH_ADDRESS) {
preBalances_[i] = payable(address(this)).balance;
}
else {
preBalances_[i] = IERC20(asset).balanceOf(address(this));
}
}
}
function __postProcessCall(
uint256[] memory preBalances,
address[] memory receivedAssets
)
private
returns (
address[] memory incomingAssets_,
uint256[] memory incomingAmounts_,
address[] memory outgoingAssets_,
uint256[] memory outgoingAmounts_
)
{
// Get balance diffs of old assets
uint256[] memory balanceDiffs = new uint256[](preBalances.length);
bool[] memory areOutgoingAssets = new bool[](preBalances.length);
uint256 outgoingAssetsCount;
uint256 incomingAssetsCount;
for (uint256 i = 0; i < preBalances.length; i++) {
address asset = EnumerableSet.at(usedAssets, i);
uint256 balance;
if (asset == ETH_ADDRESS) {
balance = payable(address(this)).balance;
}
else {
balance = IERC20(asset).balanceOf(address(this));
}
if (balance > preBalances[i]) {
balanceDiffs[i] = balance.sub(preBalances[i]);
incomingAssetsCount++;
}
else if (balance < preBalances[i]) {
balanceDiffs[i] = preBalances[i].sub(balance);
outgoingAssetsCount++;
areOutgoingAssets[i] = true;
}
}
// Add received assets to incoming/outgoing asset counts
uint256 newAssetsCount;
for (uint256 i = 0; i < receivedAssets.length; i++) {
if (!EnumerableSet.contains(usedAssets, receivedAssets[i])) {
newAssetsCount++;
}
}
// Construct incoming/outgoing asset arrays
incomingAssets_ = new address[](incomingAssetsCount.add(newAssetsCount));
incomingAmounts_ = new uint256[](incomingAssetsCount.add(newAssetsCount));
outgoingAssets_ = new address[](outgoingAssetsCount);
outgoingAmounts_ = new uint256[](outgoingAssetsCount);
for (uint256 i = 0; i < preBalances.length; i++) {
if (balanceDiffs[i] == 0) continue;
if (areOutgoingAssets[i]) {
outgoingAssets_[i] = EnumerableSet.at(usedAssets, i);
outgoingAmounts_[i] = balanceDiffs[i];
}
else {
incomingAssets_[i] = EnumerableSet.at(usedAssets, i);
incomingAmounts_[i] = balanceDiffs[i];
}
}
// Update usedAssets with assets received in call, and add to incoming/outgoing assets
uint256 receivedAssetsAddedCount;
for (uint256 i = 0; i < receivedAssets.length; i++) {
uint256 index = incomingAssetsCount.add(receivedAssetsAddedCount);
address asset = receivedAssets[i];
uint256 balance;
if (asset == ETH_ADDRESS) {
balance = payable(address(this)).balance;
}
else {
balance = IERC20(asset).balanceOf(address(this));
}
incomingAssets_[index] = asset;
incomingAmounts_[index] = balance;
receivedAssetsAddedCount++;
EnumerableSet.add(usedAssets, asset);
}
}
function __validateExecuteStackInputs(
address[] memory _spendAssets,
uint256[] memory _spendAssetBalances,
address[] memory _callAdapters,
string[] memory _callSigs,
bytes[] memory _callArgs
)
private
pure
{
require(
_callAdapters.length == _callSigs.length,
"__validateExecuteStackInputs: _callAdapters and _callSigs unequal lengths"
);
require(
_callAdapters.length == _callArgs.length,
"__validateExecuteStackInputs: _callAdapters and _callArgs unequal lengths"
);
require(
_spendAssets.length == _spendAssetBalances.length,
"__validateExecuteStackInputs: _spendAssets and _spendAssetBalances unequal lengths"
);
}
}
| All `call-` prefixed param arrays are the same length, and each index represents a call in the stack Increment stackId | function executeStack(
address[] memory _spendAssets,
uint256[] memory _spendAssetBalances,
address[] memory _callAdapters,
string[] memory _callSigs,
bytes[] memory _callArgs
)
override
payable
{
__validateExecuteStackInputs(
_spendAssets,
_spendAssetBalances,
_callAdapters,
_callSigs,
_callArgs
);
__custodyAssets(_spendAssets, _spendAssetBalances);
__executeCalls(_callAdapters, _callSigs, _callArgs);
(
address[] memory paidOutAssets,
uint256[] memory paidOutAmounts
) = __payoutBalances();
emit StackExecuted(
msg.sender,
stackId,
_spendAssets,
_spendAssetBalances,
_callAdapters,
_callSigs,
_callArgs,
paidOutAssets,
paidOutAmounts
);
stackId++;
}
| 12,807,975 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/LinkTokenInterface.sol";
import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constructor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 private constant USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) {
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface internal immutable LINK;
address private immutable vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 => uint256) /* keyHash */ /* nonce */
private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(address _vrfCoordinator, address _link) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness. It ensures 2 things:
* @dev 1. The fulfillment came from the VRFCoordinator
* @dev 2. The consumer contract implements fulfillRandomWords.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constructor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash). Create subscription, fund it
* @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
* @dev subscription management functions).
* @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
* @dev callbackGasLimit, numWords),
* @dev see (VRFCoordinatorInterface for a description of the arguments).
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomWords method.
*
* @dev The randomness argument to fulfillRandomWords is a set of random words
* @dev generated from your requestId and the blockHash of the request.
*
* @dev If your contract could have concurrent requests open, you can use the
* @dev requestId returned from requestRandomWords to track which response is associated
* @dev with which randomness request.
* @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ.
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request. It is for this reason that
* @dev that you can signal to an oracle you'd like them to wait longer before
* @dev responding to the request (however this is not enforced in the contract
* @dev and so remains effective only in the case of unmodified oracle software).
*/
abstract contract VRFConsumerBaseV2 {
error OnlyCoordinatorCanFulfill(address have, address want);
address private immutable vrfCoordinator;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
*/
constructor(address _vrfCoordinator) {
vrfCoordinator = _vrfCoordinator;
}
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomWords the VRF output expanded to the requested number of words
*/
function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal virtual;
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external {
if (msg.sender != vrfCoordinator) {
revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator);
}
fulfillRandomWords(requestId, randomWords);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface VRFCoordinatorV2Interface {
/**
* @notice Get configuration relevant for making requests
* @return minimumRequestConfirmations global min for request confirmations
* @return maxGasLimit global max for request gas limit
* @return s_provingKeyHashes list of registered key hashes
*/
function getRequestConfig()
external
view
returns (
uint16,
uint32,
bytes32[] memory
);
/**
* @notice Request a set of random words.
* @param keyHash - Corresponds to a particular oracle job which uses
* that key for generating the VRF proof. Different keyHash's have different gas price
* ceilings, so you can select a specific one to bound your maximum per request cost.
* @param subId - The ID of the VRF subscription. Must be funded
* with the minimum subscription balance required for the selected keyHash.
* @param minimumRequestConfirmations - How many blocks you'd like the
* oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
* for why you may want to request more. The acceptable range is
* [minimumRequestBlockConfirmations, 200].
* @param callbackGasLimit - How much gas you'd like to receive in your
* fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
* may be slightly less than this amount because of gas used calling the function
* (argument decoding etc.), so you may need to request slightly more than you expect
* to have inside fulfillRandomWords. The acceptable range is
* [0, maxGasLimit]
* @param numWords - The number of uint256 random values you'd like to receive
* in your fulfillRandomWords callback. Note these numbers are expanded in a
* secure way by the VRFCoordinator from a single random value supplied by the oracle.
* @return requestId - A unique identifier of the request. Can be used to match
* a request to a response in fulfillRandomWords.
*/
function requestRandomWords(
bytes32 keyHash,
uint64 subId,
uint16 minimumRequestConfirmations,
uint32 callbackGasLimit,
uint32 numWords
) external returns (uint256 requestId);
/**
* @notice Create a VRF subscription.
* @return subId - A unique subscription id.
* @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
* @dev Note to fund the subscription, use transferAndCall. For example
* @dev LINKTOKEN.transferAndCall(
* @dev address(COORDINATOR),
* @dev amount,
* @dev abi.encode(subId));
*/
function createSubscription() external returns (uint64 subId);
/**
* @notice Get a VRF subscription.
* @param subId - ID of the subscription
* @return balance - LINK balance of the subscription in juels.
* @return reqCount - number of requests for this subscription, determines fee tier.
* @return owner - owner of the subscription.
* @return consumers - list of consumer address which are able to use this subscription.
*/
function getSubscription(uint64 subId)
external
view
returns (
uint96 balance,
uint64 reqCount,
address owner,
address[] memory consumers
);
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @param newOwner - proposed new owner of the subscription
*/
function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external;
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @dev will revert if original owner of subId has
* not requested that msg.sender become the new owner.
*/
function acceptSubscriptionOwnerTransfer(uint64 subId) external;
/**
* @notice Add a consumer to a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - New consumer which can use the subscription
*/
function addConsumer(uint64 subId, address consumer) external;
/**
* @notice Remove a consumer from a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - Consumer to remove from the subscription
*/
function removeConsumer(uint64 subId, address consumer) external;
/**
* @notice Cancel a subscription
* @param subId - ID of the subscription
* @param to - Where to send the remaining LINK to
*/
function cancelSubscription(uint64 subId, address to) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// 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 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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
/**
__ __ _ _ _ _____ ____
| \/ | | | (_) | | | __ \ /\ / __ \
| \ / | ___ __| | _ ___ __ __ __ _ | | | | | | / \ | | | |
| |\/| | / _ \ / _` | | | / _ \ \ \ / / / _` | | | | | | | / /\ \ | | | |
| | | | | __/ | (_| | | | | __/ \ V / | (_| | | | | |__| | / ____ \ | |__| |
|_| |_| \___| \__,_| |_| \___| \_/ \__,_| |_| |_____/ /_/ \_\ \____/
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
import "./erc721psi/ERC721PsiRandomSeedRevealBurnableUpgradeable.sol";
import "./access/MedievalAccessControlled.sol";
import "./opensea/IProxyRegistry.sol";
import "./interface/IMedievalNFT.sol";
import "./Traits.sol";
contract MedievalNFT is Initializable, MedievalAccessControlled, IMedievalNFT, ERC721PsiRandomSeedRevealBurnableUpgradeable {
bytes32 private constant NFT_MINTER_ROLE = keccak256("NFT_MINTER_ROLE");
using Traits for uint256;
// Chainlink
bytes32 immutable public keyHash;
uint64 immutable public subscriptionId;
uint256 public levelCap;
mapping(uint256 => string) public tokenName; //reserved
mapping(uint256 => uint256) _tokenLevel;
struct OccupationCDF {
uint32 reserved;
uint16 occupation1;
uint16 occupation1CDF;
uint16 occupation2;
uint16 occupation2CDF;
uint16 occupation3;
uint16 occupation3CDF;
}
mapping(uint256 => OccupationCDF) public genOccupationCDF;
function initialize(
address _controlCenter
) initializer virtual public {
__ERC721Psi_init("Medieval Adventurer", "ADVENTURER");
_setControlCenter(_controlCenter, tx.origin);
levelCap = 5; //TODO
}
//TODO
function _baseURI() internal pure override returns (string memory) {
return "https://medieval-backend.herokuapp.com/api/metadata/";
}
function tokenLevel(uint256 tokenId) public view returns (uint256 level){
level = _tokenLevel[tokenId] + 1;
}
function tokenOccupation(uint256 tokenId) public view virtual returns (uint16 occupation) {
OccupationCDF memory cdf = genOccupationCDF[_tokenGen(tokenId)];
require(cdf.occupation1 != 0, "Uninitialized CDF");
uint16 _seed = uint16(seed(tokenId));
if(_seed <= cdf.occupation1CDF) {
occupation = cdf.occupation1;
} else if(_seed <= cdf.occupation2CDF) {
occupation = cdf.occupation2;
} else if(_seed <= cdf.occupation3CDF) {
occupation = cdf.occupation3;
} else {
revert();
}
}
/// @param to The address that would receive the NFT.
/// @param quantity Amount of token to be minted.
function mint(address to, uint256 quantity) external override onlyRole(NFT_MINTER_ROLE) {
_safeMint(to, quantity);
}
function setName(uint256 tokenId, string calldata name) public pure {
revert("Not implemented! Stay tuned!");
}
function strength(uint256 tokenId) public virtual view returns(uint256){
return seed(tokenId).strength(tokenLevel(tokenId));
}
function house(uint256 tokenId) public view returns(uint256){
return seed(tokenId).house();
}
function _burn(uint256 _tokenId) internal override {
delete _tokenLevel[_tokenId];
delete tokenName[_tokenId];
super._burn(_tokenId);
}
/// Burn the NFTs to upgrade a NFT;
/// @param upgradeTokenId ID of the NFT to be upgraded.
/// @param materialTokenIds IDs of the NFT used as the material. The NFTs in the list will be burned.
function upgradeLevel(uint256 upgradeTokenId, uint256[] calldata materialTokenIds) external {
require(ownerOf(upgradeTokenId) == msg.sender, "Not NFT Owener!");
// Burn the NFTs.
for(uint256 i=0; i < materialTokenIds.length; i++){
uint256 tokenIdToBurn = materialTokenIds[i];
require(tokenIdToBurn != upgradeTokenId);
require(ownerOf(tokenIdToBurn) == msg.sender, "Not NFT Owener!");
_burn(tokenIdToBurn);
}
_tokenLevel[upgradeTokenId] += materialTokenIds.length;
require(_tokenLevel[upgradeTokenId] < levelCap, "Exceed the level cap!");
}
function setLevelCap(uint256 _cap) external onlyAdmin {
levelCap = _cap;
}
function setRandomOccupation(
uint256 gen,
uint16 occupation1,
uint16 occupation1CDF,
uint16 occupation2,
uint16 occupation2CDF,
uint16 occupation3,
uint16 occupation3CDF
) external onlyAdmin {
OccupationCDF memory _occupationCDF;
_occupationCDF.occupation1 = occupation1;
_occupationCDF.occupation2 = occupation2;
_occupationCDF.occupation3 = occupation3;
_occupationCDF.occupation1CDF = occupation1CDF;
_occupationCDF.occupation2CDF = occupation2CDF;
_occupationCDF.occupation3CDF = occupation3CDF;
genOccupationCDF[gen] = _occupationCDF;
}
function generation(uint256 tokenId) view public returns (uint256) {
require(_exists(tokenId));
return _tokenGen(tokenId);
}
// Called by the governanace to reveal the seed of the NFT.
function reveal() external onlyAdmin {
_reveal();
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(
address _vrfV2Coordinator,
bytes32 keyHash_,
uint64 subscriptionId_
) ERC721PsiRandomSeedRevealUpgradeable(
_vrfV2Coordinator,
200000,
10
) initializer {
keyHash = keyHash_;
subscriptionId = subscriptionId_;
}
// For opensea management.
function owner() public view virtual returns (address) {
return controlCenter.addressBook(
keccak256("OPENSEA_OWNER_ID")
);
}
/**
@dev Override the function to provide the corrosponding keyHash for the Chainlink VRF V2.
see also: https://docs.chain.link/docs/vrf-contracts/
*/
function _keyHash() internal view override returns (bytes32) {
return keyHash;
}
/**
@dev Override the function to provide the corrosponding subscription id for the Chainlink VRF V2.
see also: https://docs.chain.link/docs/get-a-random-number/#create-and-fund-a-subscription
*/
function _subscriptionId() internal view override returns (uint64) {
return subscriptionId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Traits {
uint256 constant NUM_SAMPLING = 8;
uint256 constant SAMPLING_BITS = 8;
uint256 constant SAMPLING_MASK = (1 << SAMPLING_BITS) - 1;
function gaussianTrait(uint256 seed) internal pure returns(uint256 trait) {
unchecked{
for(uint256 i=0; i < NUM_SAMPLING; i++){
trait += (seed >> (i * SAMPLING_BITS)) & SAMPLING_MASK;
}
}
}
function strength(uint256 seed, uint256 level) internal pure returns(uint256) {
return level * gaussianTrait(seed);
}
function house(uint256 seed) internal pure returns(uint256) {
return uint256(keccak256(abi.encode(
seed,
keccak256("house")
)))% 4;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.7.0;
import "./interface/IMedievalAccessControlCenter.sol";
contract MedievalAccessControlled {
string constant ACCESS_DENIED_MSG = "Access Denied!";
bytes32 constant DEFAULT_ADMIN_ROLE = 0;
IMedievalAccessControlCenter public controlCenter;
// tempAdmin has all the priviledge, and it is only used when controlCenter is not set.
address public tempAdmin;
function _setControlCenter(address _controlCenter, address _tempAdmin) internal {
controlCenter = IMedievalAccessControlCenter(_controlCenter);
if(_controlCenter == address(0)){
tempAdmin =_tempAdmin;
} else {
tempAdmin = address(0);
// Prevent setting controlCenter to an invalid address.
require(
controlCenter.getRoleMemberCount(DEFAULT_ADMIN_ROLE) > 0,
"Invalid controlCenter address!"
);
}
}
function setControlCenter(address _controlCenter, address _tempAdmin) external onlyAdmin {
_setControlCenter(_controlCenter, _tempAdmin);
}
function _hasRole(bytes32 role, address account) internal view returns(bool){
return controlCenter.hasRole(role, account);
}
function _treasury() internal view returns(address){
return controlCenter.treasury();
}
function _dao() internal view returns(address){
return controlCenter.dao();
}
modifier onlyRole(bytes32 role) {
if(address(controlCenter) == address(0)) {
require(tempAdmin == msg.sender, ACCESS_DENIED_MSG);
} else {
require(_hasRole(role, msg.sender),
ACCESS_DENIED_MSG);
}
_;
}
modifier onlyAdmin() {
if(address(controlCenter) == address(0)) {
require(tempAdmin == msg.sender, ACCESS_DENIED_MSG);
} else {
require(_hasRole(0, msg.sender),
ACCESS_DENIED_MSG);
}
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.7.0;
interface IMedievalAccessControlCenter {
function addressBook ( bytes32 ) external view returns ( address );
function getRoleAdmin ( bytes32 role ) external view returns ( bytes32 );
function getRoleMember ( bytes32 role, uint256 index ) external view returns ( address );
function getRoleMemberCount ( bytes32 role ) external view returns ( uint256 );
function grantRole ( bytes32 role, address account ) external;
function hasRole ( bytes32 role, address account ) external view returns ( bool );
function renounceRole ( bytes32 role, address account ) external;
function revokeRole ( bytes32 role, address account ) external;
function setAddress ( bytes32 id, address _address ) external;
function setRoleAdmin ( bytes32 role, bytes32 adminRole ) external;
function treasury ( ) external view returns ( address );
function dao ( ) external view returns ( address );
}
// SPDX-License-Identifier: MIT
/**
______ _____ _____ ______ ___ __ _ _ _
| ____| __ \ / ____|____ |__ \/_ | || || |
| |__ | |__) | | / / ) || | \| |/ |
| __| | _ /| | / / / / | |\_ _/
| |____| | \ \| |____ / / / /_ | | | |
|______|_| \_\\_____|/_/ |____||_| |_|
*/
pragma solidity ^0.8.0;
import "./BitScan.sol";
import "hardhat/console.sol";
/**
* @dev This Library is a modified version of Openzeppelin's BitMaps library.
* Functions of finding the index of the closest set bit from a given index are added.
* The indexing of each bucket is modifed to count from the MSB to the LSB instead of from the LSB to the MSB.
* The modification of indexing makes finding the closest previous set bit more efficient in gas usage.
*/
/**
* @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential.
* Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
*/
library BitMaps {
using BitScan for uint256;
uint256 private constant MASK_INDEX_ZERO = (1 << 255);
struct BitMap {
mapping(uint256 => uint256) _data;
}
/**
* @dev Returns whether the bit at `index` is set.
*/
function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
uint256 bucket = index >> 8;
uint256 mask = MASK_INDEX_ZERO >> (index & 0xff);
return bitmap._data[bucket] & mask != 0;
}
/**
* @dev Sets the bit at `index` to the boolean `value`.
*/
function setTo(
BitMap storage bitmap,
uint256 index,
bool value
) internal {
if (value) {
set(bitmap, index);
} else {
unset(bitmap, index);
}
}
/**
* @dev Sets the bit at `index`.
*/
function set(BitMap storage bitmap, uint256 index) internal {
uint256 bucket = index >> 8;
uint256 mask = MASK_INDEX_ZERO >> (index & 0xff);
bitmap._data[bucket] |= mask;
}
/**
* @dev Unsets the bit at `index`.
*/
function unset(BitMap storage bitmap, uint256 index) internal {
uint256 bucket = index >> 8;
uint256 mask = MASK_INDEX_ZERO >> (index & 0xff);
bitmap._data[bucket] &= ~mask;
}
/**
* @dev Find the closest index of the set bit before `index`.
*/
function scanForward(BitMap storage bitmap, uint256 index) internal view returns (uint256) {
uint256 bucket = index >> 8;
uint256 bucketIndex = (index & 0xff);
uint256 offset = 0xff ^ bucketIndex;
uint256 bb = bitmap._data[bucket];
bb = bb >> offset;
if(bb > 0) {
unchecked {
return (bucket << 8) | (bucketIndex - bb.bitScanForward256());
}
} else {
require(bucket > 0, "BitMaps: The set bit before the index doesn't exist.");
unchecked {
bucket--;
bucketIndex = 255;
offset = 0;
}
while(true) {
bb = bitmap._data[bucket];
if(bb > 0) {
unchecked {
return (bucket << 8) | (bucketIndex - bb.bitScanForward256());
}
} else {
require(bucket > 0, "BitMaps: The set bit before the index doesn't exist.");
unchecked {
bucket--;
}
}
}
}
}
function getBucket(BitMap storage bitmap, uint256 bucket) internal view returns (uint256) {
return bitmap._data[bucket];
}
}
// SPDX-License-Identifier: MIT
/**
______ _____ _____ ______ ___ __ _ _ _
| ____| __ \ / ____|____ |__ \/_ | || || |
| |__ | |__) | | / / ) || | \| |/ |
| __| | _ /| | / / / / | |\_ _/
| |____| | \ \| |____ / / / /_ | | | |
|______|_| \_\\_____|/_/ |____||_| |_|
*/
pragma solidity ^0.8.0;
library BitScan {
uint256 constant private DEBRUIJN_256 = 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff;
bytes constant private LOOKUP_TABLE_256 = hex"0001020903110a19042112290b311a3905412245134d2a550c5d32651b6d3a7506264262237d468514804e8d2b95569d0d495ea533a966b11c886eb93bc176c9071727374353637324837e9b47af86c7155181ad4fd18ed32c9096db57d59ee30e2e4a6a5f92a6be3498aae067ddb2eb1d5989b56fd7baf33ca0c2ee77e5caf7ff0810182028303840444c545c646c7425617c847f8c949c48a4a8b087b8c0c816365272829aaec650acd0d28fdad4e22d6991bd97dfdcea58b4d6f29fede4f6fe0f1f2f3f4b5b6b607b8b93a3a7b7bf357199c5abcfd9e168bcdee9b3f1ecf5fd1e3e5a7a8aa2b670c4ced8bbe8f0f4fc3d79a1c3cde7effb78cce6facbf9f8";
function isolateLSB256(uint256 bb) pure internal returns (uint256) {
require(bb > 0);
unchecked {
return bb & (0 - bb);
}
}
function isolateMSB256(uint256 bb) pure internal returns (uint256) {
require(bb > 0);
unchecked {
bb |= bb >> 256;
bb |= bb >> 128;
bb |= bb >> 64;
bb |= bb >> 32;
bb |= bb >> 16;
bb |= bb >> 8;
bb |= bb >> 4;
bb |= bb >> 2;
bb |= bb >> 1;
return (bb >> 1) + 1;
}
}
function bitScanForward256(uint256 bb) pure internal returns (uint8) {
unchecked {
return uint8(LOOKUP_TABLE_256[(isolateLSB256(bb) * DEBRUIJN_256) >> 248]);
}
}
function bitScanReverse256(uint256 bb) pure internal returns (uint8) {
unchecked {
return 255 - uint8(LOOKUP_TABLE_256[((isolateMSB256(bb) * DEBRUIJN_256) >> 248)]);
}
}
}
// SPDX-License-Identifier: MIT
/**
______ _____ _____ ______ ___ __ _ _ _
| ____| __ \ / ____|____ |__ \/_ | || || |
| |__ | |__) | | / / ) || | \| |/ |
| __| | _ /| | / / / / | |\_ _/
| |____| | \ \| |____ / / / /_ | | | |
|______|_| \_\\_____|/_/ |____||_| |_|
*/
pragma solidity ^0.8.0;
import "./ERC721PsiUpgradeable.sol";
import "./BitMaps.sol";
abstract contract ERC721PsiBatchMetaDataUpgradeable is ERC721PsiUpgradeable {
using BitMaps for BitMaps.BitMap;
BitMaps.BitMap private _metaDataBatchHead;
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual override {
uint256 tokenIdBatchHead = _minted;
_metaDataBatchHead.set(tokenIdBatchHead);
super._safeMint(to, quantity, _data);
}
/**
* @dev Return the batch head tokenId where the on-chain metadata is stored during minting.
*
* The returned tokenId will remain the same after the token transfer.
*/
function _getMetaDataBatchHead(uint256 tokenId) internal view returns (uint256 tokenIdMetaDataBatchHead) {
tokenIdMetaDataBatchHead = _metaDataBatchHead.scanForward(tokenId);
}
}
// SPDX-License-Identifier: MIT
/**
______ _____ _____ ______ ___ __ _ _ _
| ____| __ \ / ____|____ |__ \/_ | || || |
| |__ | |__) | | / / ) || | \| |/ |
| __| | _ /| | / / / / | |\_ _/
| |____| | \ \| |____ / / / /_ | | | |
|______|_| \_\\_____|/_/ |____||_| |_|
*/
pragma solidity ^0.8.0;
import "./BitMaps.sol";
import "./ERC721PsiRandomSeedRevealUpgradeable.sol";
abstract contract ERC721PsiRandomSeedRevealBurnableUpgradeable is ERC721PsiRandomSeedRevealUpgradeable {
using BitMaps for BitMaps.BitMap;
BitMaps.BitMap private _burnedToken;
/**
* @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 from = ownerOf(tokenId);
_beforeTokenTransfers(from, address(0), tokenId, 1);
_burnedToken.set(tokenId);
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
}
/**
* @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 override virtual returns (bool){
if(_burnedToken.get(tokenId)) {
return false;
}
return super._exists(tokenId);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _minted - _burned();
}
/**
* @dev Returns number of token burned.
*/
function _burned() internal view returns (uint256 burned){
uint256 totalBucket = (_minted >> 8) + 1;
for(uint256 i=0; i < totalBucket; i++) {
uint256 bucket = _burnedToken.getBucket(i);
burned += _popcount(bucket);
}
}
/**
* @dev Returns number of set bits.
*/
function _popcount(uint256 x) private pure returns (uint256 count) {
unchecked{
for (count=0; x!=0; count++)
x &= x - 1;
}
}
}
// SPDX-License-Identifier: MIT
/**
______ _____ _____ ______ ___ __ _ _ _
| ____| __ \ / ____|____ |__ \/_ | || || |
| |__ | |__) | | / / ) || | \| |/ |
| __| | _ /| | / / / / | |\_ _/
| |____| | \ \| |____ / / / /_ | | | |
|______|_| \_\\_____|/_/ |____||_| |_|
*/
pragma solidity ^0.8.0;
import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
import "./interface/IERC721RandomSeed.sol";
import "./BitMaps.sol";
import "./ERC721PsiBatchMetaDataUpgradeable.sol";
abstract contract ERC721PsiRandomSeedRevealUpgradeable is IERC721RandomSeed, ERC721PsiBatchMetaDataUpgradeable, VRFConsumerBaseV2 {
// Chainklink VRF V2
VRFCoordinatorV2Interface immutable COORDINATOR;
uint32 immutable callbackGasLimit;
uint16 immutable requestConfirmations;
uint16 constant numWords = 1;
// requestId => genId
mapping(uint256 => uint256) private requestIdToGenId;
// genId => seed
mapping(uint256 => uint256) private genSeed;
// batchHeadTokenId => genId
mapping(uint256 => uint256) private _batchHeadtokenGen;
// current genId for minting
uint256 private currentGen;
event RandomnessRequest(uint256 requestId);
constructor(
address coordinator,
uint32 _callbackGasLimit,
uint16 _requestConfirmations
) VRFConsumerBaseV2(coordinator) {
COORDINATOR = VRFCoordinatorV2Interface(coordinator);
callbackGasLimit = _callbackGasLimit;
requestConfirmations = _requestConfirmations;
}
/**
* Callback function used by VRF Coordinator
*/
function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override {
uint256 randomness = randomWords[0];
uint256 genId = requestIdToGenId[requestId];
delete requestIdToGenId[genId];
genSeed[genId] = randomness;
_processRandomnessFulfillment(requestId, genId, randomness);
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual override {
uint256 tokenIdHead = _minted;
_batchHeadtokenGen[tokenIdHead] = currentGen;
super._safeMint(to, quantity, _data);
}
/**
@dev Query the generation of `tokenId`.
*/
function _tokenGen(uint256 tokenId) internal view returns (uint256) {
require(_exists(tokenId), "ERC721PsiRandomSeedReveal: generation query for nonexistent token");
return _batchHeadtokenGen[_getMetaDataBatchHead(tokenId)];
}
/**
@dev Request the randomess for the tokens of the current generation.
*/
function _reveal() internal virtual {
uint256 requestId = COORDINATOR.requestRandomWords(
_keyHash(),
_subscriptionId(),
requestConfirmations,
callbackGasLimit,
numWords
);
emit RandomnessRequest(requestId);
requestIdToGenId[requestId] = currentGen;
_processRandomnessRequest(requestId, currentGen);
currentGen++;
}
/**
@dev Return the random seed of `tokenId`.
Revert when the randomness hasn't been fulfilled.
*/
function seed(uint256 tokenId) public virtual override view returns (uint256){
require(_exists(tokenId), "ERC721PsiRandomSeedReveal: seed query for nonexistent token");
unchecked {
uint256 _genSeed = genSeed[_tokenGen(tokenId)];
require(_genSeed != 0, "ERC721PsiRandomSeedReveal: Randomness hasn't been fullfilled");
return uint256(keccak256(
abi.encode(_genSeed, tokenId)
));
}
}
/**
@dev Override the function to provide the corrosponding keyHash for the Chainlink VRF V2.
see also: https://docs.chain.link/docs/vrf-contracts/
*/
function _keyHash() internal virtual returns (bytes32);
/**
@dev Override the function to provide the corrosponding subscription id for the Chainlink VRF V2.
see also: https://docs.chain.link/docs/get-a-random-number/#create-and-fund-a-subscription
*/
function _subscriptionId() internal virtual returns (uint64);
function _processRandomnessRequest(uint256 requestId, uint256 genId) internal {
}
function _processRandomnessFulfillment(uint256 requestId, uint256 genId, uint256 randomness) internal {
}
}
// SPDX-License-Identifier: MIT
/**
______ _____ _____ ______ ___ __ _ _ _
| ____| __ \ / ____|____ |__ \/_ | || || |
| |__ | |__) | | / / ) || | \| |/ |
| __| | _ /| | / / / / | |\_ _/
| |____| | \ \| |____ / / / /_ | | | |
|______|_| \_\\_____|/_/ |____||_| |_|
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./BitMaps.sol";
contract ERC721PsiUpgradeable is Initializable, ContextUpgradeable,
ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
using BitMaps for BitMaps.BitMap;
BitMaps.BitMap private _batchHead;
string private _name;
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) internal _owners;
uint256 internal _minted;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721Psi_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC721Psi_init_unchained(name_, symbol_);
}
function __ERC721Psi_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
interfaceId == type(IERC721EnumerableUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint)
{
require(owner != address(0), "ERC721Psi: balance query for the zero address");
uint count;
for( uint i; i < _minted; ++i ){
if(_exists(i)){
if( owner == ownerOf(i)){
++count;
}
}
}
return count;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
(address owner, uint256 tokenIdBatchHead) = _ownerAndBatchHeadOf(tokenId);
return owner;
}
function _ownerAndBatchHeadOf(uint256 tokenId) internal view returns (address owner, uint256 tokenIdBatchHead){
require(_exists(tokenId), "ERC721Psi: owner query for nonexistent token");
tokenIdBatchHead = _getBatchHead(tokenId);
owner = _owners[tokenIdBatchHead];
}
/**
* @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), "ERC721Psi: 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 = ownerOf(tokenId);
require(to != owner, "ERC721Psi: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721Psi: 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),
"ERC721Psi: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721Psi: 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),
"ERC721Psi: 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),
"ERC721Psi: 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),
"ERC721Psi: 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 virtual returns (bool) {
return tokenId < _minted;
}
/**
* @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),
"ERC721Psi: operator query for nonexistent token"
);
address owner = ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 quantity) internal virtual {
_safeMint(to, quantity, "");
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
uint256 tokenIdBatchHead = _minted;
require(quantity > 0, "ERC721Psi: quantity must be greater 0");
require(to != address(0), "ERC721Psi: mint to the zero address");
_beforeTokenTransfers(address(0), to, tokenIdBatchHead, quantity);
for(uint256 i=0;i < quantity; i++){
uint256 tokenId = tokenIdBatchHead + i;
emit Transfer(address(0), to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721Psi: transfer to non ERC721Receiver implementer"
);
}
_owners[tokenIdBatchHead] = to;
_batchHead.set(tokenIdBatchHead);
_minted += quantity;
_afterTokenTransfers(address(0), to, tokenIdBatchHead, quantity);
}
/**
* @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 {
(address owner, uint256 tokenIdBatchHead) = _ownerAndBatchHeadOf(tokenId);
require(
owner == from,
"ERC721Psi: transfer of token that is not own"
);
require(to != address(0), "ERC721Psi: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
uint256 nextTokenId = tokenId + 1;
if(!_batchHead.get(nextTokenId) &&
nextTokenId < _minted
) {
_owners[nextTokenId] = from;
_batchHead.set(nextTokenId);
}
_owners[tokenId] = to;
if(tokenId != tokenIdBatchHead) {
_batchHead.set(tokenId);
}
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) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721Psi: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function _getBatchHead(uint256 tokenId) internal view returns (uint256 tokenIdBatchHead) {
tokenIdBatchHead = _batchHead.scanForward(tokenId);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _minted;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < totalSupply(), "ERC721Psi: global index out of bounds");
uint count;
for(uint i; i < _minted; i++){
if(_exists(i)){
if(count == index) return i;
else count++;
}
}
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) {
uint count;
for(uint i; i < _minted; i++){
if(_exists(i) && owner == ownerOf(i)){
if(count == index) return i;
else count++;
}
}
revert("ERC721Psi: owner index out of bounds");
}
/**
* @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
pragma solidity ^0.8.0;
interface IERC721RandomSeed {
function seed(uint256 tokenId) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IMedievalNFT {
function mint(address to, uint256 quantity) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* Used to delegate ownership of a contract to another address, to save on unneeded transactions to approve contract use for users
*/
interface IProxyRegistry{
function proxies(address _account) external view returns(address);
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
} | to The address that would receive the NFT. quantity Amount of token to be minted. | function mint(address to, uint256 quantity) external override onlyRole(NFT_MINTER_ROLE) {
_safeMint(to, quantity);
}
| 10,072,655 |
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC.
//
// 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 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity 0.5.12;
contract DSPauseAbstract {
function SETOWNER297(address) external; //inject NONSTANDARD NAMING
function SETAUTHORITY462(address) external; //inject NONSTANDARD NAMING
function SETDELAY997(uint256) external; //inject NONSTANDARD NAMING
function PLANS194(bytes32) external view returns (bool); //inject NONSTANDARD NAMING
function PROXY33() external view returns (address); //inject NONSTANDARD NAMING
function DELAY572() external view returns (uint256); //inject NONSTANDARD NAMING
function PLOT308(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING
function DROP835(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING
function EXEC528(address, bytes32, bytes calldata, uint256) external returns (bytes memory); //inject NONSTANDARD NAMING
}
contract JugAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address) external; //inject NONSTANDARD NAMING
function DENY29(address) external; //inject NONSTANDARD NAMING
function ILKS89(bytes32) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function VAT322() external view returns (address); //inject NONSTANDARD NAMING
function VOW865() external view returns (address); //inject NONSTANDARD NAMING
function BASE98() external view returns (address); //inject NONSTANDARD NAMING
function INIT382(bytes32) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, address) external; //inject NONSTANDARD NAMING
function DRIP851(bytes32) external returns (uint256); //inject NONSTANDARD NAMING
}
contract VatAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address) external; //inject NONSTANDARD NAMING
function DENY29(address) external; //inject NONSTANDARD NAMING
function CAN701(address, address) external view returns (uint256); //inject NONSTANDARD NAMING
function HOPE401(address) external; //inject NONSTANDARD NAMING
function NOPE804(address) external; //inject NONSTANDARD NAMING
function ILKS89(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); //inject NONSTANDARD NAMING
function URNS72(bytes32, address) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function GEM847(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING
function DAI766(address) external view returns (uint256); //inject NONSTANDARD NAMING
function SIN979(address) external view returns (uint256); //inject NONSTANDARD NAMING
function DEBT96() external view returns (uint256); //inject NONSTANDARD NAMING
function VICE796() external view returns (uint256); //inject NONSTANDARD NAMING
function LINE365() external view returns (uint256); //inject NONSTANDARD NAMING
function LIVE39() external view returns (uint256); //inject NONSTANDARD NAMING
function INIT382(bytes32) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function CAGE573() external; //inject NONSTANDARD NAMING
function SLIP893(bytes32, address, int256) external; //inject NONSTANDARD NAMING
function FLUX455(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING
function MOVE486(address, address, uint256) external; //inject NONSTANDARD NAMING
function FROB749(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function FORK68(bytes32, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function GRAB867(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function HEAL281(uint256) external; //inject NONSTANDARD NAMING
function SUCK979(address, address, uint256) external; //inject NONSTANDARD NAMING
function FOLD739(bytes32, address, int256) external; //inject NONSTANDARD NAMING
}
contract VowAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address usr) external; //inject NONSTANDARD NAMING
function DENY29(address usr) external; //inject NONSTANDARD NAMING
function VAT322() external view returns (address); //inject NONSTANDARD NAMING
function FLAPPER608() external view returns (address); //inject NONSTANDARD NAMING
function FLOPPER190() external view returns (address); //inject NONSTANDARD NAMING
function SIN979(uint256) external view returns (uint256); //inject NONSTANDARD NAMING
function SIN979() external view returns (uint256); //inject NONSTANDARD NAMING
function ASH807() external view returns (uint256); //inject NONSTANDARD NAMING
function WAIT426() external view returns (uint256); //inject NONSTANDARD NAMING
function DUMP329() external view returns (uint256); //inject NONSTANDARD NAMING
function SUMP140() external view returns (uint256); //inject NONSTANDARD NAMING
function BUMP430() external view returns (uint256); //inject NONSTANDARD NAMING
function HUMP834() external view returns (uint256); //inject NONSTANDARD NAMING
function LIVE39() external view returns (uint256); //inject NONSTANDARD NAMING
function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, address) external; //inject NONSTANDARD NAMING
function FESS945(uint256) external; //inject NONSTANDARD NAMING
function FLOG837(uint256) external; //inject NONSTANDARD NAMING
function HEAL281(uint256) external; //inject NONSTANDARD NAMING
function KISS865(uint256) external; //inject NONSTANDARD NAMING
function FLOP497() external returns (uint256); //inject NONSTANDARD NAMING
function FLAP923() external returns (uint256); //inject NONSTANDARD NAMING
function CAGE573() external; //inject NONSTANDARD NAMING
}
contract IlkRegistryAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address) external; //inject NONSTANDARD NAMING
function DENY29(address) external; //inject NONSTANDARD NAMING
function VAT322() external view returns (address); //inject NONSTANDARD NAMING
function CAT738() external view returns (address); //inject NONSTANDARD NAMING
function SPOT274() external view returns (address); //inject NONSTANDARD NAMING
function ILKDATA365(bytes32) external view returns ( //inject NONSTANDARD NAMING
uint256,
address,
address,
address,
address,
uint256,
string memory,
string memory
);
function ILKS89() external view returns (bytes32[] memory); //inject NONSTANDARD NAMING
function ILKS89(uint) external view returns (bytes32); //inject NONSTANDARD NAMING
function ADD269(address) external; //inject NONSTANDARD NAMING
function REMOVE614(bytes32) external; //inject NONSTANDARD NAMING
function REMOVEAUTH234(bytes32) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, address) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, string calldata) external; //inject NONSTANDARD NAMING
function COUNT649() external view returns (uint256); //inject NONSTANDARD NAMING
function LIST141() external view returns (bytes32[] memory); //inject NONSTANDARD NAMING
function LIST141(uint256, uint256) external view returns (bytes32[] memory); //inject NONSTANDARD NAMING
function GET51(uint256) external view returns (bytes32); //inject NONSTANDARD NAMING
function INFO652(bytes32) external view returns ( //inject NONSTANDARD NAMING
string memory,
string memory,
uint256,
address,
address,
address,
address
);
function POS804(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function GEM847(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function PIP889(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function JOIN697(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function FLIP981(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function DEC837(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function SYMBOL988(bytes32) external view returns (string memory); //inject NONSTANDARD NAMING
function NAME950(bytes32) external view returns (string memory); //inject NONSTANDARD NAMING
}
contract SpellAction {
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/c8e9f709f4bc5d0384b47e0109eb7555f08b84fc/governance/votes/Executive%20vote%20-%20August%2014%2C%202020.md -q -O - 2>/dev/null)"
string constant public description524 = //inject NONSTANDARD NAMING
"2020-08-14 MakerDAO Weekly Executive Spell | Hash: 0x97294bc0de2100192a54a618351a84574e5d1998da234152e68b4065ac9bea0f";
// MAINNET ADDRESSES
//
// The contracts in this list should correspond to MCD core contracts, verify
// against the current release list at:
// https://changelog.makerdao.com/releases/mainnet/1.0.9/contracts.json
address constant mcd_vat35 = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; //inject NONSTANDARD NAMING
address constant mcd_jug497 = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; //inject NONSTANDARD NAMING
address constant mcd_vow892 = 0xA950524441892A31ebddF91d3cEEFa04Bf454466; //inject NONSTANDARD NAMING
address constant ilk_registry964 = 0xbE4F921cdFEf2cF5080F9Cf00CC2c14F1F96Bd07; //inject NONSTANDARD NAMING
uint256 constant million677 = 10 ** 6; //inject NONSTANDARD NAMING
uint256 constant rad54 = 10 ** 45; //inject NONSTANDARD NAMING
// Many of the settings that change weekly rely on the rate accumulator
// described at https://docs.makerdao.com/smart-contract-modules/rates-module
// To check this yourself, use the following rate calculation (example 6%):
//
// $ bc -l <<< 'scale=27; e( l(1.06)/(60 * 60 * 24 * 365) )'
//
uint256 constant six_pct_rate891 = 1000000001847694957439350562; //inject NONSTANDARD NAMING
uint256 constant fortyfour_pct_rate631 = 1000000011562757347033522598; //inject NONSTANDARD NAMING
function EXECUTE336() external { //inject NONSTANDARD NAMING
bytes32[] memory ilks = IlkRegistryAbstract(ilk_registry964).LIST141();
for(uint i = 0; i < ilks.length; i++) {
// Set all ilks dust value from 20 Dai to 100 Dai
VatAbstract(mcd_vat35).FILE935(ilks[i], "dust", 100 * rad54);
}
// Set the MANA-A stability fee
// value is determined by the rate accumulator calculation (see above)
// ex. an 8% annual rate will be 1000000002440418608258400030
//
// Existing Rate: 8%
// New Rate: 6%
JugAbstract(mcd_jug497).DRIP851("MANA-A");
JugAbstract(mcd_jug497).FILE935("MANA-A", "duty", six_pct_rate891);
// Set the USDC-B stability fee
// value is determined by the rate accumulator calculation (see above)
// ex. an 8% annual rate will be 1000000002440418608258400030
//
// Existing Rate: 46%
// New Rate: 44%
JugAbstract(mcd_jug497).DRIP851("USDC-B");
JugAbstract(mcd_jug497).FILE935("USDC-B", "duty", fortyfour_pct_rate631);
// Sets the system surplus buffer from 500k Dai to 2mm Dai
VowAbstract(mcd_vow892).FILE935("hump", 2 * million677 * rad54);
}
}
contract DssSpell {
DSPauseAbstract public pause =
DSPauseAbstract(0xbE286431454714F511008713973d3B053A2d38f3);
address public action;
bytes32 public tag;
uint256 public eta;
bytes public sig;
uint256 public expiration;
bool public done;
constructor() public {
sig = abi.encodeWithSignature("execute()");
action = address(new SpellAction());
bytes32 _tag;
address _action = action;
assembly { _tag := extcodehash(_action) }
tag = _tag;
expiration = now + 30 days;
}
function DESCRIPTION887() public view returns (string memory) { //inject NONSTANDARD NAMING
return SpellAction(action).description524();
}
function SCHEDULE900() public { //inject NONSTANDARD NAMING
require(now <= expiration, "This contract has expired");
require(eta == 0, "This spell has already been scheduled");
eta = now + DSPauseAbstract(pause).DELAY572();
pause.PLOT308(action, tag, sig, eta);
}
function CAST355() public { //inject NONSTANDARD NAMING
require(!done, "spell-already-cast");
done = true;
pause.EXEC528(action, tag, sig, eta);
}
} | inject NONSTANDARD NAMING | function PLOT308(address, bytes32, bytes calldata, uint256) external; | 12,918,527 |
//Address: 0x8b548505babfd983fc45210499b44e340bb85d76
//Contract name: Hedgely
//Balance: 0 Ether
//Verification Date: 2/3/2018
//Transacion Count: 944
// CODE STARTS HERE
pragma solidity ^0.4.19;
// Hedgely - The Ethereum Inverted Market
// [email protected]
// Contract based investment game
/**
* @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 Syndicate
* @dev Syndicated profit sharing - for early adopters
* Shares are not transferable -
*/
contract Syndicate is Ownable{
uint256 public totalSyndicateShares = 20000;
uint256 public availableEarlyPlayerShares = 5000;
uint256 public availableBuyInShares = 5000;
uint256 public minimumBuyIn = 10;
uint256 public buyInSharePrice = 500000000000000; // wei = 0.0005 ether
uint256 public shareCycleSessionSize = 1000; // number of sessions in a share cycle
uint256 public shareCycleIndex = 0; // current position in share cycle
uint256 public currentSyndicateValue = 0; // total value of syndicate to be divided among members
uint256 public numberSyndicateMembers = 0;
uint256 public syndicatePrecision = 1000000000000000;
struct member {
uint256 numShares;
uint256 profitShare;
}
address[] private syndicateMembers;
mapping(address => member ) private members;
event ProfitShare(
uint256 _currentSyndicateValue,
uint256 _numberSyndicateMembers,
uint256 _totalOwnedShares,
uint256 _profitPerShare
);
function Syndicate() public {
members[msg.sender].numShares = 10000; // owner portion
members[msg.sender].profitShare = 0;
numberSyndicateMembers = 1;
syndicateMembers.push(msg.sender);
}
// initiates a dividend of necessary, sends
function claimProfit() public {
if (members[msg.sender].numShares==0) revert(); // only syndicate members.
uint256 profitShare = members[msg.sender].profitShare;
if (profitShare>0){
members[msg.sender].profitShare = 0;
msg.sender.transfer(profitShare);
}
}
// distribute profit amonge syndicate members on a percentage share basis
function distributeProfit() internal {
uint256 totalOwnedShares = totalSyndicateShares-(availableEarlyPlayerShares+availableBuyInShares);
uint256 profitPerShare = SafeMath.div(currentSyndicateValue,totalOwnedShares);
// foreach member , calculate their profitshare
for(uint i = 0; i< numberSyndicateMembers; i++)
{
// do += so that acrues across share cycles.
members[syndicateMembers[i]].profitShare+=SafeMath.mul(members[syndicateMembers[i]].numShares,profitPerShare);
}
// emit a profit share event
ProfitShare(currentSyndicateValue, numberSyndicateMembers, totalOwnedShares , profitPerShare);
currentSyndicateValue=0; // all the profit has been divided up
shareCycleIndex = 0; // restart the share cycle count.
}
// allocate syndicate shares up to the limit.
function allocateEarlyPlayerShare() internal {
if (availableEarlyPlayerShares==0) return;
availableEarlyPlayerShares--;
addMember(); // possibly add this member to the syndicate
members[msg.sender].numShares+=1;
}
// add new member of syndicate
function addMember() internal {
if (members[msg.sender].numShares == 0){
syndicateMembers.push(msg.sender);
numberSyndicateMembers++;
}
}
// buy into syndicate
function buyIntoSyndicate() public payable {
if(msg.value==0 || availableBuyInShares==0) revert();
if(msg.value < minimumBuyIn*buyInSharePrice) revert();
uint256 value = (msg.value/syndicatePrecision)*syndicatePrecision; // ensure precision
uint256 allocation = value/buyInSharePrice;
if (allocation >= availableBuyInShares){
allocation = availableBuyInShares; // limit hit
}
availableBuyInShares-=allocation;
addMember(); // possibly add this member to the syndicate
members[msg.sender].numShares+=allocation;
}
// how many shares?
function memberShareCount() public view returns (uint256) {
return members[msg.sender].numShares;
}
// how much profit?
function memberProfitShare() public view returns (uint256) {
return members[msg.sender].profitShare;
}
}
/**
* Core Hedgely Contract
*/
contract Hedgely is Ownable, Syndicate {
// Array of players
address[] private players;
mapping(address => bool) private activePlayers;
uint256 numPlayers = 0;
// map each player address to their portfolio of investments
mapping(address => uint256 [10] ) private playerPortfolio;
uint256 public totalHedgelyWinnings;
uint256 public totalHedgelyInvested;
uint256[10] private marketOptions;
// The total amount of Ether bet for this current market
uint256 public totalInvested;
// The amount of Ether used to see the market
uint256 private seedInvestment;
// The total number of investments the users have made
uint256 public numberOfInvestments;
// The number that won the last game
uint256 public numberWinner;
// current session information
uint256 public startingBlock;
uint256 public endingBlock;
uint256 public sessionBlockSize;
uint256 public sessionNumber;
uint256 public currentLowest;
uint256 public currentLowestCount; // should count the number of currentLowest to prevent a tie
uint256 public precision = 1000000000000000; // rounding to this will keep it to 1 finney resolution
uint256 public minimumStake = 1 finney;
event Invest(
address _from,
uint256 _option,
uint256 _value,
uint256[10] _marketOptions,
uint _blockNumber
);
event EndSession(
uint256 _sessionNumber,
uint256 _winningOption,
uint256[10] _marketOptions,
uint256 _blockNumber
);
event StartSession(
uint256 _sessionNumber,
uint256 _sessionBlockSize,
uint256[10] _marketOptions,
uint256 _blockNumber
);
bool locked;
modifier noReentrancy() {
require(!locked);
locked = true;
_;
locked = false;
}
function Hedgely() public {
owner = msg.sender;
sessionBlockSize = 100;
sessionNumber = 0;
totalHedgelyWinnings = 0;
totalHedgelyInvested = 0;
numPlayers = 0;
resetMarket();
}
// the full amount invested in each option
function getMarketOptions() public constant returns (uint256[10])
{
return marketOptions;
}
// each player can get their own portfolio
function getPlayerPortfolio() public constant returns (uint256[10])
{
return playerPortfolio[msg.sender];
}
// the number of investors this session
function numberOfInvestors() public constant returns(uint count) {
return numPlayers;
}
// generate a random number between 1 and 20 to seed a symbol
function rand() internal returns (uint64) {
return random(19)+1;
}
// pseudo random - but does that matter?
uint64 _seed = 0;
function random(uint64 upper) private returns (uint64 randomNumber) {
_seed = uint64(keccak256(keccak256(block.blockhash(block.number), _seed), now));
return _seed % upper;
}
// resets the market conditions
function resetMarket() internal {
sessionNumber ++;
startingBlock = block.number;
endingBlock = startingBlock + sessionBlockSize; // approximately every 5 minutes - can play with this
numPlayers = 0;
// randomize the initial market values
uint256 sumInvested = 0;
for(uint i=0;i<10;i++)
{
uint256 num = rand();
marketOptions[i] =num * precision; // wei
sumInvested+= marketOptions[i];
}
playerPortfolio[this] = marketOptions;
totalInvested = sumInvested;
seedInvestment = sumInvested;
insertPlayer(this);
numPlayers=1;
numberOfInvestments = 10;
currentLowest = findCurrentLowest();
StartSession(sessionNumber, sessionBlockSize, marketOptions , startingBlock);
}
// utility to round to the game precision
function roundIt(uint256 amount) internal constant returns (uint256)
{
// round down to correct preicision
uint256 result = (amount/precision)*precision;
return result;
}
// main entry point for investors/players
function invest(uint256 optionNumber) public payable noReentrancy {
// Check that the number is within the range (uints are always>=0 anyway)
assert(optionNumber <= 9);
uint256 amount = roundIt(msg.value); // round to precision
assert(amount >= minimumStake);
uint256 holding = playerPortfolio[msg.sender][optionNumber];
holding = SafeMath.add(holding, amount);
playerPortfolio[msg.sender][optionNumber] = holding;
marketOptions[optionNumber] = SafeMath.add(marketOptions[optionNumber],amount);
numberOfInvestments += 1;
totalInvested += amount;
totalHedgelyInvested += amount;
if (!activePlayers[msg.sender]){
insertPlayer(msg.sender);
activePlayers[msg.sender]=true;
}
Invest(msg.sender, optionNumber, amount, marketOptions, block.number);
// possibly allocate syndicate shares
allocateEarlyPlayerShare(); // allocate a single share per investment for early adopters
currentLowest = findCurrentLowest();
if (block.number >= endingBlock && currentLowestCount==1) distributeWinnings();
} // end invest
// find lowest option sets currentLowestCount>1 if there are more than 1 lowest
function findCurrentLowest() internal returns (uint lowestOption) {
uint winner = 0;
uint lowestTotal = marketOptions[0];
currentLowestCount = 0;
for(uint i=0;i<10;i++)
{
if (marketOptions [i]<lowestTotal){
winner = i;
lowestTotal = marketOptions [i];
currentLowestCount = 0;
}
if (marketOptions [i]==lowestTotal){currentLowestCount+=1;}
}
return winner;
}
// distribute winnings at the end of a session
function distributeWinnings() internal {
if (currentLowestCount>1){
return; // cannot end session because there is no lowest.
}
numberWinner = currentLowest;
// record the end of session
EndSession(sessionNumber, numberWinner, marketOptions , block.number);
uint256 sessionWinnings = 0;
for(uint j=1;j<numPlayers;j++)
{
if (playerPortfolio[players[j]][numberWinner]>0){
uint256 winningAmount = playerPortfolio[players[j]][numberWinner];
uint256 winnings = SafeMath.mul(8,winningAmount); // eight times the invested amount.
totalHedgelyWinnings+=winnings;
sessionWinnings+=winnings;
players[j].transfer(winnings); // don't throw here
}
playerPortfolio[players[j]] = [0,0,0,0,0,0,0,0,0,0];
activePlayers[players[j]]=false;
}
uint256 playerInvestments = totalInvested-seedInvestment;
if (sessionWinnings>playerInvestments){
uint256 loss = sessionWinnings-playerInvestments; // this is a loss
if (currentSyndicateValue>=loss){
currentSyndicateValue-=loss;
}else{
currentSyndicateValue = 0;
}
}
if (playerInvestments>sessionWinnings){
currentSyndicateValue+=playerInvestments-sessionWinnings; // this is a gain
}
// check if share cycle is complete and if required distribute profits
shareCycleIndex+=1;
if (shareCycleIndex >= shareCycleSessionSize){
distributeProfit();
}
resetMarket();
} // end distribute winnings
// convenience to manage a growing array
function insertPlayer(address value) internal {
if(numPlayers == players.length) {
players.length += 1;
}
players[numPlayers++] = value;
}
// We might vary this at some point
function setsessionBlockSize (uint256 blockCount) public onlyOwner {
sessionBlockSize = blockCount;
}
// ----- admin functions in event of an issue --
function withdraw(uint256 amount) public onlyOwner {
require(amount<=this.balance);
if (amount==0){
amount=this.balance;
}
owner.transfer(amount);
}
// In the event of catastrophe
function kill() public onlyOwner {
if(msg.sender == owner)
selfdestruct(owner);
}
// donations, funding, replenish
function() public payable {}
}
/**
* @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;
}
}
| initiates a dividend of necessary, sends | function claimProfit() public {
uint256 profitShare = members[msg.sender].profitShare;
if (profitShare>0){
members[msg.sender].profitShare = 0;
msg.sender.transfer(profitShare);
}
}
| 7,240,714 |
./full_match/420666/0x11CaA255049904e194D11F7bb290CAC5aFcbace7/sources/libraries/PancakeLibrary.sol | given some amount of an asset and pair reserves, returns an equivalent amount of the other asset | function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "PancakeLibrary: INSUFFICIENT_AMOUNT");
require(reserveA > 0 && reserveB > 0, "PancakeLibrary: INSUFFICIENT_LIQUIDITY");
amountB = amountA.mul(reserveB) / reserveA;
}
| 16,368,905 |
./partial_match/1/0x08E1451D4f34cD67E9b4647bCcb251483EeeC6D7/sources/MultiSigStub.sol | Returns list of transaction IDs in defined range. from Index start position of transaction array. to Index end position of transaction array. pending Include pending transactions. executed Include executed transactions. return Returns array of transaction IDs. | function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i = 0; i < transactionCount; i++) {
if (pending && !transactions[i].executed || executed && transactions[i].executed) {
transactionIdsTemp[count] = i;
count += 1;
}
}
_transactionIds = new uint[](to - from);
for (i = from; i < to; i++) {
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
| 9,309,964 |
pragma solidity >=0.6.0 <0.9.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./DAO.sol";
contract Paper is ERC721, DAO {
using Counters for Counters.Counter;
Counters.Counter private paperId;
// mapping(uint256 => mapping(address => uint256)) paperSponsorAmounts;
constructor(string memory _tokenName, string memory _tokenSymbol)
ERC721(_tokenName, _tokenSymbol)
public {}
function submitDraft(
string memory _title,
string memory _tokenURI,
string[] memory _fields,
string[] memory _subFields,
uint256[] memory _references,
uint256 _validatorTip,
address payable[] memory _validatorAddresses
) public payable returns (uint256) {
require(msg.value == _validatorTip, "specified validatorTip not sent");
if (!isScholar[msg.sender]) {
isScholar[msg.sender] = true;
}
paperId.increment();
uint256 newPaperId = paperId.current();
address payable _owner = payable(msg.sender);
address payable _author = payable(msg.sender);
address payable _validator;
address payable[] memory _peerReviewers;
// mapping(address => uint256) storage sa = paperSponsorAmounts[
// newPaperId
// ];
PaperStruct memory paper = PaperStruct(
newPaperId,
_tokenURI,
_title,
_owner,
_author,
// _authors,
// _beneficiary,
_validator,
_peerReviewers,
_fields,
_subFields,
_references,
_validatorTip,
block.timestamp + 6 weeks, // default deadline
PublicationStage.Draft,
// sa,
0
);
_safeMint(_owner, newPaperId);
_setTokenURI(newPaperId, _tokenURI);
// // adds categories
// // since mappings already have values, every fields already has every subfields already. for example for subCategories['Computer'] every imaginable subfields mapping value already exists, we can push to it.
// bool CategoryExists = false;
// for (uint256 i = 0; i < fields.length; i++) {
// if (
// keccak256(abi.encodePacked((fields[i]))) ==
// keccak256(abi.encodePacked((_fields)))
// ) {
// CategoryExists = true;
// }
// }
// if (CategoryExists == false) {
// fields.push(_fields);
// }
// updates mapping
paperById[newPaperId] = paper;
scholarPapers[_author].push(newPaperId);
for (uint256 i = 0; i < _references.length; i++) {
citedBy[_references[i]].push(newPaperId);
citedByCount[_references[i]] += 1;
address pauthor = paperById[_references[i]].author;
uint256 maxhindex = scholarPapers[pauthor].length;
uint256 maxcit = 0;
for (uint256 j=0; j<scholarPapers[pauthor].length;j++){
maxcit = citedByCount[scholarPapers[pauthor][j]];
if (maxcit <= maxhindex) {
hIndex[pauthor] = maxhindex;
}
}
}
emit PaperCreated(
newPaperId,
// _tokenURI
// _title,
// // _owner,
// // _author,
_fields,
// // _subFields,
_references
// // _validatorTip
);
// emit PaperCreated(paper);
// send validationRequest
for (uint256 i = 0; i < _validatorAddresses.length; i++) {
require(isValidator[_validatorAddresses[i]], "not a validator");
}
require(
paperById[newPaperId].stage == PublicationStage.Draft,
"cannot send validation request at this stage."
);
for (uint256 i = 0; i < _validatorAddresses.length; i++) {
validatorRequests[_validatorAddresses[i]][newPaperId] = true;
emit ValidationRequestSent(newPaperId, _validatorAddresses[i]);
}
return newPaperId;
}
function requestValidation(
uint256 _tokenId,
address payable[] memory _validatorAddresses
) public {
require(_tokenId <= paperId.current(), "no such paper");
require(
msg.sender == paperById[_tokenId].owner,
"only owner can send request"
);
require(
paperById[_tokenId].validator == address(0),
"validator already assigned"
);
for (uint256 i = 0; i < _validatorAddresses.length; i++) {
require(isValidator[_validatorAddresses[i]], "not a validator");
}
require(
paperById[_tokenId].stage == PublicationStage.Draft,
"cannot send validation request at this stage."
);
for (uint256 i = 0; i < _validatorAddresses.length; i++) {
validatorRequests[_validatorAddresses[i]][_tokenId] = true;
emit ValidationRequestSent(_tokenId, _validatorAddresses[i]);
}
}
function acceptValidationRequest(uint256 _tokenId, uint256 _deadline)
public
returns (uint256)
{
require(
isValidator[msg.sender] == true,
"sender should be a validator"
);
require(_tokenId <= paperId.current(), "no such paper");
require(
validatorRequests[msg.sender][_tokenId] == true,
"no validatorRequest"
);
// TODO: check if validator field matches with paper field
// require(validatorFields[_validator].length != 0, " not a validator ");
require(
paperById[_tokenId].validator == address(0),
"validator already assigned"
);
require(
paperById[_tokenId].stage == PublicationStage.Draft,
"cannot assign validator at this stage."
);
validatorResponseDeadline[msg.sender][_tokenId] = _deadline;
emit ValidatorResponseSent(_tokenId, msg.sender, _deadline);
return (_deadline);
}
function selectValidator(uint256 _tokenId, address payable _validator)
public
returns (bool)
{
require(_tokenId <= paperId.current(), "no such paper");
require(msg.sender == paperById[_tokenId].owner, "not the owner");
require(
validatorRequests[_validator][_tokenId] == true,
"you didn't send a request to this validator"
);
require(
validatorResponseDeadline[_validator][_tokenId] != 0,
"validator didn't send response"
);
paperById[_tokenId].validator = _validator;
paperById[_tokenId].deadline = validatorResponseDeadline[_validator][
_tokenId
];
paperById[_tokenId].stage = PublicationStage.Preprint;
emit ValidatorConfirmed(
_tokenId,
_validator,
validatorResponseDeadline[_validator][_tokenId]
);
return true;
}
function review(
uint256 _tokenId,
address payable _reviewer,
ReviewerDecision _decision,
string memory _commentsCid
) public {
require(_tokenId <= paperId.current(), "no such paper");
require(
paperById[_tokenId].stage == PublicationStage.Preprint,
"cannot review at this stage"
);
require(
isVerifiedScholar[_reviewer] == true,
"Please verify your address to start reviewing papers"
);
Scholar memory rvwr = scholarByAddress[_reviewer];
bool allowed = false;
for (uint256 i = 0; i < rvwr.fields.length; i++) {
for (uint256 j = 0; j < paperById[_tokenId].fields.length; j++) {
if (
keccak256(abi.encodePacked((rvwr.fields[i]))) ==
keccak256(abi.encodePacked((paperById[_tokenId].fields[j])))
) {
allowed = true;
}
}
}
require(
allowed == true,
"your research field is different from this paper"
);
Review memory rvw = Review(
_tokenId,
_reviewer,
_decision,
_commentsCid
);
reviews[_reviewer][_tokenId].push(rvw);
paperById[_tokenId].peerReviewers.push(_reviewer);
emit ReviewAdded(_tokenId, _reviewer, _commentsCid, _decision);
}
function submitValidatorDecision(uint256 _tokenId, ValidatorDecision _decision)
public
{
require(
isValidator[msg.sender] == true,
"sender should be a validator"
);
require(_tokenId <= paperId.current(), "no such paper");
require(
paperById[_tokenId].validator == msg.sender,
"you are not the validator assigned to this paper"
);
require(
paperById[_tokenId].stage == PublicationStage.Preprint,
"cannot submit validator decision at this stage."
);
if (_decision ==ValidatorDecision.Accept) {
paperById[_tokenId].stage = PublicationStage.Published;
emit Accepted(_tokenId);
} else if (_decision ==ValidatorDecision.Reject) {
paperById[_tokenId].stage = PublicationStage.Draft;
paperById[_tokenId].validator = address(0);
}
emit Validated(_tokenId, _decision);
}
function sellPaper(uint256 _tokenId, address _buyer) public {
require(_tokenId <= paperId.current(), "no such paper");
require(
msg.sender == paperById[_tokenId].owner,
"only owner can sell the paper"
);
require(
paperById[_tokenId].stage == PublicationStage.Published,
"not published"
);
safeTransferFrom(msg.sender, _buyer, _tokenId);
}
function sponsorPaper(uint256 _tokenId) public payable {
require(_tokenId <= paperId.current(), "no such paper");
require(
paperById[_tokenId].stage != PublicationStage.Published,
"cannot sponsor at this stage"
);
sponsorAmounts[msg.sender][_tokenId] += msg.value;
// paperById[_tokenId].sponsorAmounts[msg.sender] += msg.value;
paperById[_tokenId].amountRaised += msg.value;
}
}
| TODO: check if validator field matches with paper field require(validatorFields[_validator].length != 0, " not a validator "); | function acceptValidationRequest(uint256 _tokenId, uint256 _deadline)
public
returns (uint256)
{
require(
isValidator[msg.sender] == true,
"sender should be a validator"
);
require(_tokenId <= paperId.current(), "no such paper");
require(
validatorRequests[msg.sender][_tokenId] == true,
"no validatorRequest"
);
require(
paperById[_tokenId].validator == address(0),
"validator already assigned"
);
require(
paperById[_tokenId].stage == PublicationStage.Draft,
"cannot assign validator at this stage."
);
validatorResponseDeadline[msg.sender][_tokenId] = _deadline;
emit ValidatorResponseSent(_tokenId, msg.sender, _deadline);
return (_deadline);
}
| 13,122,562 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ERC20.sol";
import "./Dubi.sol";
import "./IHodl.sol";
import "./MintMath.sol";
contract Purpose is ERC20 {
// The DUBI contract, required for auto-minting DUBI on burn.
Dubi private immutable _dubi;
// The HODL contract, required for burning locked PRPS.
IHodl private immutable _hodl;
modifier onlyHodl() {
require(msg.sender == _hodlAddress, "PRPS-1");
_;
}
constructor(
uint256 initialSupply,
address optIn,
address dubi,
address hodl,
address externalAddress1,
address externalAddress2,
address externalAddress3
)
public
ERC20(
"Purpose",
"PRPS",
optIn,
hodl,
externalAddress1,
externalAddress2,
externalAddress3
)
{
_dubi = Dubi(dubi);
_hodl = IHodl(hodl);
_mintInitialSupply(msg.sender, initialSupply);
}
/**
* @dev Returns the address of the {HODL} contract used for burning locked PRPS.
*/
function hodl() external view returns (address) {
return address(_hodl);
}
/**
* @dev Returns the hodl balance of the given `tokenHolder`
*/
function hodlBalanceOf(address tokenHolder) public view returns (uint256) {
// The hodl balance follows after the first 96 bits in the packed data.
return uint96(_packedData[tokenHolder] >> 96);
}
/**
* @dev Transfer `amount` PRPS from `from` to the Hodl contract.
*
* This can only be called by the Hodl contract.
*/
function hodlTransfer(address from, uint96 amount) external onlyHodl {
_move(from, address(_hodl), amount);
}
/**
* @dev Increase the hodl balance of `account` by `hodlAmount`. This is
* only used as part of the migration.
*/
function migrateHodlBalance(address account, uint96 hodlAmount)
external
onlyHodl
{
UnpackedData memory unpacked = _unpackPackedData(_packedData[account]);
unpacked.hodlBalance += hodlAmount;
_packedData[account] = _packUnpackedData(unpacked);
}
/**
* @dev Increase the hodl balance of `to` by moving `amount` PRPS from `from`'s balance.
*
* This can only be called by the Hodl contract.
*/
function increaseHodlBalance(
address from,
address to,
uint96 amount
) external onlyHodl {
UnpackedData memory unpackedDataFrom = _unpackPackedData(
_packedData[from]
);
UnpackedData memory unpackedDataTo;
// We only need to unpack twice if from != to
if (from != to) {
unpackedDataTo = _unpackPackedData(_packedData[to]);
} else {
unpackedDataTo = unpackedDataFrom;
}
// `from` must have enough balance
require(unpackedDataFrom.balance >= amount, "PRPS-3");
// Subtract balance from `from`
unpackedDataFrom.balance -= amount;
// Add to `hodlBalance` from `to`
unpackedDataTo.hodlBalance += amount;
// We only need to pack twice if from != to
if (from != to) {
_packedData[to] = _packUnpackedData(unpackedDataTo);
}
_packedData[from] = _packUnpackedData(unpackedDataFrom);
}
/**
* @dev Decrease the hodl balance of `from` by `hodlAmount` and increase
* the regular balance by `refundAmount.
*
* `refundAmount` might be less than `hodlAmount`.
*
* E.g. when burning fuel in locked PRPS
*
* This can only be called by the Hodl contract.
*/
function decreaseHodlBalance(
address from,
uint96 hodlAmount,
uint96 refundAmount
) external onlyHodl {
require(hodlAmount >= refundAmount, "PRPS-4");
UnpackedData memory unpackedDataFrom = _unpackPackedData(
_packedData[from]
);
// `from` must have enough balance
require(unpackedDataFrom.hodlBalance >= hodlAmount, "PRPS-5");
// Subtract amount from hodl balance
unpackedDataFrom.hodlBalance -= hodlAmount;
if (refundAmount > 0) {
// Add amount to balance
unpackedDataFrom.balance += refundAmount;
}
// Write to storage
_packedData[from] = _packUnpackedData(unpackedDataFrom);
}
/**
* @dev Revert the hodl balance change caused by `from` on `to`.
*
* E.g. when reverting a pending hodl.
*
* This can only be called by the Hodl contract.
*/
function revertHodlBalance(
address from,
address to,
uint96 amount
) external onlyHodl {
UnpackedData memory unpackedDataFrom = _unpackPackedData(
_packedData[from]
);
UnpackedData memory unpackedDataTo;
// We only need to unpack twice if from != to
if (from != to) {
unpackedDataTo = _unpackPackedData(_packedData[to]);
} else {
unpackedDataTo = unpackedDataFrom;
}
// `to` must have enough hodl balance
require(unpackedDataTo.hodlBalance >= amount, "PRPS-5");
// Subtract hodl balance from `to`
unpackedDataTo.hodlBalance -= amount;
// Add to `balance` from `from`
unpackedDataFrom.balance += amount;
// We only need to pack twice if from != to
if (from != to) {
_packedData[to] = _packUnpackedData(unpackedDataTo);
}
_packedData[from] = _packUnpackedData(unpackedDataFrom);
}
/**
* @dev Mint DUBI when burning PRPS
* @param from address token holder address
* @param transferAmount amount of tokens to burn
* @param occupiedAmount amount of tokens that are occupied
* @param createdAt equal to block.timestamp if not finalizing a pending op, otherwise
* it corresponds to op.createdAt
* @param finalizing boolean indicating whether this is a finalizing transaction or not. Changes
* how the `amount` is interpreted.
*
* When burning PRPS, we first try to burn unlocked PRPS.
* If burning an amount that exceeds the unlocked PRPS of `from`, we attempt to burn the
* difference from locked PRPS.
*
* If the desired `amount` cannot be filled by taking locked and unlocked PRPS into account,
* this function reverts.
*
* Burning locked PRPS means reducing the `hodlBalance` while burning unlocked PRPS means reducing
* the regular `balance`.
*
* This function returns the actual unlocked PRPS that needs to be removed from `balance`.
*
*/
function _beforeBurn(
address from,
UnpackedData memory unpacked,
uint96 transferAmount,
uint96 occupiedAmount,
uint32 createdAt,
FuelBurn memory fuelBurn,
bool finalizing
) internal override returns (uint96) {
uint96 totalDubiToMint;
uint96 lockedPrpsToBurn;
uint96 burnableUnlockedPrps;
// Depending on whether this is a finalizing burn or not,
// the amount of locked/unlocked PRPS is determined differently.
if (finalizing) {
// For a finalizing burn, we use the occupied amount, since we already know how much
// locked PRPS we are going to burn. This amount represents the `pendingLockedPrps`
// on the hodl items.
lockedPrpsToBurn = occupiedAmount;
// Since `transferAmount` is the total amount of PRPS getting burned, we need to subtract
// the `occupiedAmount` to get the actual amount of unlocked PRPS.
// Sanity check
assert(transferAmount >= occupiedAmount);
transferAmount -= occupiedAmount;
// Set the unlocked PRPS to burn to the updated `transferAmount`
burnableUnlockedPrps = transferAmount;
} else {
// For a direct burn, we start off with the full amounts, since we don't know the exact
// amounts initially.
lockedPrpsToBurn = transferAmount;
burnableUnlockedPrps = unpacked.balance;
}
// 1) Try to burn unlocked PRPS
if (burnableUnlockedPrps > 0) {
// Nice, we can burn unlocked PRPS
// Catch underflow i.e. don't burn more than we need to
if (burnableUnlockedPrps > transferAmount) {
burnableUnlockedPrps = transferAmount;
}
// Calculate DUBI to mint based on unlocked PRPS we can burn
totalDubiToMint = MintMath.calculateDubiToMintMax(
burnableUnlockedPrps
);
// Subtract the amount of burned unlocked PRPS from the locked PRPS we
// need to burn if this is NOT a finalizing burn, because in that case we
// already have the exact amount locked PRPS we want to burn.
if (!finalizing) {
lockedPrpsToBurn -= burnableUnlockedPrps;
}
}
// 2) Burn locked PRPS if there's not enough unlocked PRPS
// Burn an additional amount of locked PRPS equal to the fuel if any
if (fuelBurn.fuelType == FuelType.LOCKED_PRPS) {
// The `burnFromLockedPrps` call will fail, if not enough PRPS can be burned.
lockedPrpsToBurn += fuelBurn.amount;
}
if (lockedPrpsToBurn > 0) {
uint96 dubiToMintFromLockedPrps = _burnFromLockedPrps({
from: from,
unpacked: unpacked,
lockedPrpsToBurn: lockedPrpsToBurn,
createdAt: createdAt,
finalizing: finalizing
});
// We check 'greater than or equal' because it's possible to mint 0 new DUBI
// e.g. when called right after a hodl where not enough time passed to generate new DUBI.
uint96 dubiToMint = totalDubiToMint + dubiToMintFromLockedPrps;
require(dubiToMint >= totalDubiToMint, "PRPS-6");
totalDubiToMint = dubiToMint;
} else {
// Sanity check for finalizes that don't touch locked PRPS
assert(occupiedAmount == 0);
}
// Burn minted DUBI equal to the fuel if any
if (fuelBurn.fuelType == FuelType.AUTO_MINTED_DUBI) {
require(totalDubiToMint >= fuelBurn.amount, "PRPS-7");
totalDubiToMint -= fuelBurn.amount;
}
// Mint DUBI taking differences between burned locked/unlocked into account
if (totalDubiToMint > 0) {
_dubi.purposeMint(from, totalDubiToMint);
}
return burnableUnlockedPrps;
}
function _burnFromLockedPrps(
address from,
UnpackedData memory unpacked,
uint96 lockedPrpsToBurn,
uint32 createdAt,
bool finalizing
) private returns (uint96) {
// Reverts if the exact amount needed cannot be burned
uint96 dubiToMintFromLockedPrps = _hodl.burnLockedPrps({
from: from,
amount: lockedPrpsToBurn,
dubiMintTimestamp: createdAt,
burnPendingLockedPrps: finalizing
});
require(unpacked.hodlBalance >= lockedPrpsToBurn, "PRPS-8");
unpacked.hodlBalance -= lockedPrpsToBurn;
return dubiToMintFromLockedPrps;
}
function _callerIsDeployTimeKnownContract()
internal
override
view
returns (bool)
{
if (msg.sender == address(_dubi)) {
return true;
}
return super._callerIsDeployTimeKnownContract();
}
//---------------------------------------------------------------
// Fuel
//---------------------------------------------------------------
/**
* @dev Burns `fuel` from `from`. Can only be called by one of the deploy-time known contracts.
*/
function burnFuel(address from, TokenFuel memory fuel) public override {
require(_callerIsDeployTimeKnownContract(), "PRPS-2");
_burnFuel(from, fuel);
}
function _burnFuel(address from, TokenFuel memory fuel) private {
require(fuel.amount <= MAX_BOOSTER_FUEL, "PRPS-10");
require(from != address(0) && from != msg.sender, "PRPS-11");
if (fuel.tokenAlias == TOKEN_FUEL_ALIAS_UNLOCKED_PRPS) {
// Burn fuel from unlocked PRPS
UnpackedData memory unpacked = _unpackPackedData(_packedData[from]);
require(unpacked.balance >= fuel.amount, "PRPS-7");
unpacked.balance -= fuel.amount;
_packedData[from] = _packUnpackedData(unpacked);
return;
}
if (fuel.tokenAlias == TOKEN_FUEL_ALIAS_LOCKED_PRPS) {
// Burn fuel from locked PRPS
UnpackedData memory unpacked = _unpackPackedData(_packedData[from]);
require(unpacked.hodlBalance >= fuel.amount, "PRPS-7");
unpacked.hodlBalance -= fuel.amount;
// We pass a mint timestamp, but that doesn't mean that DUBI is minted.
// The returned DUBI that should be minted is ignored.
// Reverts if not enough locked PRPS can be burned.
_hodl.burnLockedPrps({
from: from,
amount: fuel.amount,
dubiMintTimestamp: uint32(block.timestamp),
burnPendingLockedPrps: false
});
_packedData[from] = _packUnpackedData(unpacked);
return;
}
revert("PRPS-12");
}
/**
*@dev Burn the fuel of a `boostedSend`
*/
function _burnBoostedSendFuel(
address from,
BoosterFuel memory fuel,
UnpackedData memory unpacked
) internal override returns (FuelBurn memory) {
FuelBurn memory fuelBurn;
if (fuel.unlockedPrps > 0) {
require(fuel.unlockedPrps <= MAX_BOOSTER_FUEL, "PRPS-10");
require(unpacked.balance >= fuel.unlockedPrps, "PRPS-7");
unpacked.balance -= fuel.unlockedPrps;
fuelBurn.amount = fuel.unlockedPrps;
fuelBurn.fuelType = FuelType.UNLOCKED_PRPS;
return fuelBurn;
}
if (fuel.lockedPrps > 0) {
require(fuel.lockedPrps <= MAX_BOOSTER_FUEL, "PRPS-10");
// We pass a mint timestamp, but that doesn't mean that DUBI is minted.
// The returned DUBI that should be minted is ignored.
// Reverts if not enough locked PRPS can be burned.
_hodl.burnLockedPrps({
from: from,
amount: fuel.lockedPrps,
dubiMintTimestamp: uint32(block.timestamp),
burnPendingLockedPrps: false
});
require(unpacked.hodlBalance >= fuel.lockedPrps, "PRPS-7");
unpacked.hodlBalance -= fuel.lockedPrps;
fuelBurn.amount = fuel.lockedPrps;
fuelBurn.fuelType = FuelType.LOCKED_PRPS;
return fuelBurn;
}
// If the fuel is DUBI, then we have to reach out to the DUBI contract.
if (fuel.dubi > 0) {
// Reverts if the requested amount cannot be burned
_dubi.burnFuel(
from,
TokenFuel({
tokenAlias: TOKEN_FUEL_ALIAS_DUBI,
amount: fuel.dubi
})
);
fuelBurn.amount = fuel.dubi;
fuelBurn.fuelType = FuelType.DUBI;
return fuelBurn;
}
return fuelBurn;
}
/**
*@dev Burn the fuel of a `boostedBurn`
*/
function _burnBoostedBurnFuel(
address from,
BoosterFuel memory fuel,
UnpackedData memory unpacked
) internal override returns (FuelBurn memory) {
FuelBurn memory fuelBurn;
if (fuel.unlockedPrps > 0) {
require(fuel.unlockedPrps <= MAX_BOOSTER_FUEL, "PRPS-10");
require(unpacked.balance >= fuel.unlockedPrps, "PRPS-7");
unpacked.balance -= fuel.unlockedPrps;
fuelBurn.amount = fuel.unlockedPrps;
fuelBurn.fuelType = FuelType.UNLOCKED_PRPS;
return fuelBurn;
}
if (fuel.lockedPrps > 0) {
require(fuel.lockedPrps <= MAX_BOOSTER_FUEL, "PRPS-10");
require(unpacked.hodlBalance >= fuel.lockedPrps, "PRPS-7");
// Fuel is taken from hodl balance in _beforeBurn
// unpacked.hodlBalance -= fuel.lockedPrps;
fuelBurn.amount = fuel.lockedPrps;
fuelBurn.fuelType = FuelType.LOCKED_PRPS;
return fuelBurn;
}
if (fuel.intrinsicFuel > 0) {
require(fuel.intrinsicFuel <= MAX_BOOSTER_FUEL, "PRPS-10");
fuelBurn.amount = fuel.intrinsicFuel;
fuelBurn.fuelType = FuelType.AUTO_MINTED_DUBI;
return fuelBurn;
}
// If the fuel is DUBI, then we have to reach out to the DUBI contract.
if (fuel.dubi > 0) {
// Reverts if the requested amount cannot be burned
_dubi.burnFuel(
from,
TokenFuel({
tokenAlias: TOKEN_FUEL_ALIAS_DUBI,
amount: fuel.dubi
})
);
fuelBurn.amount = fuel.dubi;
fuelBurn.fuelType = FuelType.DUBI;
return fuelBurn;
}
// No fuel at all
return fuelBurn;
}
//---------------------------------------------------------------
// Pending ops
//---------------------------------------------------------------
function _getHasherContracts()
internal
override
returns (address[] memory)
{
address[] memory hashers = new address[](5);
hashers[0] = address(this);
hashers[1] = address(_dubi);
hashers[2] = _hodlAddress;
hashers[3] = _externalAddress1;
hashers[4] = _externalAddress2;
return hashers;
}
/**
* @dev Create a pending transfer by moving the funds of `spender` to this contract.
* Special behavior applies to pending burns to account for locked PRPS.
*/
function _createPendingTransferInternal(
OpHandle memory opHandle,
address spender,
address from,
address to,
uint256 amount,
bytes memory data
) internal override returns (PendingTransfer memory) {
if (opHandle.opType != OP_TYPE_BURN) {
return
// Nothing special to do for non-burns so just call parent implementation
super._createPendingTransferInternal(
opHandle,
spender,
from,
to,
amount,
data
);
}
// When burning, we first use unlocked PRPS and match the remaining amount with locked PRPS from the Hodl contract.
// Sanity check
assert(amount < 2**96);
uint96 transferAmount = uint96(amount);
uint96 lockedPrpsAmount = transferAmount;
UnpackedData memory unpacked = _unpackPackedData(_packedData[from]);
// First try to move as much unlocked PRPS as possible to the PRPS address
uint96 unlockedPrpsToMove = transferAmount;
if (unlockedPrpsToMove > unpacked.balance) {
unlockedPrpsToMove = unpacked.balance;
}
// Update the locked PRPS we have to use
lockedPrpsAmount -= unlockedPrpsToMove;
if (unlockedPrpsToMove > 0) {
_move({from: from, to: address(this), amount: unlockedPrpsToMove});
}
// If we still need locked PRPS, call into the Hodl contract.
// This will also take pending hodls into account, if `from` has
// some.
if (lockedPrpsAmount > 0) {
// Reverts if not the exact amount can be set to pending
_hodl.setLockedPrpsToPending(from, lockedPrpsAmount);
}
// Create pending transfer
return
PendingTransfer({
spender: spender,
transferAmount: transferAmount,
to: to,
occupiedAmount: lockedPrpsAmount,
data: data
});
}
/**
* @dev Hook that is called during revert of a pending op.
* Reverts any changes to locked PRPS when 'opType' is burn.
*/
function _onRevertPendingOp(
address user,
uint8 opType,
uint64 opId,
uint96 transferAmount,
uint96 occupiedAmount
) internal override {
if (opType != OP_TYPE_BURN) {
return;
}
// Extract the pending locked PRPS from the amount.
if (occupiedAmount > 0) {
_hodl.revertLockedPrpsSetToPending(user, occupiedAmount);
}
}
//---------------------------------------------------------------
// Shared pending ops for Hodl
//---------------------------------------------------------------
/**
* @dev Creates a new opHandle with the given type for `user`. Hodl and Prps share the same
* opCounter to enforce a consistent order in which pending ops are finalized/reverted
* across contracts. This function can only be called by Hodl.
*/
function createNewOpHandleShared(
IOptIn.OptInStatus memory optInStatus,
address user,
uint8 opType
) public onlyHodl returns (OpHandle memory) {
return _createNewOpHandle(optInStatus, user, opType);
}
/**
* @dev Delete the op handle with the given `opId` from `user`. Hodl and Prps share the same
* opCounter to enforce a consistent order in which pending ops are finalized/reverted
* across contracts. This function can only be called by Hodl.
*/
function deleteOpHandleShared(address user, OpHandle memory opHandle)
public
onlyHodl
returns (bool)
{
_deleteOpHandle(user, opHandle);
return true;
}
/**
* @dev Get the next op id for `user`. Hodl and Prps share the same
* opCounter to enforce a consistent order in which pending ops are finalized/reverted
* across contracts. This function can only be called by Hodl.
*/
function assertFinalizeFIFOShared(address user, uint64 opId)
public
onlyHodl
returns (bool)
{
_assertFinalizeFIFO(user, opId);
return true;
}
/**
* @dev Get the next op id for `user`. Hodl and Prps share the same
* opCounter to enforce a consistent order in which pending ops are finalized/reverted
* across contracts. This function can only be called by Hodl.
*/
function assertRevertLIFOShared(address user, uint64 opId)
public
onlyHodl
returns (bool)
{
_assertRevertLIFO(user, opId);
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/IERC1820Registry.sol";
import "./IBoostableERC20.sol";
import "./BoostableERC20.sol";
/**
* @dev This is a heavily modified fork of @openzeppelin/contracts/token/ERC20/ERC20.sol (3.1.0)
*/
abstract contract ERC20 is IERC20, IBoostableERC20, BoostableERC20, Ownable {
using SafeMath for uint256;
// NOTE: In contrary to the Transfer event, the Burned event always
// emits the amount including the burned fuel if any.
// The amount is stored in the lower 96 bits of `amountAndFuel`,
// followed by 3 bits to encode the type of fuel used and finally
// another 96 bits for the fuel amount.
//
// 0 96 99 195 256
// amount fuelType fuelAmount padding
//
event Burned(uint256 amountAndFuel, bytes data);
enum FuelType {NONE, UNLOCKED_PRPS, LOCKED_PRPS, DUBI, AUTO_MINTED_DUBI}
struct FuelBurn {
FuelType fuelType;
uint96 amount;
}
uint256 private _totalSupply;
string private _name;
string private _symbol;
address internal immutable _hodlAddress;
address internal immutable _externalAddress1;
address internal immutable _externalAddress2;
address internal immutable _externalAddress3;
IERC1820Registry internal constant _ERC1820_REGISTRY = IERC1820Registry(
0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24
);
// Mapping of address to packed data.
// For efficiency reasons the token balance is a packed uint96 alongside
// other data. The packed data has the following layout:
//
// MSB uint256 LSB
// uint64 nonce | uint96 hodlBalance | uint96 balance
//
// balance: the balance of a token holder that can be transferred freely
// hodlBalance: the balance of a token holder that is hodled
// nonce: a sequential number used for booster replay protection
//
// Only PRPS utilizes `hodlBalance`. For DUBI it is always 0.
//
mapping(address => uint256) internal _packedData;
struct UnpackedData {
uint96 balance;
uint96 hodlBalance;
uint64 nonce;
}
function _unpackPackedData(uint256 packedData)
internal
pure
returns (UnpackedData memory)
{
UnpackedData memory unpacked;
// 1) Read balance from the first 96 bits
unpacked.balance = uint96(packedData);
// 2) Read hodlBalance from the next 96 bits
unpacked.hodlBalance = uint96(packedData >> 96);
// 3) Read nonce from the next 64 bits
unpacked.nonce = uint64(packedData >> (96 + 96));
return unpacked;
}
function _packUnpackedData(UnpackedData memory unpacked)
internal
pure
returns (uint256)
{
uint256 packedData;
// 1) Write balance to the first 96 bits
packedData |= unpacked.balance;
// 2) Write hodlBalance to the the next 96 bits
packedData |= uint256(unpacked.hodlBalance) << 96;
// 3) Write nonce to the next 64 bits
packedData |= uint256(unpacked.nonce) << (96 + 96);
return packedData;
}
// ERC20-allowances
mapping(address => mapping(address => uint256)) private _allowances;
//---------------------------------------------------------------
// Pending state for non-boosted operations while opted-in
//---------------------------------------------------------------
uint8 internal constant OP_TYPE_SEND = BOOST_TAG_SEND;
uint8 internal constant OP_TYPE_BURN = BOOST_TAG_BURN;
struct PendingTransfer {
// NOTE: For efficiency reasons balances are stored in a uint96 which is sufficient
// since we only use 18 decimals.
//
// Two amounts are associated with a pending transfer, to allow deriving contracts
// to store extra information.
//
// E.g. PRPS makes use of this by encoding the pending locked PRPS in the
// `occupiedAmount` field.
//
address spender;
uint96 transferAmount;
address to;
uint96 occupiedAmount;
bytes data;
}
// A mapping of hash(user, opId) to pending transfers. Pending burns are also considered regular transfers.
mapping(bytes32 => PendingTransfer) private _pendingTransfers;
//---------------------------------------------------------------
constructor(
string memory name,
string memory symbol,
address optIn,
address hodl,
address externalAddress1,
address externalAddress2,
address externalAddress3
) public Ownable() BoostableERC20(optIn) {
_name = name;
_symbol = symbol;
_hodlAddress = hodl;
_externalAddress1 = externalAddress1;
_externalAddress2 = externalAddress2;
_externalAddress3 = externalAddress3;
// register interfaces
_ERC1820_REGISTRY.setInterfaceImplementer(
address(this),
keccak256("BoostableERC20Token"),
address(this)
);
_ERC1820_REGISTRY.setInterfaceImplementer(
address(this),
keccak256("ERC20Token"),
address(this)
);
}
/**
* @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.
*/
function decimals() public pure returns (uint8) {
return 18;
}
/**
* @dev Returns the current nonce of `account`
*/
function getNonce(address account) external override view returns (uint64) {
UnpackedData memory unpacked = _unpackPackedData(_packedData[account]);
return unpacked.nonce;
}
/**
* @dev Returns the total supply
*/
function totalSupply()
external
override(IBoostableERC20, IERC20)
view
returns (uint256)
{
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder)
public
override(IBoostableERC20, IERC20)
view
returns (uint256)
{
// Return the balance of the holder that is not hodled (i.e. first 96 bits of the packeData)
return uint96(_packedData[tokenHolder]);
}
/**
* @dev Returns the unpacked data struct of `tokenHolder`
*/
function unpackedDataOf(address tokenHolder)
public
view
returns (UnpackedData memory)
{
return _unpackPackedData(_packedData[tokenHolder]);
}
/**
* @dev Mints `amount` new tokens for `to`.
*
* To make things more efficient, the total supply is optionally packed into the passed
* amount where the first 96 bits are used for the actual amount and the following 96 bits
* for the total supply.
*
*/
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
function _mintInitialSupply(address to, uint256 amount) internal {
// _mint does not update the totalSupply by default, unless the second 96 bits
// passed are non-zero - in which case the non-zero value becomes the new total supply.
// So in order to get the correct initial supply, we have to mirror the lower 96 bits
// to the following 96 bits.
amount = amount | (amount << 96);
_mint(to, amount);
}
function _mint(address to, uint256 amount) internal {
require(to != address(0), "ERC20-1");
// The actual amount to mint (=lower 96 bits)
uint96 amountToMint = uint96(amount);
// The new total supply, which may be 0 in which case no update is performed.
uint96 updatedTotalSupply = uint96(amount >> 96);
// Update state variables
if (updatedTotalSupply > 0) {
_totalSupply = updatedTotalSupply;
}
// Update packed data and check for uint96 overflow
UnpackedData memory unpacked = _unpackPackedData(_packedData[to]);
uint96 updatedBalance = unpacked.balance + amountToMint;
// The overflow check also takes the hodlBalance into account
require(
updatedBalance + unpacked.hodlBalance >= unpacked.balance,
"ERC20-2"
);
unpacked.balance = updatedBalance;
_packedData[to] = _packUnpackedData(unpacked);
emit Transfer(address(0), to, amountToMint);
}
/**
* @dev Transfer `amount` from msg.sender to `recipient`
*/
function transfer(address recipient, uint256 amount)
public
override(IBoostableERC20, IERC20)
returns (bool)
{
_assertSenderRecipient(msg.sender, recipient);
// Never create a pending transfer if msg.sender is a deploy-time known contract
if (!_callerIsDeployTimeKnownContract()) {
// Create pending transfer if sender is opted-in and the permaboost is active
address from = msg.sender;
IOptIn.OptInStatus memory optInStatus = getOptInStatus(from);
if (optInStatus.isOptedIn && optInStatus.permaBoostActive) {
_createPendingTransfer({
opType: OP_TYPE_SEND,
spender: msg.sender,
from: msg.sender,
to: recipient,
amount: amount,
data: "",
optInStatus: optInStatus
});
return true;
}
}
_move({from: msg.sender, to: recipient, amount: amount});
return true;
}
/**
* @dev Burns `amount` of msg.sender.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes memory data) public {
// Create pending burn if sender is opted-in and the permaboost is active
IOptIn.OptInStatus memory optInStatus = getOptInStatus(msg.sender);
if (optInStatus.isOptedIn && optInStatus.permaBoostActive) {
_createPendingTransfer({
opType: OP_TYPE_BURN,
spender: msg.sender,
from: msg.sender,
to: address(0),
amount: amount,
data: data,
optInStatus: optInStatus
});
return;
}
_burn({
from: msg.sender,
amount: amount,
data: data,
incrementNonce: false
});
}
/**
* @dev Moves `amount` tokens from `sender` to `recipient`.
*
* Can only be used by deploy-time known contracts.
*
* IBoostableERC20 extension
*/
function boostedTransferFrom(
address sender,
address recipient,
uint256 amount,
bytes calldata data
) public override returns (bool) {
_assertSenderRecipient(sender, recipient);
IOptIn.OptInStatus memory optInStatus = getOptInStatus(sender);
// Only transfer if `sender` is a deploy-time known contract, otherwise
// revert.
require(
_isDeployTimeKnownContractAndCanTransfer(
sender,
recipient,
amount,
optInStatus,
data
),
"ERC20-17"
);
_move({from: sender, to: recipient, amount: amount});
return true;
}
function _isDeployTimeKnownContractAndCanTransfer(
address sender,
address recipient,
uint256 amount,
IOptIn.OptInStatus memory optInStatus,
bytes memory data
) private view returns (bool) {
// If the caller not a deploy-time known contract, the transfer is not allowed
if (!_callerIsDeployTimeKnownContract()) {
return false;
}
if (msg.sender != _externalAddress3) {
return true;
}
// _externalAddress3 passes a flag via `data` that indicates whether it is a boosted transaction
// or not.
uint8 isBoostedBits;
assembly {
// Load flag using a 1-byte offset, because `mload` always reads
// 32-bytes at once and the first 32 bytes of `data` contain it's length.
isBoostedBits := mload(add(data, 0x01))
}
// Reading into a 'bool' directly doesn't work for some reason
if (isBoostedBits & 1 == 1) {
return true;
}
// If the latter, then _externalAddress3 can only transfer the funds if either:
// - the permaboost is not active
// - `sender` is not opted-in to begin with
//
// If `sender` is opted-in and the permaboost is active, _externalAddress3 cannot
// take funds, except when boosted. Here the booster trusts _externalAddress3, since it already
// verifies that `sender` provided a valid signature.
//
// This is special to _externalAddress3, other deploy-time known contracts do not make use of `data`.
if (optInStatus.permaBoostActive && optInStatus.isOptedIn) {
return false;
}
return true;
}
/**
* @dev Verify the booster payload against the nonce that is stored in the packed data of an account.
* The increment happens outside of this function, when the balance is updated.
*/
function _verifyNonce(BoosterPayload memory payload, uint64 currentNonce)
internal
pure
{
require(currentNonce == payload.nonce - 1, "ERC20-5");
}
//---------------------------------------------------------------
// Boosted functions
//---------------------------------------------------------------
/**
* @dev Perform multiple `boostedSend` calls in a single transaction.
*
* NOTE: Booster extension
*/
function boostedSendBatch(
BoostedSend[] memory sends,
Signature[] memory signatures
) external {
require(
sends.length > 0 && sends.length == signatures.length,
"ERC20-6"
);
for (uint256 i = 0; i < sends.length; i++) {
boostedSend(sends[i], signatures[i]);
}
}
/**
* @dev Perform multiple `boostedBurn` calls in a single transaction.
*
* NOTE: Booster extension
*/
function boostedBurnBatch(
BoostedBurn[] memory burns,
Signature[] memory signatures
) external {
require(
burns.length > 0 && burns.length == signatures.length,
"ERC20-6"
);
for (uint256 i = 0; i < burns.length; i++) {
boostedBurn(burns[i], signatures[i]);
}
}
/**
* @dev Send `amount` tokens from `sender` to recipient`.
* The `sender` must be opted-in and the `msg.sender` must be a trusted booster.
*
* NOTE: Booster extension
*/
function boostedSend(BoostedSend memory send, Signature memory signature)
public
{
address from = send.sender;
address to = send.recipient;
UnpackedData memory unpackedFrom = _unpackPackedData(_packedData[from]);
UnpackedData memory unpackedTo = _unpackPackedData(_packedData[to]);
// We verify the nonce separately, since it's stored next to the balance
_verifyNonce(send.boosterPayload, unpackedFrom.nonce);
_verifyBoostWithoutNonce(
send.sender,
hashBoostedSend(send, msg.sender),
send.boosterPayload,
signature
);
FuelBurn memory fuelBurn = _burnBoostedSendFuel(
from,
send.fuel,
unpackedFrom
);
_moveUnpacked({
from: send.sender,
unpackedFrom: unpackedFrom,
to: send.recipient,
unpackedTo: unpackedTo,
amount: send.amount,
fuelBurn: fuelBurn,
incrementNonce: true
});
}
/**
* @dev Burn the fuel of a `boostedSend`. Returns a `FuelBurn` struct containing information about the burn.
*/
function _burnBoostedSendFuel(
address from,
BoosterFuel memory fuel,
UnpackedData memory unpacked
) internal virtual returns (FuelBurn memory);
/**
* @dev Burn `amount` tokens from `account`.
* The `account` must be opted-in and the `msg.sender` must be a trusted booster.
*
* NOTE: Booster extension
*/
function boostedBurn(
BoostedBurn memory message,
// A signature, that is compared against the function payload and only accepted if signed by 'sender'
Signature memory signature
) public {
address from = message.account;
UnpackedData memory unpacked = _unpackPackedData(_packedData[from]);
// We verify the nonce separately, since it's stored next to the balance
_verifyNonce(message.boosterPayload, unpacked.nonce);
_verifyBoostWithoutNonce(
message.account,
hashBoostedBurn(message, msg.sender),
message.boosterPayload,
signature
);
FuelBurn memory fuelBurn = _burnBoostedBurnFuel(
from,
message.fuel,
unpacked
);
_burnUnpacked({
from: message.account,
unpacked: unpacked,
amount: message.amount,
data: message.data,
incrementNonce: true,
fuelBurn: fuelBurn
});
}
/**
* @dev Burn the fuel of a `boostedSend`. Returns a `FuelBurn` struct containing information about the burn.
*/
function _burnBoostedBurnFuel(
address from,
BoosterFuel memory fuel,
UnpackedData memory unpacked
) internal virtual returns (FuelBurn memory);
function burnFuel(address from, TokenFuel memory fuel)
external
virtual
override
{}
//---------------------------------------------------------------
/**
* @dev Get the allowance of `spender` for `holder`
*/
function allowance(address holder, address spender)
public
override(IBoostableERC20, IERC20)
view
returns (uint256)
{
return _allowances[holder][spender];
}
/**
* @dev Increase the allowance of `spender` by `value` for msg.sender
*/
function approve(address spender, uint256 value)
public
override(IBoostableERC20, IERC20)
returns (bool)
{
address holder = msg.sender;
_assertSenderRecipient(holder, spender);
_approve(holder, spender, value);
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)
{
_assertSenderRecipient(msg.sender, spender);
_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)
{
_assertSenderRecipient(msg.sender, spender);
_approve(
msg.sender,
spender,
_allowances[msg.sender][spender].sub(subtractedValue, "ERC20-18")
);
return true;
}
/**
* @dev Transfer `amount` from `holder` to `recipient`.
*
* `msg.sender` requires an allowance >= `amount` of `holder`.
*/
function transferFrom(
address holder,
address recipient,
uint256 amount
) public override(IBoostableERC20, IERC20) returns (bool) {
_assertSenderRecipient(holder, recipient);
address spender = msg.sender;
// Create pending transfer if the token holder is opted-in and the permaboost is active
IOptIn.OptInStatus memory optInStatus = getOptInStatus(holder);
if (optInStatus.isOptedIn && optInStatus.permaBoostActive) {
// Ignore allowances if holder is opted-in
require(holder == spender, "ERC20-7");
_createPendingTransfer({
opType: OP_TYPE_SEND,
spender: spender,
from: holder,
to: recipient,
amount: amount,
data: "",
optInStatus: optInStatus
});
return true;
}
// Not opted-in, but we still need to check approval of the given spender
_approve(
holder,
spender,
_allowances[holder][spender].sub(amount, "ERC20-4")
);
_move({from: holder, to: recipient, amount: amount});
return true;
}
/**
* @dev Burn tokens
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param incrementNonce whether to increment the nonce or not - only true for boosted burns
*/
function _burn(
address from,
uint256 amount,
bytes memory data,
bool incrementNonce
) internal virtual {
require(from != address(0), "ERC20-8");
UnpackedData memory unpacked = _unpackPackedData(_packedData[from]);
// Empty fuel burn
FuelBurn memory fuelBurn;
_burnUnpacked({
from: from,
unpacked: unpacked,
amount: amount,
data: data,
incrementNonce: incrementNonce,
fuelBurn: fuelBurn
});
}
function _burnUnpacked(
address from,
UnpackedData memory unpacked,
uint256 amount,
bytes memory data,
bool incrementNonce,
FuelBurn memory fuelBurn
) internal {
// _beforeBurn allows deriving contracts to run additional logic and affect the amount
// that is actually getting burned. E.g. when burning PRPS, a portion of it might be taken
// from the `hodlBalance`. Thus the returned `burnAmount` overrides `amount` and will be
// subtracted from the actual `balance`.
uint96 actualBurnAmount = _beforeBurn({
from: from,
unpacked: unpacked,
transferAmount: uint96(amount),
occupiedAmount: 0,
createdAt: uint32(block.timestamp),
fuelBurn: fuelBurn,
finalizing: false
});
// Update to new balance
if (incrementNonce) {
// The nonce uses 64 bits, so a overflow is pretty much impossible
// via increments of 1.
unpacked.nonce++;
}
if (actualBurnAmount > 0) {
require(unpacked.balance >= actualBurnAmount, "ERC20-9");
unpacked.balance -= actualBurnAmount;
}
// Update packed data by writing to storage
_packedData[from] = _packUnpackedData(unpacked);
// Total supply can be updated in batches elsewhere, shaving off another >5k gas.
// _totalSupply = _totalSupply.sub(amount);
// The `Burned` event is emitted with the total amount that got burned.
// Furthermore, the fuel used is encoded in the upper bits.
uint256 amountAndFuel;
// Set first 96 bits to amount
amountAndFuel |= uint96(amount);
// Set next 3 bits to fuel type
uint8 fuelType = uint8(fuelBurn.fuelType);
amountAndFuel |= uint256(fuelType) << 96;
// Set next 96 bits to fuel amount
amountAndFuel |= uint256(fuelBurn.amount) << (96 + 3);
emit Burned(amountAndFuel, data);
// We emit a transfer event with the actual burn amount excluding burned `hodlBalance`.
emit Transfer(from, address(0), actualBurnAmount);
}
/**
* @dev Allow deriving contracts to prepare a burn. By default it behaves like an identity function
* and just returns the amount passed in.
*/
function _beforeBurn(
address from,
UnpackedData memory unpacked,
uint96 transferAmount,
uint96 occupiedAmount,
uint32 createdAt,
FuelBurn memory fuelBurn,
bool finalizing
) internal virtual returns (uint96) {
return transferAmount;
}
function _move(
address from,
address to,
uint256 amount
) internal {
UnpackedData memory unpackedFrom = _unpackPackedData(_packedData[from]);
UnpackedData memory unpackedTo = _unpackPackedData(_packedData[to]);
// Empty fuel burn
FuelBurn memory fuelBurn;
_moveUnpacked({
from: from,
unpackedFrom: unpackedFrom,
to: to,
unpackedTo: unpackedTo,
amount: amount,
incrementNonce: false,
fuelBurn: fuelBurn
});
}
function _moveUnpacked(
address from,
UnpackedData memory unpackedFrom,
address to,
UnpackedData memory unpackedTo,
uint256 amount,
bool incrementNonce,
FuelBurn memory fuelBurn
) internal {
require(from != to, "ERC20-19");
// Increment nonce of sender if it's a boosted send
if (incrementNonce) {
// The nonce uses 64 bits, so a overflow is pretty much impossible
// via increments of 1.
unpackedFrom.nonce++;
}
// Check if sender has enough tokens
uint96 transferAmount = uint96(amount);
require(unpackedFrom.balance >= transferAmount, "ERC20-10");
// Subtract transfer amount from sender balance
unpackedFrom.balance -= transferAmount;
// Check that recipient balance doesn't overflow
uint96 updatedRecipientBalance = unpackedTo.balance + transferAmount;
require(updatedRecipientBalance >= unpackedTo.balance, "ERC20-12");
unpackedTo.balance = updatedRecipientBalance;
_packedData[from] = _packUnpackedData(unpackedFrom);
_packedData[to] = _packUnpackedData(unpackedTo);
// The transfer amount does not include any used fuel
emit Transfer(from, to, transferAmount);
}
/**
* @dev See {ERC20-_approve}.
*/
function _approve(
address holder,
address spender,
uint256 value
) internal {
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
function _assertSenderRecipient(address sender, address recipient)
private
pure
{
require(sender != address(0) && recipient != address(0), "ERC20-13");
}
/**
* @dev Checks whether msg.sender is a deploy-time known contract or not.
*/
function _callerIsDeployTimeKnownContract()
internal
virtual
view
returns (bool)
{
if (msg.sender == _hodlAddress) {
return true;
}
if (msg.sender == _externalAddress1) {
return true;
}
if (msg.sender == _externalAddress2) {
return true;
}
if (msg.sender == _externalAddress3) {
return true;
}
return false;
}
//---------------------------------------------------------------
// Pending ops
//---------------------------------------------------------------
/**
* @dev Create a pending transfer
*/
function _createPendingTransfer(
uint8 opType,
address spender,
address from,
address to,
uint256 amount,
bytes memory data,
IOptIn.OptInStatus memory optInStatus
) private {
OpHandle memory opHandle = _createNewOpHandle(
optInStatus,
from,
opType
);
PendingTransfer memory pendingTransfer = _createPendingTransferInternal(
opHandle,
spender,
from,
to,
amount,
data
);
_pendingTransfers[_getOpKey(from, opHandle.opId)] = pendingTransfer;
// Emit PendingOp event
emit PendingOp(from, opHandle.opId, opHandle.opType);
}
/**
* @dev Create a pending transfer by moving the funds of `spender` to this contract.
* Deriving contracts may override this function.
*/
function _createPendingTransferInternal(
OpHandle memory opHandle,
address spender,
address from,
address to,
uint256 amount,
bytes memory data
) internal virtual returns (PendingTransfer memory) {
// Move funds into this contract
// Reverts if `from` has less than `amount` tokens.
_move({from: from, to: address(this), amount: amount});
// Create op
PendingTransfer memory pendingTransfer = PendingTransfer({
transferAmount: uint96(amount),
spender: spender,
occupiedAmount: 0,
to: to,
data: data
});
return pendingTransfer;
}
/**
* @dev Finalize a pending op
*/
function finalizePendingOp(address user, OpHandle memory opHandle) public {
uint8 opType = opHandle.opType;
// Assert that the caller (msg.sender) is allowed to finalize the given op
uint32 createdAt = uint32(_assertCanFinalize(user, opHandle));
// Reverts if opId doesn't exist
PendingTransfer storage pendingTransfer = _safeGetPendingTransfer(
user,
opHandle.opId
);
// Cleanup
// NOTE: We do not delete the pending transfer struct, because it only makes it
// more expensive since we already hit the gas refund limit.
//
// delete _pendingTransfers[_getOpKey(user, opHandle.opId)];
//
// The difference is ~13k gas.
//
// Deleting the op handle is enough to invalidate an opId forever:
_deleteOpHandle(user, opHandle);
// Call op type specific finalize
if (opType == OP_TYPE_SEND) {
_finalizeTransferOp(pendingTransfer, user, createdAt);
} else if (opType == OP_TYPE_BURN) {
_finalizePendingBurn(pendingTransfer, user, createdAt);
} else {
revert("ERC20-15");
}
// Emit event
emit FinalizedOp(user, opHandle.opId, opType);
}
/**
* @dev Finalize a pending transfer
*/
function _finalizeTransferOp(
PendingTransfer storage pendingTransfer,
address from,
uint32 createdAt
) private {
address to = pendingTransfer.to;
uint96 transferAmount = pendingTransfer.transferAmount;
address _this = address(this);
UnpackedData memory unpackedThis = _unpackPackedData(
_packedData[_this]
);
UnpackedData memory unpackedTo = _unpackPackedData(_packedData[to]);
// Check that sender balance does not overflow
require(unpackedThis.balance >= transferAmount, "ERC20-2");
unpackedThis.balance -= transferAmount;
// Check that recipient doesn't overflow
uint96 updatedBalanceRecipient = unpackedTo.balance + transferAmount;
require(updatedBalanceRecipient >= unpackedTo.balance, "ERC20-2");
unpackedTo.balance = updatedBalanceRecipient;
_packedData[_this] = _packUnpackedData(unpackedThis);
_packedData[to] = _packUnpackedData(unpackedTo);
// Transfer event is emitted with original sender
emit Transfer(from, to, transferAmount);
}
/**
* @dev Finalize a pending burn
*/
function _finalizePendingBurn(
PendingTransfer storage pendingTransfer,
address from,
uint32 createdAt
) private {
uint96 transferAmount = pendingTransfer.transferAmount;
// We pass the packedData of `from` to `_beforeBurn`, because it PRPS needs to update
// the `hodlBalance` which is NOT on the contract's own packedData.
UnpackedData memory unpackedFrom = _unpackPackedData(_packedData[from]);
// Empty fuel burn
FuelBurn memory fuelBurn;
uint96 burnAmountExcludingLockedPrps = _beforeBurn({
from: from,
unpacked: unpackedFrom,
transferAmount: transferAmount,
occupiedAmount: pendingTransfer.occupiedAmount,
createdAt: createdAt,
fuelBurn: fuelBurn,
finalizing: true
});
// Update to new balance
// NOTE: We change the balance of this contract, because that's where
// the pending PRPS went to.
address _this = address(this);
UnpackedData memory unpackedOfContract = _unpackPackedData(
_packedData[_this]
);
require(
unpackedOfContract.balance >= burnAmountExcludingLockedPrps,
"ERC20-2"
);
unpackedOfContract.balance -= burnAmountExcludingLockedPrps;
_packedData[_this] = _packUnpackedData(unpackedOfContract);
_packedData[from] = _packUnpackedData(unpackedFrom);
// Furthermore, total supply can be updated elsewhere, shaving off another >5k gas.
// _totalSupply = _totalSupply.sub(amount);
// Emit events using the same `transferAmount` instead of what `_beforeBurn`
// returned which is only used for updating the balance correctly.
emit Burned(transferAmount, pendingTransfer.data);
emit Transfer(from, address(0), transferAmount);
}
/**
* @dev Revert a pending operation.
*
* Only the opted-in booster can revert a transaction if it provides a signed and still valid booster message
* from the original sender.
*/
function revertPendingOp(
address user,
OpHandle memory opHandle,
bytes memory boosterMessage,
Signature memory signature
) public {
// Prepare revert, including permission check and prevents reentrancy for same opHandle.
_prepareOpRevert({
user: user,
opHandle: opHandle,
boosterMessage: boosterMessage,
signature: signature
});
// Now perform the actual revert of the pending op
_revertPendingOp(user, opHandle.opType, opHandle.opId);
}
/**
* @dev Revert a pending transfer
*/
function _revertPendingOp(
address user,
uint8 opType,
uint64 opId
) private {
PendingTransfer storage pendingTransfer = _safeGetPendingTransfer(
user,
opId
);
uint96 transferAmount = pendingTransfer.transferAmount;
uint96 occupiedAmount = pendingTransfer.occupiedAmount;
// Move funds from this contract back to the original sender. Transfers and burns
// are reverted the same way. We only transfer back the `transferAmount` - that is the amount
// that actually got moved into this contract. The occupied amount is released during `onRevertPendingOp`
// by the deriving contract.
_move({from: address(this), to: user, amount: transferAmount});
// Call hook to allow deriving contracts to perform additional cleanup
_onRevertPendingOp(user, opType, opId, transferAmount, occupiedAmount);
// NOTE: we do not clean up the ops mapping, because we already hit the
// gas refund limit.
// delete _pendingTransfers[_getOpKey(user, opHandle.opId)];
// Emit event
emit RevertedOp(user, opId, opType);
}
/**
* @dev Hook that is called during revert of a pending transfer.
* Allows deriving contracts to perform additional cleanup.
*/
function _onRevertPendingOp(
address user,
uint8 opType,
uint64 opId,
uint96 transferAmount,
uint96 occupiedAmount
) internal virtual {}
/**
* @dev Safely get a pending transfer. Reverts if it doesn't exist.
*/
function _safeGetPendingTransfer(address user, uint64 opId)
private
view
returns (PendingTransfer storage)
{
PendingTransfer storage pendingTransfer = _pendingTransfers[_getOpKey(
user,
opId
)];
require(pendingTransfer.spender != address(0), "ERC20-16");
return pendingTransfer;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ERC20.sol";
import "./Purpose.sol";
contract Dubi is ERC20 {
Purpose private immutable _prps;
constructor(
uint256 initialSupply,
address optIn,
address purpose,
address hodl,
address externalAddress1,
address externalAddress2,
address externalAddress3
)
public
ERC20(
"Decentralized Universal Basic Income",
"DUBI",
optIn,
hodl,
externalAddress1,
externalAddress2,
externalAddress3
)
{
_mintInitialSupply(msg.sender, initialSupply);
_prps = Purpose(purpose);
}
function hodlMint(address to, uint256 amount) public {
require(msg.sender == _hodlAddress, "DUBI-2");
_mint(to, amount);
}
function purposeMint(address to, uint256 amount) public {
require(msg.sender == address(_prps), "DUBI-3");
_mint(to, amount);
}
function _callerIsDeployTimeKnownContract()
internal
override
view
returns (bool)
{
if (msg.sender == address(_prps)) {
return true;
}
return super._callerIsDeployTimeKnownContract();
}
//---------------------------------------------------------------
// Fuel
//---------------------------------------------------------------
/**
* @dev Burns `fuel` from `from`. Can only be called by one of the deploy-time known contracts.
*/
function burnFuel(address from, TokenFuel memory fuel) public override {
require(_callerIsDeployTimeKnownContract(), "DUBI-1");
_burnFuel(from, fuel);
}
function _burnFuel(address from, TokenFuel memory fuel) private {
require(fuel.amount <= MAX_BOOSTER_FUEL, "DUBI-5");
require(from != address(0) && from != msg.sender, "DUBI-6");
if (fuel.tokenAlias == TOKEN_FUEL_ALIAS_DUBI) {
// Burn fuel from DUBI
UnpackedData memory unpacked = _unpackPackedData(_packedData[from]);
require(unpacked.balance >= fuel.amount, "DUBI-7");
unpacked.balance -= fuel.amount;
_packedData[from] = _packUnpackedData(unpacked);
return;
}
revert("DUBI-8");
}
/**
*@dev Burn the fuel of a `boostedSend`
*/
function _burnBoostedSendFuel(
address from,
BoosterFuel memory fuel,
UnpackedData memory unpacked
) internal override returns (FuelBurn memory) {
FuelBurn memory fuelBurn;
if (fuel.dubi > 0) {
require(fuel.dubi <= MAX_BOOSTER_FUEL, "DUBI-5");
// From uses his own DUBI to fuel the boost
require(unpacked.balance >= fuelBurn.amount, "DUBI-7");
unpacked.balance -= fuel.dubi;
fuelBurn.amount = fuel.dubi;
fuelBurn.fuelType = FuelType.DUBI;
return fuelBurn;
}
// If the fuel is PRPS, then we have to reach out to the PRPS contract.
if (fuel.unlockedPrps > 0) {
// Reverts if the requested amount cannot be burned
_prps.burnFuel(
from,
TokenFuel({
tokenAlias: TOKEN_FUEL_ALIAS_UNLOCKED_PRPS,
amount: fuel.unlockedPrps
})
);
fuelBurn.amount = fuel.unlockedPrps;
fuelBurn.fuelType = FuelType.UNLOCKED_PRPS;
return fuelBurn;
}
if (fuel.lockedPrps > 0) {
// Reverts if the requested amount cannot be burned
_prps.burnFuel(
from,
TokenFuel({
tokenAlias: TOKEN_FUEL_ALIAS_LOCKED_PRPS,
amount: fuel.lockedPrps
})
);
fuelBurn.amount = fuel.lockedPrps;
fuelBurn.fuelType = FuelType.LOCKED_PRPS;
return fuelBurn;
}
// No fuel at all
return fuelBurn;
}
/**
*@dev Burn the fuel of a `boostedBurn`
*/
function _burnBoostedBurnFuel(
address from,
BoosterFuel memory fuel,
UnpackedData memory unpacked
) internal override returns (FuelBurn memory) {
FuelBurn memory fuelBurn;
// If the fuel is DUBI, then we can remove it directly
if (fuel.dubi > 0) {
require(fuel.dubi <= MAX_BOOSTER_FUEL, "DUBI-5");
require(unpacked.balance >= fuel.dubi, "DUBI-7");
unpacked.balance -= fuel.dubi;
fuelBurn.amount = fuel.dubi;
fuelBurn.fuelType = FuelType.DUBI;
return fuelBurn;
}
// If the fuel is PRPS, then we have to reach out to the PRPS contract.
if (fuel.unlockedPrps > 0) {
// Reverts if the requested amount cannot be burned
_prps.burnFuel(
from,
TokenFuel({
tokenAlias: TOKEN_FUEL_ALIAS_UNLOCKED_PRPS,
amount: fuel.unlockedPrps
})
);
fuelBurn.amount = fuel.unlockedPrps;
fuelBurn.fuelType = FuelType.UNLOCKED_PRPS;
return fuelBurn;
}
if (fuel.lockedPrps > 0) {
// Reverts if the requested amount cannot be burned
_prps.burnFuel(
from,
TokenFuel({
tokenAlias: TOKEN_FUEL_ALIAS_LOCKED_PRPS,
amount: fuel.lockedPrps
})
);
// No direct fuel, but we still return a indirect fuel so that it can be added
// to the burn event.
fuelBurn.amount = fuel.lockedPrps;
fuelBurn.fuelType = FuelType.LOCKED_PRPS;
return fuelBurn;
}
// DUBI has no intrinsic fuel
if (fuel.intrinsicFuel > 0) {
revert("DUBI-8");
}
// No fuel at all
return fuelBurn;
}
//---------------------------------------------------------------
// Pending ops
//---------------------------------------------------------------
function _getHasherContracts()
internal
override
returns (address[] memory)
{
address[] memory hashers = new address[](5);
hashers[0] = address(this);
hashers[1] = address(_prps);
hashers[2] = _hodlAddress;
hashers[3] = _externalAddress1;
hashers[4] = _externalAddress2;
return hashers;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IHodl {
/**
* @dev Lock the given amount of PRPS for the specified period (or infinitely)
* for DUBI.
*/
function hodl(
uint24 id,
uint96 amountPrps,
uint16 duration,
address dubiBeneficiary,
address prpsBeneficiary
) external;
/**
* @dev Release a hodl of `prpsBeneficiary` with the given `creator` and `id`.
*/
function release(
uint24 id,
address prpsBeneficiary,
address creator
) external;
/**
* @dev Withdraw can be used to withdraw DUBI from infinitely locked PRPS.
* The amount of DUBI withdrawn depends on the time passed since the last withdrawal.
*/
function withdraw(
uint24 id,
address prpsBeneficiary,
address creator
) external;
/**
* @dev Burn `amount` of `from`'s locked and/or pending PRPS.
*
* This function is supposed to be only called by the PRPS contract.
*
* Returns the amount of DUBI that needs to be minted.
*/
function burnLockedPrps(
address from,
uint96 amount,
uint32 dubiMintTimestamp,
bool burnPendingLockedPrps
) external returns (uint96);
/**
* @dev Set `amount` of `from`'s locked PRPS to pending.
*
* This function is supposed to be only called by the PRPS contract.
*
* Returns the amount of locked PRPS that could be set to pending.
*/
function setLockedPrpsToPending(address from, uint96 amount) external;
/**
* @dev Revert `amount` of `from`'s pending locked PRPS to not pending.
*
* This function is supposed to be only called by the PRPS contract and returns
*/
function revertLockedPrpsSetToPending(address account, uint96 amount)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// NOTE: we ignore leap-seconds etc.
library MintMath {
// The maximum number of seconds per month (365 * 24 * 60 * 60 / 12)
uint32 public constant SECONDS_PER_MONTH = 2628000;
// The maximum number of days PRPS can be finitely locked for
uint16 public constant MAX_FINITE_LOCK_DURATION_DAYS = 365;
// The maximum number of seconds PRPS can be finitely locked for
uint32 public constant MAX_FINITE_LOCK_DURATION_SECONDS = uint32(
MAX_FINITE_LOCK_DURATION_DAYS
) *
24 *
60 *
60;
/**
* @dev Calculates the DUBI to mint based on the given amount of PRPS and duration in days.
* NOTE: We trust the caller to ensure that the duration between 1 and 365.
*/
function calculateDubiToMintByDays(
uint256 amountPrps,
uint16 durationInDays
) internal pure returns (uint96) {
uint32 durationInSeconds = uint32(durationInDays) * 24 * 60 * 60;
return calculateDubiToMintBySeconds(amountPrps, durationInSeconds);
}
/**
* @dev Calculates the DUBI to mint based on the given amount of PRPS and duration in seconds.
*/
function calculateDubiToMintBySeconds(
uint256 amountPrps,
uint32 durationInSeconds
) internal pure returns (uint96) {
// NOTE: We do not use safe math for efficiency reasons
uint256 _percentage = percentage(
durationInSeconds,
MAX_FINITE_LOCK_DURATION_SECONDS,
18 // precision in WEI, 10^18
) * 4; // A full lock grants 4%, so multiply by 4.
// Multiply PRPS by the percentage and then divide by the precision (=10^8)
// from the previous step
uint256 _dubiToMint = (amountPrps * _percentage) / (1 ether * 100); // multiply by 100, because we deal with percentages
// Assert that the calculated DUBI never overflows uint96
assert(_dubiToMint < 2**96);
return uint96(_dubiToMint);
}
function calculateDubiToMintMax(uint96 amount)
internal
pure
returns (uint96)
{
return
calculateDubiToMintBySeconds(
amount,
MAX_FINITE_LOCK_DURATION_SECONDS
);
}
function calculateMintDuration(uint32 _now, uint32 lastWithdrawal)
internal
pure
returns (uint32)
{
require(lastWithdrawal > 0 && lastWithdrawal <= _now, "MINT-1");
// NOTE: we don't use any safe math here for efficiency reasons. The assert above
// is already a pretty good guarantee that nothing goes wrong. Also, all numbers involved
// are very well smaller than uint256 in the first place.
uint256 _elapsedTotal = _now - lastWithdrawal;
uint256 _proRatedYears = _elapsedTotal / SECONDS_PER_MONTH / 12;
uint256 _elapsedInYear = _elapsedTotal %
MAX_FINITE_LOCK_DURATION_SECONDS;
//
// Examples (using months instead of seconds):
// calculation formula: (monthsSinceWithdrawal % 12) + (_proRatedYears * 12)
// 1) Burn after 11 months since last withdrawal (number of years = 11 / 12 + 1 = 1)
// => (11 % 12) + (years * 12) => 23 months worth of DUBI
// => 23 months
// 1) Burn after 4 months since last withdrawal (number of years = 4 / 12 + 1 = 1)
// => (4 % 12) + (years * 12) => 16 months worth of DUBI
// => 16 months
// 2) Burn 0 months after withdrawal after 4 months (number of years = 0 / 12 + 1 = 1):
// => (0 % 12) + (years * 12) => 12 months worth of DUBI (+ 4 months worth of withdrawn DUBI)
// => 16 months
// 3) Burn after 36 months since last withdrawal (number of years = 36 / 12 + 1 = 4)
// => (36 % 12) + (years * 12) => 48 months worth of DUBI
// => 48 months
// 4) Burn 1 month after withdrawal after 35 months (number of years = 1 / 12 + 1 = 1):
// => (1 % 12) + (years * 12) => 12 month worth of DUBI (+ 35 months worth of withdrawn DUBI)
// => 47 months
uint32 _mintDuration = uint32(
_elapsedInYear + _proRatedYears * MAX_FINITE_LOCK_DURATION_SECONDS
);
return _mintDuration;
}
function percentage(
uint256 numerator,
uint256 denominator,
uint256 precision
) internal pure returns (uint256) {
return
((numerator * (uint256(10)**(precision + 1))) / denominator + 5) /
uint256(10);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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 Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Token agnostic fuel struct that is passed around when the fuel is burned by a different (token) contract.
// The contract has to explicitely support the desired token that should be burned.
struct TokenFuel {
// A token alias that must be understood by the target contract
uint8 tokenAlias;
uint96 amount;
}
/**
* @dev Extends the interface of the ERC20 standard as defined in the EIP with
* `boostedTransferFrom` to perform transfers without having to rely on an allowance.
*/
interface IBoostableERC20 {
// ERC20
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
// Extension
/**
* @dev Moves `amount` tokens from `sender` to `recipient`.
*
* If the caller is known by the callee, then the implementation should skip approval checks.
* Also accepts a data payload, similar to ERC721's `safeTransferFrom` to pass arbitrary data.
*
*/
function boostedTransferFrom(
address sender,
address recipient,
uint256 amount,
bytes calldata data
) external returns (bool);
/**
* @dev Burns `fuel` from `from`.
*/
function burnFuel(address from, TokenFuel memory fuel) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./Boostable.sol";
import "./BoostableLib.sol";
/**
* @dev EIP712 boostable primitives related to ERC20 for the Purpose domain
*/
abstract contract BoostableERC20 is Boostable {
/**
* @dev A struct representing the payload of the ERC20 `boostedSend` function.
*/
struct BoostedSend {
uint8 tag;
address sender;
address recipient;
uint256 amount;
bytes data;
BoosterFuel fuel;
BoosterPayload boosterPayload;
}
/**
* @dev A struct representing the payload of the ERC20 `boostedBurn` function.
*/
struct BoostedBurn {
uint8 tag;
address account;
uint256 amount;
bytes data;
BoosterFuel fuel;
BoosterPayload boosterPayload;
}
uint8 internal constant BOOST_TAG_SEND = 0;
uint8 internal constant BOOST_TAG_BURN = 1;
bytes32 internal constant BOOSTED_SEND_TYPEHASH = keccak256(
"BoostedSend(uint8 tag,address sender,address recipient,uint256 amount,bytes data,BoosterFuel fuel,BoosterPayload boosterPayload)BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)"
);
bytes32 internal constant BOOSTED_BURN_TYPEHASH = keccak256(
"BoostedBurn(uint8 tag,address account,uint256 amount,bytes data,BoosterFuel fuel,BoosterPayload boosterPayload)BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)"
);
constructor(address optIn) public Boostable(optIn) {}
/**
* @dev Returns the hash of `boostedSend`.
*/
function hashBoostedSend(BoostedSend memory send, address booster)
internal
view
returns (bytes32)
{
return
BoostableLib.hashWithDomainSeparator(
_DOMAIN_SEPARATOR,
keccak256(
abi.encode(
BOOSTED_SEND_TYPEHASH,
BOOST_TAG_SEND,
send.sender,
send.recipient,
send.amount,
keccak256(send.data),
BoostableLib.hashBoosterFuel(send.fuel),
BoostableLib.hashBoosterPayload(
send.boosterPayload,
booster
)
)
)
);
}
/**
* @dev Returns the hash of `boostedBurn`.
*/
function hashBoostedBurn(BoostedBurn memory burn, address booster)
internal
view
returns (bytes32)
{
return
BoostableLib.hashWithDomainSeparator(
_DOMAIN_SEPARATOR,
keccak256(
abi.encode(
BOOSTED_BURN_TYPEHASH,
BOOST_TAG_BURN,
burn.account,
burn.amount,
keccak256(burn.data),
BoostableLib.hashBoosterFuel(burn.fuel),
BoostableLib.hashBoosterPayload(
burn.boosterPayload,
booster
)
)
)
);
}
/**
* @dev Tries to interpret the given boosterMessage and
* return it's hash plus creation timestamp.
*/
function decodeAndHashBoosterMessage(
address targetBooster,
bytes memory boosterMessage
) external override view returns (bytes32, uint64) {
require(boosterMessage.length > 0, "PB-7");
uint8 tag = _readBoosterTag(boosterMessage);
if (tag == BOOST_TAG_SEND) {
BoostedSend memory send = abi.decode(boosterMessage, (BoostedSend));
return (
hashBoostedSend(send, targetBooster),
send.boosterPayload.timestamp
);
}
if (tag == BOOST_TAG_BURN) {
BoostedBurn memory burn = abi.decode(boosterMessage, (BoostedBurn));
return (
hashBoostedBurn(burn, targetBooster),
burn.boosterPayload.timestamp
);
}
// Unknown tag, so just return an empty result
return ("", 0);
}
}
// 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 "./ProtectedBoostable.sol";
/**
* @dev Purpose Boostable primitives using the EIP712 standard
*/
abstract contract Boostable is ProtectedBoostable {
// "Purpose", "Dubi" and "Hodl" are all under the "Purpose" umbrella
constructor(address optIn)
public
ProtectedBoostable(
optIn,
keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256("Purpose"),
keccak256("1"),
_getChainId(),
address(this)
)
)
)
{}
// Fuel alias constants - used when fuel is burned from external contract calls
uint8 internal constant TOKEN_FUEL_ALIAS_UNLOCKED_PRPS = 0;
uint8 internal constant TOKEN_FUEL_ALIAS_LOCKED_PRPS = 1;
uint8 internal constant TOKEN_FUEL_ALIAS_DUBI = 2;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
struct BoosterFuel {
uint96 dubi;
uint96 unlockedPrps;
uint96 lockedPrps;
uint96 intrinsicFuel;
}
struct BoosterPayload {
address booster;
uint64 timestamp;
uint64 nonce;
// Fallback for 'personal_sign' when e.g. using hardware wallets that don't support
// EIP712 signing (yet).
bool isLegacySignature;
}
// Library for Boostable hash functions that are completely inlined.
library BoostableLib {
bytes32 private constant BOOSTER_PAYLOAD_TYPEHASH = keccak256(
"BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)"
);
bytes32 internal constant BOOSTER_FUEL_TYPEHASH = keccak256(
"BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)"
);
/**
* @dev Returns the hash of the packed DOMAIN_SEPARATOR and `messageHash` and is used for verifying
* a signature.
*/
function hashWithDomainSeparator(
bytes32 domainSeparator,
bytes32 messageHash
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked("\x19\x01", domainSeparator, messageHash)
);
}
/**
* @dev Returns the hash of `payload` using the provided booster (i.e. `msg.sender`).
*/
function hashBoosterPayload(BoosterPayload memory payload, address booster)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
BOOSTER_PAYLOAD_TYPEHASH,
booster,
payload.timestamp,
payload.nonce,
payload.isLegacySignature
)
);
}
function hashBoosterFuel(BoosterFuel memory fuel)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
BOOSTER_FUEL_TYPEHASH,
fuel.dubi,
fuel.unlockedPrps,
fuel.lockedPrps,
fuel.intrinsicFuel
)
);
}
/**
* @dev Returns the tag found in the given `boosterMessage`.
*/
function _readBoosterTag(bytes memory boosterMessage)
internal
pure
returns (uint8)
{
// The tag is either the 32th byte or the 64th byte depending on whether
// the booster message contains dynamic bytes or not.
//
// If it contains a dynamic byte array, then the first word points to the first
// data location.
//
// Therefore, we read the 32th byte and check if it's >= 32 and if so,
// simply read the (32 + first word)th byte to get the tag.
//
// This imposes a limit on the number of tags we can support (<32), but
// given that it is very unlikely for so many tags to exist it is fine.
//
// Read the 32th byte to get the tag, because it is a uint8 padded to 32 bytes.
// i.e.
// -----------------------------------------------------------------v
// 0x0000000000000000000000000000000000000000000000000000000000000001
// ...
//
uint8 tag = uint8(boosterMessage[31]);
if (tag >= 32) {
// Read the (32 + tag) byte. E.g. if tag is 32, then we read the 64th:
// --------------------------------------------------------------------
// 0x0000000000000000000000000000000000000000000000000000000000000020 |
// 0000000000000000000000000000000000000000000000000000000000000001 <
// ...
//
tag = uint8(boosterMessage[31 + tag]);
}
return tag;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./EIP712Boostable.sol";
import "./IOptIn.sol";
import "./ProtectedBoostableLib.sol";
abstract contract ProtectedBoostable is EIP712Boostable {
//---------------------------------------------------------------
// State for non-boosted operations while opted-in and the OPT_IN permaboost is active
//---------------------------------------------------------------
uint256 private constant MAX_PENDING_OPS = 25;
// A mapping of account to an opCounter.
mapping(address => OpCounter) internal _opCounters;
// A mapping of account to an array containing all it's pending ops.
mapping(address => OpHandle[]) internal _pendingOpsByAddress;
// A mapping of keccak256(address,opId) to a struct holding metadata like the associated user account and creation timestamp.
mapping(bytes32 => OpMetadata) internal _opMetadata;
// Event that is emitted whenever a pending op is created
// NOTE: returning an OpHandle in the event flattens it into an array for some reason
// i.e. emit PendingOp(0x123.., OpHandle(1, 0)) => { from: 0x123, opHandle: ['1', '0']}
event PendingOp(address from, uint64 opId, uint8 opType);
// Event that is emitted whenever a pending op is finalized
event FinalizedOp(address from, uint64 opId, uint8 opType);
// Event that is emitted whenever a pending op is reverted
event RevertedOp(address from, uint64 opId, uint8 opType);
constructor(address optIn, bytes32 domainSeparator)
public
EIP712Boostable(optIn, domainSeparator)
{}
//---------------------------------------------------------------
// Pending ops
//---------------------------------------------------------------
/**
* @dev Returns the metadata of an op. Returns a zero struct if it doesn't exist.
*/
function getOpMetadata(address user, uint64 opId)
public
virtual
view
returns (OpMetadata memory)
{
return _opMetadata[_getOpKey(user, opId)];
}
/**
* @dev Returns the metadata of an op. Returns a zero struct if it doesn't exist.
*/
function getOpCounter(address user)
public
virtual
view
returns (OpCounter memory)
{
return _opCounters[user];
}
/**
* @dev Returns the metadata of an op. Reverts if it doesn't exist or
* the opType mismatches.
*/
function safeGetOpMetadata(address user, OpHandle memory opHandle)
public
virtual
view
returns (OpMetadata memory)
{
OpMetadata storage metadata = _opMetadata[_getOpKey(
user,
opHandle.opId
)];
// If 'createdAt' is zero, then it's non-existent for us
require(metadata.createdAt > 0, "PB-1");
require(metadata.opType == opHandle.opType, "PB-2");
return metadata;
}
/**
* @dev Get the next op id for `user`
*/
function _getNextOpId(address user) internal returns (uint64) {
OpCounter storage counter = _opCounters[user];
// NOTE: we always increase by 1, so it cannot overflow as long as this
// is the only place increasing the counter.
uint64 nextOpId = counter.value + 1;
// This also updates the nextFinalize/Revert values
if (counter.nextFinalize == 0) {
// Only gets updated if currently pointing to "nothing", because FIFO
counter.nextFinalize = nextOpId;
}
// nextRevert is always updated to the new opId, because LIFO
counter.nextRevert = nextOpId;
counter.value = nextOpId;
// NOTE: It is safe to downcast to uint64 since it's practically impossible to overflow.
return nextOpId;
}
/**
* @dev Creates a new opHandle with the given type for `user`.
*/
function _createNewOpHandle(
IOptIn.OptInStatus memory optInStatus,
address user,
uint8 opType
) internal virtual returns (OpHandle memory) {
uint64 nextOpId = _getNextOpId(user);
OpHandle memory opHandle = OpHandle({opId: nextOpId, opType: opType});
// NOTE: we have a hard limit of 25 pending OPs and revert if that
// limit is exceeded.
require(_pendingOpsByAddress[user].length < MAX_PENDING_OPS, "PB-3");
address booster = optInStatus.optedInTo;
_pendingOpsByAddress[user].push(opHandle);
_opMetadata[_getOpKey(user, nextOpId)] = OpMetadata({
createdAt: uint64(block.timestamp),
booster: booster,
opType: opType
});
return opHandle;
}
/**
* @dev Delete the given `opHandle` from `user`.
*/
function _deleteOpHandle(address user, OpHandle memory opHandle)
internal
virtual
{
OpHandle[] storage _opHandles = _pendingOpsByAddress[user];
OpCounter storage opCounter = _opCounters[user];
ProtectedBoostableLib.deleteOpHandle(
user,
opHandle,
_opHandles,
opCounter,
_opMetadata
);
}
/**
* @dev Assert that the caller is allowed to finalize a pending op.
*
* Returns the user and createdAt timestamp of the op on success in order to
* save some gas by minimizing redundant look-ups.
*/
function _assertCanFinalize(address user, OpHandle memory opHandle)
internal
returns (uint64)
{
OpMetadata memory metadata = safeGetOpMetadata(user, opHandle);
uint64 createdAt = metadata.createdAt;
// First check if the user is still opted-in. If not, then anyone
// can finalize since it is no longer associated with the original booster.
IOptIn.OptInStatus memory optInStatus = getOptInStatus(user);
if (!optInStatus.isOptedIn) {
return createdAt;
}
// Revert if not FIFO order
_assertFinalizeFIFO(user, opHandle.opId);
return ProtectedBoostableLib.assertCanFinalize(metadata, optInStatus);
}
/**
* @dev Asserts that the caller (msg.sender) is allowed to revert a pending operation.
* The caller must be opted-in by user and provide a valid signature from the user
* that hasn't expired yet.
*/
function _assertCanRevert(
address user,
OpHandle memory opHandle,
uint64 opTimestamp,
bytes memory boosterMessage,
Signature memory signature
) internal {
// Revert if not LIFO order
_assertRevertLIFO(user, opHandle.opId);
IOptIn.OptInStatus memory optInStatus = getOptInStatus(user);
require(
optInStatus.isOptedIn && msg.sender == optInStatus.optedInTo,
"PB-6"
);
// In order to verify the boosterMessage, we need the hash and timestamp of when it
// was signed. To interpret the boosterMessage, consult all available hasher contracts and
// take the first non-zero result.
address[] memory hasherContracts = _getHasherContracts();
// Call external library function, which performs the actual assertion. The reason
// why it is not inlined, is that the need to reduce bytecode size.
ProtectedBoostableLib.verifySignatureForRevert(
user,
opTimestamp,
optInStatus,
boosterMessage,
hasherContracts,
signature
);
}
function _getHasherContracts() internal virtual returns (address[] memory);
/**
* @dev Asserts that the given opId is the next to be finalized for `user`.
*/
function _assertFinalizeFIFO(address user, uint64 opId) internal virtual {
OpCounter storage counter = _opCounters[user];
require(counter.nextFinalize == opId, "PB-9");
}
/**
* @dev Asserts that the given opId is the next to be reverted for `user`.
*/
function _assertRevertLIFO(address user, uint64 opId) internal virtual {
OpCounter storage counter = _opCounters[user];
require(counter.nextRevert == opId, "PB-10");
}
/**
* @dev Prepare an op revert.
* - Asserts that the caller is allowed to revert the given op
* - Deletes the op handle to minimize risks of reentrancy
*/
function _prepareOpRevert(
address user,
OpHandle memory opHandle,
bytes memory boosterMessage,
Signature memory signature
) internal {
OpMetadata memory metadata = safeGetOpMetadata(user, opHandle);
_assertCanRevert(
user,
opHandle,
metadata.createdAt,
boosterMessage,
signature
);
// Delete opHandle, which prevents reentrancy since `safeGetOpMetadata`
// will fail afterwards.
_deleteOpHandle(user, opHandle);
}
/**
* @dev Returns the hash of (user, opId) which is used as a look-up
* key in the `_opMetadata` mapping.
*/
function _getOpKey(address user, uint64 opId)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(user, opId));
}
/**
* @dev Deriving contracts can override this function to accept a boosterMessage for a given booster and
* interpret it into a hash and timestamp.
*/
function decodeAndHashBoosterMessage(
address targetBooster,
bytes memory boosterMessage
) external virtual view returns (bytes32, uint64) {}
/**
* @dev Returns the tag found in the given `boosterMesasge`.
*/
function _readBoosterTag(bytes memory boosterMessage)
internal
pure
returns (uint8)
{
// The tag is either the 32th byte or the 64th byte depending on whether
// the booster message contains dynamic bytes or not.
//
// If it contains a dynamic byte array, then the first word points to the first
// data location.
//
// Therefore, we read the 32th byte and check if it's >= 32 and if so,
// simply read the (32 + first word)th byte to get the tag.
//
// This imposes a limit on the number of tags we can support (<32), but
// given that it is very unlikely for so many tags to exist it is fine.
//
// Read the 32th byte to get the tag, because it is a uint8 padded to 32 bytes.
// i.e.
// -----------------------------------------------------------------v
// 0x0000000000000000000000000000000000000000000000000000000000000001
// ...
//
uint8 tag = uint8(boosterMessage[31]);
if (tag >= 32) {
// Read the (32 + tag) byte. E.g. if tag is 32, then we read the 64th:
// --------------------------------------------------------------------
// 0x0000000000000000000000000000000000000000000000000000000000000020 |
// 0000000000000000000000000000000000000000000000000000000000000001 <
// ...
//
tag = uint8(boosterMessage[31 + tag]);
}
return tag;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "./IOptIn.sol";
import "./BoostableLib.sol";
import "./IBoostableERC20.sol";
/**
* @dev Boostable base contract
*
* All deriving contracts are expected to implement EIP712 for the message signing.
*
*/
abstract contract EIP712Boostable {
using ECDSA for bytes32;
// solhint-disable-next-line var-name-mixedcase
IOptIn internal immutable _OPT_IN;
// solhint-disable-next-line var-name-mixedcase
bytes32 internal immutable _DOMAIN_SEPARATOR;
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 private constant BOOSTER_PAYLOAD_TYPEHASH = keccak256(
"BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)"
);
bytes32 internal constant BOOSTER_FUEL_TYPEHASH = keccak256(
"BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)"
);
// The boost fuel is capped to 10 of the respective token that will be used for payment.
uint96 internal constant MAX_BOOSTER_FUEL = 10 ether;
// A magic booster permission prefix
bytes6 private constant MAGIC_BOOSTER_PERMISSION_PREFIX = "BOOST-";
constructor(address optIn, bytes32 domainSeparator) public {
_OPT_IN = IOptIn(optIn);
_DOMAIN_SEPARATOR = domainSeparator;
}
// A mapping of mappings to keep track of used nonces by address to
// protect against replays. Each 'Boostable' contract maintains it's own
// state for nonces.
mapping(address => uint64) private _nonces;
//---------------------------------------------------------------
function getNonce(address account) external virtual view returns (uint64) {
return _nonces[account];
}
function getOptInStatus(address account)
internal
view
returns (IOptIn.OptInStatus memory)
{
return _OPT_IN.getOptInStatus(account);
}
/**
* @dev Called by every 'boosted'-function to ensure that `msg.sender` (i.e. a booster) is
* allowed to perform the call for `from` (the origin) by verifying that `messageHash`
* has been signed by `from`. Additionally, `from` provides a nonce to prevent
* replays. Boosts cannot be verified out of order.
*
* @param from the address that the boost is made for
* @param messageHash the reconstructed message hash based on the function input
* @param payload the booster payload
* @param signature the signature of `from`
*/
function verifyBoost(
address from,
bytes32 messageHash,
BoosterPayload memory payload,
Signature memory signature
) internal {
uint64 currentNonce = _nonces[from];
require(currentNonce == payload.nonce - 1, "AB-1");
_nonces[from] = currentNonce + 1;
_verifyBoostWithoutNonce(from, messageHash, payload, signature);
}
/**
* @dev Verify a boost without verifying the nonce.
*/
function _verifyBoostWithoutNonce(
address from,
bytes32 messageHash,
BoosterPayload memory payload,
Signature memory signature
) internal view {
// The sender must be the booster specified in the payload
require(msg.sender == payload.booster, "AB-2");
(bool isOptedInToSender, uint256 optOutPeriod) = _OPT_IN.isOptedInBy(
msg.sender,
from
);
// `from` must be opted-in to booster
require(isOptedInToSender, "AB-3");
// The given timestamp must not be greater than `block.timestamp + 1 hour`
// and at most `optOutPeriod(booster)` seconds old.
uint64 _now = uint64(block.timestamp);
uint64 _optOutPeriod = uint64(optOutPeriod);
bool notTooFarInFuture = payload.timestamp <= _now + 1 hours;
bool belowMaxAge = true;
// Calculate the absolute difference. Because of the small tolerance, `payload.timestamp`
// may be greater than `_now`:
if (payload.timestamp <= _now) {
belowMaxAge = _now - payload.timestamp <= _optOutPeriod;
}
// Signature must not be expired
require(notTooFarInFuture && belowMaxAge, "AB-4");
// NOTE: Currently, hardware wallets (e.g. Ledger, Trezor) do not support EIP712 signing (specifically `signTypedData_v4`).
// However, a user can still sign the EIP712 hash with the caveat that it's signed using `personal_sign` which prepends
// the prefix '"\x19Ethereum Signed Message:\n" + len(message)'.
//
// To still support that, we add the prefix to the hash if `isLegacySignature` is true.
if (payload.isLegacySignature) {
messageHash = messageHash.toEthSignedMessageHash();
}
// Valid, if the recovered address from `messageHash` with the given `signature` matches `from`.
address signer = ecrecover(
messageHash,
signature.v,
signature.r,
signature.s
);
if (!payload.isLegacySignature && signer != from) {
// As a last resort we try anyway, in case the caller simply forgot the `isLegacySignature` flag.
signer = ecrecover(
messageHash.toEthSignedMessageHash(),
signature.v,
signature.r,
signature.s
);
}
require(from == signer, "AB-5");
}
/**
* @dev Returns the hash of `payload` using the provided booster (i.e. `msg.sender`).
*/
function hashBoosterPayload(BoosterPayload memory payload, address booster)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
BOOSTER_PAYLOAD_TYPEHASH,
booster,
payload.timestamp,
payload.nonce
)
);
}
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;
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
interface IOptIn {
struct OptInStatus {
bool isOptedIn;
bool permaBoostActive;
address optedInTo;
uint32 optOutPeriod;
}
function getOptInStatusPair(address accountA, address accountB)
external
view
returns (OptInStatus memory, OptInStatus memory);
function getOptInStatus(address account)
external
view
returns (OptInStatus memory);
function isOptedInBy(address _sender, address _account)
external
view
returns (bool, uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "./IOptIn.sol";
struct OpHandle {
uint8 opType;
uint64 opId;
}
struct OpMetadata {
uint8 opType; // the operation type
uint64 createdAt; // the creation timestamp of an op
address booster; // the booster at the time of when the op has been created
}
struct OpCounter {
// The current value of the counter
uint64 value;
// Contains the opId that is to be finalized next - i.e. FIFO order
uint64 nextFinalize;
// Contains the opId that is to be reverted next - i.e. LIFO order
uint64 nextRevert;
}
// Library containing public functions for pending ops - those will never be inlined
// to reduce the bytecode size of individual contracts.
library ProtectedBoostableLib {
using ECDSA for bytes32;
function deleteOpHandle(
address user,
OpHandle memory opHandle,
OpHandle[] storage opHandles,
OpCounter storage opCounter,
mapping(bytes32 => OpMetadata) storage opMetadata
) public {
uint256 length = opHandles.length;
assert(length > 0);
uint64 minOpId; // becomes next LIFO
uint64 maxOpId; // becomes next FIFO
// Pending ops are capped to MAX_PENDING_OPS. We always perform
// MIN(length, MAX_PENDING_OPS) look-ups to do a "swap-and-pop" and
// for updating the opCounter LIFO/FIFO pointers.
for (uint256 i = 0; i < length; i++) {
uint64 currOpId = opHandles[i].opId;
if (currOpId == opHandle.opId) {
// Overwrite item at i with last
opHandles[i] = opHandles[length - 1];
// Continue, to ignore this opId when updating
// minOpId and maxOpId.
continue;
}
// Update minOpId
if (minOpId == 0 || currOpId < minOpId) {
minOpId = currOpId;
}
// Update maxOpId
if (currOpId > maxOpId) {
maxOpId = currOpId;
}
}
// Might be 0 when everything got finalized/reverted
opCounter.nextFinalize = minOpId;
// Might be 0 when everything got finalized/reverted
opCounter.nextRevert = maxOpId;
// Remove the last item
opHandles.pop();
// Remove metadata
delete opMetadata[_getOpKey(user, opHandle.opId)];
}
function assertCanFinalize(
OpMetadata memory metadata,
IOptIn.OptInStatus memory optInStatus
) public view returns (uint64) {
// Now there are three valid scenarios remaining:
//
// - msg.sender is the original booster
// - op is expired
// - getBoosterAddress returns a different booster than the original booster
//
// In the second and third case, anyone can call finalize.
address originalBooster = metadata.booster;
if (originalBooster == msg.sender) {
return metadata.createdAt; // First case
}
address currentBooster = optInStatus.optedInTo;
uint256 optOutPeriod = optInStatus.optOutPeriod;
bool isExpired = block.timestamp >= metadata.createdAt + optOutPeriod;
if (isExpired) {
return metadata.createdAt; // Second case
}
if (currentBooster != originalBooster) {
return metadata.createdAt; // Third case
}
revert("PB-4");
}
function verifySignatureForRevert(
address user,
uint64 opTimestamp,
IOptIn.OptInStatus memory optInStatus,
bytes memory boosterMessage,
address[] memory hasherContracts,
Signature memory signature
) public {
require(hasherContracts.length > 0, "PB-12");
// Result of hasher contract call
uint64 signedAt;
bytes32 boosterHash;
bool signatureVerified;
for (uint256 i = 0; i < hasherContracts.length; i++) {
// Call into the hasher contract and take the first non-zero result.
// The contract must implement the following function:
//
// decodeAndHashBoosterMessage(
// address targetBooster,
// bytes memory boosterMessage
// )
//
// If it doesn't, then the call will fail (success=false) and we try the next one.
// If it succeeds (success = true), then we try to decode the result.
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory result) = address(hasherContracts[i])
.call(
// keccak256("decodeAndHashBoosterMessage(address,bytes)")
abi.encodeWithSelector(
0xaf6eec54,
msg.sender, /* msg.sender becomes the target booster */
boosterMessage
)
);
if (!success) {
continue;
}
// The result is exactly 2 words long = 512 bits = 64 bytes
// 32 bytes for the expected message hash
// 8 bytes (padded to 32 bytes) for the expected timestamp
if (result.length != 64) {
continue;
}
// NOTE: A contract with malintent could return any hash that we would
// try to recover against. But there is no harm done in doing so since
// the user must have signed it.
//
// However, it might return an unrelated timestamp, that the user hasn't
// signed - so it could prolong the expiry of a signature which is a valid
// concern whose risk we minimize by using also the op timestamp which guarantees
// that a signature eventually expires.
// Decode and recover signer
(boosterHash, signedAt) = abi.decode(result, (bytes32, uint64));
address signer = ecrecover(
boosterHash,
signature.v,
signature.r,
signature.s
);
if (user != signer) {
// NOTE: Currently, hardware wallets (e.g. Ledger, Trezor) do not support EIP712 signing (specifically `signTypedData_v4`).
// However, a user can still sign the EIP712 hash with the caveat that it's signed using `personal_sign` which prepends
// the prefix '"\x19Ethereum Signed Message:\n" + len(message)'.
//
// To still support that, we also add the prefix and try to use the recovered address instead:
signer = ecrecover(
boosterHash.toEthSignedMessageHash(),
signature.v,
signature.r,
signature.s
);
}
// If we recovered `user` from the signature, then we have a valid signature.
if (user == signer) {
signatureVerified = true;
break;
}
// Keep trying
}
// Revert if signature couldn't be verified with any of the returned hashes
require(signatureVerified, "PB-8");
// Lastly, the current time must not be older than:
// MIN(opTimestamp, signedAt) + optOutPeriod * 3
uint64 _now = uint64(block.timestamp);
// The maximum age is equal to whichever is lowest:
// opTimestamp + optOutPeriod * 3
// signedAt + optOutPeriod * 3
uint64 maximumAge;
if (opTimestamp > signedAt) {
maximumAge = signedAt + uint64(optInStatus.optOutPeriod * 3);
} else {
maximumAge = opTimestamp + uint64(optInStatus.optOutPeriod * 3);
}
require(_now <= maximumAge, "PB-11");
}
function _getOpKey(address user, uint64 opId)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(user, opId));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
| Transfer `amount` from `holder` to `recipient`. `msg.sender` requires an allowance >= `amount` of `holder`./ Create pending transfer if the token holder is opted-in and the permaboost is active Ignore allowances if holder is opted-in | function transferFrom(
address holder,
address recipient,
uint256 amount
) public override(IBoostableERC20, IERC20) returns (bool) {
_assertSenderRecipient(holder, recipient);
address spender = msg.sender;
IOptIn.OptInStatus memory optInStatus = getOptInStatus(holder);
if (optInStatus.isOptedIn && optInStatus.permaBoostActive) {
require(holder == spender, "ERC20-7");
_createPendingTransfer({
opType: OP_TYPE_SEND,
spender: spender,
from: holder,
to: recipient,
amount: amount,
data: "",
optInStatus: optInStatus
});
return true;
}
_approve(
holder,
spender,
_allowances[holder][spender].sub(amount, "ERC20-4")
);
return true;
}
| 491,272 |
./full_match/1/0xFcEC7556B204008e26F78Dfa0996f0Df4994a354/sources/mamasaitama.sol | make sure we capture all ETH that may or may not be sent to this contract | function claimTokens () public {
payable(marketingAddress).transfer(address(this).balance);
}
| 2,970,636 |
./full_match/4/0x208426c2B281aC34f7005A03f638F43C6489505e/sources/contracts/lib/balancer/configurable-rights-pool/libraries/SmartPoolManager.sol | External function called to make the contract update weights according to plan bPool - Core BPool the CRP is wrapping gradualUpdate - gradual update parameters from the CRP/ Do nothing if we call this when there is no update plan This loop contains external calls External calls are to math libraries or the underlying pool, so low risk Make sure it does nothing if the new and old weights are the same (saves gas) It's a degenerate case if they're all the same, but you certainly could have a plan where you only change some of the weights in the set We are decreasing the weight First get the total weight delta And the amount it should change per block = total change/number of blocks in the perioddeltaPerBlock = bdivx(weightDelta, blockPeriod); newWeight = startWeight - (blocksElapsed deltaPerBlock) We are increasing the weight First get the total weight delta And the amount it should change per block = total change/number of blocks in the perioddeltaPerBlock = bdivx(weightDelta, blockPeriod); newWeight = startWeight + (blocksElapsed deltaPerBlock) Reset to allow add/remove tokens, or manual weight updates | function pokeWeights(IBPool bPool, GradualUpdateParams storage gradualUpdate) external {
if (gradualUpdate.startBlock == 0) {
return;
}
if (block.number > gradualUpdate.endBlock) {
currentBlock = gradualUpdate.endBlock;
currentBlock = block.number;
}
uint256 blockPeriod = BalancerSafeMath.bsub(gradualUpdate.endBlock, gradualUpdate.startBlock);
uint256 blocksElapsed = BalancerSafeMath.bsub(currentBlock, gradualUpdate.startBlock);
uint256 weightDelta;
uint256 deltaPerBlock;
uint256 newWeight;
address[] memory tokens = bPool.getCurrentTokens();
for (uint256 i = 0; i < tokens.length; i++) {
if (gradualUpdate.startWeights[i] != gradualUpdate.endWeights[i]) {
if (gradualUpdate.endWeights[i] < gradualUpdate.startWeights[i]) {
weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], gradualUpdate.endWeights[i]);
deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod);
newWeight = BalancerSafeMath.bsub(
gradualUpdate.startWeights[i],
BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)
);
weightDelta = BalancerSafeMath.bsub(gradualUpdate.endWeights[i], gradualUpdate.startWeights[i]);
deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod);
newWeight = BalancerSafeMath.badd(
gradualUpdate.startWeights[i],
BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)
);
}
uint256 bal = bPool.getBalance(tokens[i]);
bPool.rebind(tokens[i], bal, newWeight);
}
}
if (block.number >= gradualUpdate.endBlock) {
gradualUpdate.startBlock = 0;
}
}
| 12,288,028 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
import "./OwnableStorage.sol";
contract Ownable{
OwnableStorage _storage;
function initialize( address storage_ ) public {
_storage = OwnableStorage(storage_);
}
modifier OnlyAdmin(){
require( _storage.isAdmin(msg.sender) );
_;
}
modifier OnlyGovernance(){
require( _storage.isGovernance( msg.sender ) );
_;
}
modifier OnlyAdminOrGovernance(){
require( _storage.isAdmin(msg.sender) || _storage.isGovernance( msg.sender ) );
_;
}
function updateAdmin( address admin_ ) public OnlyAdmin {
_storage.setAdmin(admin_);
}
function updateGovenance( address gov_ ) public OnlyAdminOrGovernance {
_storage.setGovernance(gov_);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
contract OwnableStorage {
address public _admin;
address public _governance;
constructor() payable {
_admin = msg.sender;
_governance = msg.sender;
}
function setAdmin( address account ) public {
require( isAdmin( msg.sender ));
_admin = account;
}
function setGovernance( address account ) public {
require( isAdmin( msg.sender ) || isGovernance( msg.sender ));
_admin = account;
}
function isAdmin( address account ) public view returns( bool ) {
return account == _admin;
}
function isGovernance( address account ) public view returns( bool ) {
return account == _admin;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./Ownable.sol";
// Hard Work Now! For Punkers by 0xViktor...
contract PunkRewardPool is Ownable, Initializable, ReentrancyGuard{
using SafeMath for uint;
using SafeERC20 for IERC20;
bool isStarting = false;
bool isInitialize = false;
uint constant MAX_WEIGHT = 500;
uint constant BLOCK_YEAR = 2102400;
IERC20 Punk;
uint startBlock;
address [] forges;
mapping ( address => uint ) totalSupplies;
mapping ( address => mapping( address=>uint ) ) balances;
mapping ( address => mapping( address=>uint ) ) checkPointBlocks;
mapping( address => uint ) weights;
uint weightSum;
mapping( address => uint ) distributed;
uint totalDistributed;
function initializePunkReward( address storage_, address punk_ ) public initializer {
// Hard Work Now! For Punkers by 0xViktor...
require(!isInitialize);
Ownable.initialize( storage_ );
Punk = IERC20( punk_ );
startBlock = 0;
weightSum = 0;
totalDistributed = 0;
isInitialize = true;
}
function start() public OnlyAdmin{
startBlock = block.number;
isStarting = true;
}
function addForge( address forge ) public OnlyAdminOrGovernance {
// Hard Work Now! For Punkers by 0xViktor...
require( !_checkForge( forge ), "PUNK_REWARD_POOL: Already Exist" );
forges.push( forge );
weights[ forge ] = 0;
}
function setForge( address forge, uint weight ) public OnlyAdminOrGovernance {
// Hard Work Now! For Punkers by 0xViktor...
require( _checkForge( forge ), "PUNK_REWARD_POOL: Not Exist Forge" );
( uint minWeight , uint maxWeight ) = getWeightRange( forge );
require( minWeight <= weight && weight <= maxWeight, "PUNK_REWARD_POOL: Invalid weight" );
weights[ forge ] = weight;
weightSum = 0;
for( uint i = 0 ; i < forges.length ; i++ ){
weightSum += weights[ forges[ i ] ];
}
}
function getWeightRange( address forge ) public view returns( uint, uint ){
// Hard Work Now! For Punkers by 0xViktor...
if( forges.length == 0 ) return ( 1, MAX_WEIGHT );
if( forges.length == 1 ) return ( weights[ forges[ 0 ] ], weights[ forges[ 0 ] ] );
if( weightSum == 0 ) return ( 0, MAX_WEIGHT );
uint highestWeight = 0;
uint excludeWeight = weightSum.sub( weights[ forge ] );
for( uint i = 0 ; i < forges.length ; i++ ){
if( forges[ i ] != forge && highestWeight < weights[ forges[ i ] ] ){
highestWeight = weights[ forges[ i ] ];
}
}
if( highestWeight > excludeWeight.sub( highestWeight ) ){
return ( highestWeight.sub( excludeWeight.sub( highestWeight ) ), MAX_WEIGHT < excludeWeight ? MAX_WEIGHT : excludeWeight );
}else{
return ( 0, MAX_WEIGHT < excludeWeight ? MAX_WEIGHT : excludeWeight );
}
}
function claimPunk( ) public {
// Hard Work Now! For Punkers by 0xViktor...
claimPunk( msg.sender );
}
function claimPunk( address to ) public {
// Hard Work Now! For Punkers by 0xViktor...
if( isStarting ){
for( uint i = 0 ; i < forges.length ; i++ ){
address forge = forges[i];
uint reward = getClaimPunk( forge, to );
checkPointBlocks[ forge ][ to ] = block.number;
if( reward > 0 ) Punk.safeTransfer( to, reward );
distributed[ forge ] = distributed[ forge ].add( reward );
totalDistributed = totalDistributed.add( reward );
}
}
}
function claimPunk( address forge, address to ) public nonReentrant {
// Hard Work Now! For Punkers by 0xViktor...
if( isStarting ){
uint reward = getClaimPunk( forge, to );
checkPointBlocks[ forge ][ to ] = block.number;
if( reward > 0 ) Punk.safeTransfer( to, reward );
distributed[ forge ] = distributed[ forge ].add( reward );
totalDistributed = totalDistributed.add( reward );
}
}
function staking( address forge, uint amount ) public {
// Hard Work Now! For Punkers by 0xViktor...
staking( forge, amount, msg.sender );
}
function unstaking( address forge, uint amount ) public {
// Hard Work Now! For Punkers by 0xViktor...
unstaking( forge, amount, msg.sender );
}
function staking( address forge, uint amount, address from ) public nonReentrant {
// Hard Work Now! For Punkers by 0xViktor...
require( msg.sender == from || _checkForge( msg.sender ), "REWARD POOL : NOT ALLOWD" );
claimPunk( from );
checkPointBlocks[ forge ][ from ] = block.number;
IERC20( forge ).safeTransferFrom( from, address( this ), amount );
balances[ forge ][ from ] = balances[ forge ][ from ].add( amount );
totalSupplies[ forge ] = totalSupplies[ forge ].add( amount );
}
function unstaking( address forge, uint amount, address from ) public nonReentrant {
// Hard Work Now! For Punkers by 0xViktor...
require( msg.sender == from || _checkForge( msg.sender ), "REWARD POOL : NOT ALLOWD" );
claimPunk( from );
checkPointBlocks[ forge ][ from ] = block.number;
balances[ forge ][ from ] = balances[ forge ][ from ].sub( amount );
IERC20( forge ).safeTransfer( from, amount );
totalSupplies[ forge ] = totalSupplies[ forge ].sub( amount );
}
function _checkForge( address forge ) internal view returns( bool ){
// Hard Work Now! For Punkers by 0xViktor...
bool check = false;
for( uint i = 0 ; i < forges.length ; i++ ){
if( forges[ i ] == forge ){
check = true;
break;
}
}
return check;
}
function _calcRewards( address forge, address user, uint fromBlock, uint currentBlock ) internal view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
uint balance = balances[ forge ][ user ];
if( balance == 0 ) return 0;
uint totalSupply = totalSupplies[ forge ];
uint weight = weights[ forge ];
uint startPeriod = _getPeriodFromBlock( fromBlock );
uint endPeriod = _getPeriodFromBlock( currentBlock );
if( startPeriod == endPeriod ){
uint during = currentBlock.sub( fromBlock ).mul( balance ).mul( weight ).mul( _perBlockRateFromPeriod( startPeriod ) );
return during.div( weightSum ).div( totalSupply );
}else{
uint denominator = weightSum.mul( totalSupply );
uint duringStartNumerator = _getBlockFromPeriod( startPeriod.add( 1 ) ).sub( fromBlock );
duringStartNumerator = duringStartNumerator.mul( weight ).mul( _perBlockRateFromPeriod( startPeriod ) ).mul( balance );
uint duringEndNumerator = currentBlock.sub( _getBlockFromPeriod( endPeriod ) );
duringEndNumerator = duringEndNumerator.mul( weight ).mul( _perBlockRateFromPeriod( endPeriod ) ).mul( balance );
uint duringMid = 0;
for( uint i = startPeriod.add( 1 ) ; i < endPeriod ; i++ ) {
uint numerator = BLOCK_YEAR.mul( 4 ).mul( balance ).mul( weight ).mul( _perBlockRateFromPeriod( i ) );
duringMid += numerator.div( denominator );
}
uint duringStartAmount = duringStartNumerator.div( denominator );
uint duringEndAmount = duringEndNumerator.div( denominator );
return duringStartAmount + duringMid + duringEndAmount;
}
}
function _getBlockFromPeriod( uint period ) internal view returns ( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return startBlock.add( period.sub( 1 ).mul( BLOCK_YEAR ).mul( 4 ) );
}
function _getPeriodFromBlock( uint blockNumber ) internal view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return blockNumber.sub( startBlock ).div( BLOCK_YEAR.mul( 4 ) ).add( 1 );
}
function _perBlockRateFromPeriod( uint period ) internal view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
uint totalDistribute = Punk.balanceOf( address( this ) ).add( totalDistributed ).div( period.mul( 2 ) );
uint perBlock = totalDistribute.div( BLOCK_YEAR.mul( 4 ) );
return perBlock;
}
function getClaimPunk( address to ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
uint reward = 0;
for( uint i = 0 ; i < forges.length ; i++ ){
reward += getClaimPunk( forges[ i ], to );
}
return reward;
}
function getClaimPunk( address forge, address to ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
uint checkPointBlock = checkPointBlocks[ forge ][ to ];
if( checkPointBlock <= getStartBlock() ){
checkPointBlock = getStartBlock();
}
return checkPointBlock > startBlock ? _calcRewards( forge, to, checkPointBlock, block.number ) : 0;
}
function getWeightSum() public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return weightSum;
}
function getWeight( address forge ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return weights[ forge ];
}
function getTotalDistributed( ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return totalDistributed;
}
function getDistributed( address forge ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return distributed[ forge ];
}
function getAllocation( ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return _perBlockRateFromPeriod( _getPeriodFromBlock( block.number ) );
}
function getAllocation( address forge ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return getAllocation( ).mul( weights[ forge ] ).div( weightSum );
}
function staked( address forge, address account ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return balances[ forge ][ account ];
}
function getTotalReward() public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return Punk.balanceOf( address( this ) ).add( totalDistributed );
}
function getStartBlock() public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return startBlock;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
import "../../utils/Address.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* 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;
}
}
}
| Hard Work Now! For Punkers by 0xViktor... | function getWeight( address forge ) public view returns( uint ){
return weights[ forge ];
}
| 1,144,744 |
/*
_..._ . __ __ ___ _..._
.' '. .'| | |/ `.' `. .' '.
. .-. .< | | .-. .-. ' . .-. .
| ' ' | | | | | | | | | __ | ' ' |
_ _ | | | | | | .'''-. _ _ | | | | | | .:--.'. | | | |
| ' / | | | | | | |/.'''. \ | ' / || | | | | |/ | \ | | | | |
.' | .' | | | | | | / | | .' | .' || | | | | |`" __ | | | | | |
/ | / | | | | | | | | | / | / ||__| |__| |__| .'.''| | | | | |
| `'. | | | | | | | | | | `'. | / / | |_| | | |
' .'| '/| | | | | '. | '.' .'| '/ \ \._,\ '/| | | |
`-' `--' '--' '--' '---' '---'`-' `--' `--' `" '--' '--'
_..._ .-'''-. .-'''-. .-'''-.
.-'_..._''. ' _ \ ' _ \ ' _ \
.' .' '.\/ /` '. \ __ __ ___ _________ _...._ / /` '. \ .--. .--. / /` '. \ _..._
/ .' . | \ ' | |/ `.' `.\ |.' '-. . | \ ' |__| |__|. | \ ' .' '.
. ' | ' | '| .-. .-. '\ .'```'. '. | ' | ' .--. .| .--.| ' | '. .-. .
| | \ \ / / | | | | | | \ | \ \\ \ / / | | .' |_ | |\ \ / / | ' ' |
| | `. ` ..' / | | | | | | | | | | `. ` ..' / _ | | .' || | `. ` ..' / | | | | _
. ' '-...-'` | | | | | | | \ / . '-...-'`.' | | |'--. .-'| | '-...-'` | | | | .' |
\ '. . | | | | | | | |\`'-.-' .' . | /| | | | | | | | | | . | /
'. `._____.-'/ |__| |__| |__| | | '-....-'` .'.'| |//|__| | | |__| | | | | .'.'| |//
`-.______ / .' '. .'.'.-' / | '.' | | | |.'.'.-' /
` '-----------' .' \_.' | / | | | |.' \_.'
`'-' '--' '--'
www.unhuman.xyz
by Damjanski + Steve Snygin
*/
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (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() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// 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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: IERC2981.sol
pragma solidity ^0.8.0;
///
/// @dev Interface for the NFT Royalty Standard
///
interface IERC2981 is IERC165 {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
/// _registerInterface(_INTERFACE_ID_ERC2981);
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view returns (
address receiver,
uint256 royaltyAmount
);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
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;
bool public mintingActive;
// 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 'data:application/json;base64,';
}
/**
* @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 {}
}
library Base64 {
string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000"
hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000"
hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000"
hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE_ENCODE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
// read 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// write 4 characters
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
function decode(string memory _data) internal pure returns (bytes memory) {
bytes memory data = bytes(_data);
if (data.length == 0) return new bytes(0);
require(data.length % 4 == 0, "invalid base64 decoder input");
// load the table into memory
bytes memory table = TABLE_DECODE;
// every 4 characters represent 3 bytes
uint256 decodedLen = (data.length / 4) * 3;
// add some extra buffer at the end required for the writing
bytes memory result = new bytes(decodedLen + 32);
assembly {
// padding with '='
let lastBytes := mload(add(data, mload(data)))
if eq(and(lastBytes, 0xFF), 0x3d) {
decodedLen := sub(decodedLen, 1)
if eq(and(lastBytes, 0xFFFF), 0x3d3d) {
decodedLen := sub(decodedLen, 1)
}
}
// set the actual output length
mstore(result, decodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 4 characters at a time
for {} lt(dataPtr, endPtr) {}
{
// read 4 characters
dataPtr := add(dataPtr, 4)
let input := mload(dataPtr)
// write 3 bytes
let output := add(
add(
shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)),
shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))),
add(
shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)),
and(mload(add(tablePtr, and( input , 0xFF))), 0xFF)
)
)
mstore(resultPtr, shl(232, output))
resultPtr := add(resultPtr, 3)
}
}
return result;
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File: Token.sol
pragma solidity ^0.8.0;
/**
* @title Sample NFT contract
* @dev Extends ERC-721 NFT contract and implements ERC-2981
*/
contract UNHUMAN is Ownable, ERC721URIStorage {
// Keep a mapping of token ids and corresponding IPFS hashes
mapping(string => uint8) hashes;
// Maximum amounts of mintable tokens
uint256 public constant MAX_SUPPLY = 777;
// Address of the royalties recipient
address private _royaltiesReceiver;
// Percentage of each sale to pay as royalties
uint256 public constant royaltiesPercentage = 10;
mapping (address => uint) public artBalance;
mapping (uint => bytes32) public storedData;
// Events
event Mint(uint256 tokenId, address recipient);
constructor(address initialRoyaltiesReceiver) ERC721("UNHUMAN COMPOSITIONS", "UNHUMAN") {
_royaltiesReceiver = initialRoyaltiesReceiver;
artBalance[address(this)] = MAX_SUPPLY;
}
/** Overrides ERC-721's _baseURI function */
function _baseURI() internal view override returns (string memory) {
return 'data:application/json;base64,';
}
function _beforeTokenTransfer(address from, address to, uint256 amount)
internal override(ERC721) {
super._beforeTokenTransfer(from, to, amount);
}
function _burn(uint256 tokenId)
internal override(ERC721URIStorage) {
super._burn(tokenId);
}
/// @notice Getter function for _royaltiesReceiver
/// @return the address of the royalties recipient
function royaltiesReceiver() external returns(address) {
return _royaltiesReceiver;
}
/// @notice Changes the royalties' recipient address (in case rights are
/// transferred for instance)
/// @param newRoyaltiesReceiver - address of the new royalties recipient
function setRoyaltiesReceiver(address newRoyaltiesReceiver)
external onlyOwner {
require(newRoyaltiesReceiver != _royaltiesReceiver); // dev: Same address
_royaltiesReceiver = newRoyaltiesReceiver;
}
/// @notice Returns a token's URI
/// @dev See {IERC721Metadata-tokenURI}.
/// @param tokenId - the id of the token whose URI to return
/// @return a string containing an URI pointing to the token's ressource
function tokenURI(uint256 tokenId)
public view override(ERC721URIStorage)
returns (string memory) {
return super.tokenURI(tokenId);
}
/// @notice Informs callers that this contract supports ERC2981
function supportsInterface(bytes4 interfaceId)
public view override(ERC721)
returns (bool) {
return interfaceId == type(IERC2981).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @notice Returns all the tokens owned by an address
/// @param _owner - the address to query
/// @return ownerTokens - an array containing the ids of all tokens
/// owned by the address
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _value sale price
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view
returns (address receiver, uint256 royaltyAmount) {
uint256 _royalties = (_salePrice * royaltiesPercentage) / 100;
return (_royaltiesReceiver, _royalties);
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
function concatenate(string memory a,string memory b) public pure returns (string memory){
return string(abi.encodePacked(a,'',b));
}
function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {
uint8 i = 0;
while(i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
function mint(string calldata artData, uint objects, uint noColors, bytes32[] memory colors) external payable {
string memory json;
string memory attributes;
require(mintingActive || msg.sender == owner(), "Minting is paused");
require(msg.value >= 100000000000000000 wei, "You must pay at least 0.1 Eth per art");
require(artBalance[address(this)]+1 >= 1, "Not enough art in stock to complete this purchase");
_safeMint(msg.sender, MAX_SUPPLY-artBalance[address(this)]+1);
for (uint i=0; i < noColors; i++){
attributes = concatenate(attributes, ',{"Trait_type":"Color_');
attributes = concatenate(attributes, uint2str(i+1));
attributes = concatenate(attributes, '","value":"');
attributes = concatenate(attributes, bytes32ToString(colors[i]));
attributes = concatenate(attributes, '"}');
}
json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"description":"Unhuman Compositions is a collection of 777 generative NFTs by Damjanski - each generated when you take a photo. Each NFT is fully stored and rendered on chain.","external_url":"http://unhuman.xyz"',',',
'"name": "Unhuman Composition ',
uint2str(MAX_SUPPLY-artBalance[address(this)]+1),'",',
'"image": "',
artData, '",',
'"attributes":[',
'{"Trait_type":"Property_1","value":"',
uint2str(objects),
' Objects"},',
'{"Trait_type":"Property_2","value":"',
uint2str(noColors),
' Colors"}',
attributes,
']}'
)
)
)
);
_setTokenURI(MAX_SUPPLY-artBalance[address(this)]+1, json);
artBalance[address(this)] -= 1;
artBalance[msg.sender] += 1;
}
function setMintingActive(bool isMintingActive) public onlyOwner {
mintingActive = isMintingActive;
}
function withdraw(uint amount) onlyOwner public returns(bool) {
require(amount <= address(this).balance);
address someone = msg.sender;
payable(someone).transfer(amount);
return true;
}
} | Called with the sale price to determine how much royalty is owed and to whom. _tokenId - the NFT asset queried for royalty information _salePrice - sale price of the NFT asset specified by _tokenId return receiver - address of who should be sent the royalty payment return royaltyAmount - the royalty payment amount for _value sale price | function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view
returns (address receiver, uint256 royaltyAmount) {
uint256 _royalties = (_salePrice * royaltiesPercentage) / 100;
return (_royaltiesReceiver, _royalties);
}
| 9,871,429 |
./full_match/1/0xb2FF612F584b078f61cE9faB56F24969bf71E382/sources/contracts/CreateToken/Meter/StandardToken.sol | require(_owner == _msgSender(), "Only owner is allowed to modify blacklist."); | function blacklistUpdate(address user, bool value)
public
virtual
onlyOwner
canBlacklist
{
_blacklist[user] = value;
emit BlacklistUpdated(user, value);
}
| 4,869,436 |
// File: ERC20.sol
pragma solidity ^0.5.10;
/// @title ERC20 interface is a subset of the ERC20 specification.
/// @notice see https://github.com/ethereum/EIPs/issues/20
interface ERC20 {
function allowance(address _owner, address _spender) external view returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function balanceOf(address _who) external view returns (uint256);
function totalSupply() external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
}
// File: 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) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: Address.sol
pragma solidity ^0.5.0;
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: SafeERC20.sol
/**
* The MIT License (MIT)
*
* Copyright (c) 2016-2019 zOS Global Limited
*
* 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.5.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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(ERC20 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(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
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(ERC20 token, bytes memory data) internal {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: transferrable.sol
/**
* Transferrable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title SafeTransfer, allowing contract to withdraw tokens accidentally sent to itself
contract Transferrable {
using SafeERC20 for ERC20;
/// @dev This function is used to move tokens sent accidentally to this contract method.
/// @dev The owner can chose the new destination address
/// @param _to is the recipient's address.
/// @param _asset is the address of an ERC20 token or 0x0 for ether.
/// @param _amount is the amount to be transferred in base units.
function _safeTransfer(address payable _to, address _asset, uint _amount) internal {
// address(0) is used to denote ETH
if (_asset == address(0)) {
_to.transfer(_amount);
} else {
ERC20(_asset).safeTransfer(_to, _amount);
}
}
}
// File: balanceable.sol
/**
* Balanceable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title Balanceable - This is a contract used to get a balance
contract Balanceable {
/// @dev This function is used to get a balance
/// @param _address of which balance we are trying to ascertain
/// @param _asset is the address of an ERC20 token or 0x0 for ether.
/// @return balance associated with an address, for any token, in the wei equivalent
function _balance(address _address, address _asset) internal view returns (uint) {
if (_asset != address(0)) {
return ERC20(_asset).balanceOf(_address);
} else {
return _address.balance;
}
}
}
// File: burner.sol
/**
* IBurner - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
// The BurnerToken interface is the interface to a token contract which
// provides the total burnable supply for the TokenHolder contract.
interface IBurner {
function currentSupply() external view returns (uint);
}
// File: ownable.sol
/**
* Ownable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title Ownable has an owner address and provides basic authorization control functions.
/// This contract is modified version of the MIT OpenZepplin Ownable contract
/// This contract allows for the transferOwnership operation to be made impossible
/// https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol
contract Ownable {
event TransferredOwnership(address _from, address _to);
event LockedOwnership(address _locked);
address payable private _owner;
bool private _isTransferable;
/// @notice Constructor sets the original owner of the contract and whether or not it is one time transferable.
constructor(address payable _account_, bool _transferable_) internal {
_owner = _account_;
_isTransferable = _transferable_;
// Emit the LockedOwnership event if no longer transferable.
if (!_isTransferable) {
emit LockedOwnership(_account_);
}
emit TransferredOwnership(address(0), _account_);
}
/// @notice Reverts if called by any account other than the owner.
modifier onlyOwner() {
require(_isOwner(msg.sender), "sender is not an owner");
_;
}
/// @notice Allows the current owner to transfer control of the contract to a new address.
/// @param _account address to transfer ownership to.
/// @param _transferable indicates whether to keep the ownership transferable.
function transferOwnership(address payable _account, bool _transferable) external onlyOwner {
// Require that the ownership is transferable.
require(_isTransferable, "ownership is not transferable");
// Require that the new owner is not the zero address.
require(_account != address(0), "owner cannot be set to zero address");
// Set the transferable flag to the value _transferable passed in.
_isTransferable = _transferable;
// Emit the LockedOwnership event if no longer transferable.
if (!_transferable) {
emit LockedOwnership(_account);
}
// Emit the ownership transfer event.
emit TransferredOwnership(_owner, _account);
// Set the owner to the provided address.
_owner = _account;
}
/// @notice check if the ownership is transferable.
/// @return true if the ownership is transferable.
function isTransferable() external view returns (bool) {
return _isTransferable;
}
/// @notice Allows the current owner to relinquish control of the contract.
/// @dev Renouncing to ownership will leave the contract without an owner and unusable.
/// @dev It will not be possible to call the functions with the `onlyOwner` modifier anymore.
function renounceOwnership() external onlyOwner {
// Require that the ownership is transferable.
require(_isTransferable, "ownership is not transferable");
// note that this could be terminal
_owner = address(0);
emit TransferredOwnership(_owner, address(0));
}
/// @notice Find out owner address
/// @return address of the owner.
function owner() public view returns (address payable) {
return _owner;
}
/// @notice Check if owner address
/// @return true if sender is the owner of the contract.
function _isOwner(address _address) internal view returns (bool) {
return _address == _owner;
}
}
// File: controller.sol
/**
* Controller - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title The IController interface provides access to the isController and isAdmin checks.
interface IController {
function isController(address) external view returns (bool);
function isAdmin(address) external view returns (bool);
}
/// @title Controller stores a list of controller addresses that can be used for authentication in other contracts.
/// @notice The Controller implements a hierarchy of concepts, Owner, Admin, and the Controllers.
/// @dev Owner can change the Admins
/// @dev Admins and can the Controllers
/// @dev Controllers are used by the application.
contract Controller is IController, Ownable, Transferrable {
event AddedController(address _sender, address _controller);
event RemovedController(address _sender, address _controller);
event AddedAdmin(address _sender, address _admin);
event RemovedAdmin(address _sender, address _admin);
event Claimed(address _to, address _asset, uint _amount);
event Stopped(address _sender);
event Started(address _sender);
mapping (address => bool) private _isAdmin;
uint private _adminCount;
mapping (address => bool) private _isController;
uint private _controllerCount;
bool private _stopped;
/// @notice Constructor initializes the owner with the provided address.
/// @param _ownerAddress_ address of the owner.
constructor(address payable _ownerAddress_) Ownable(_ownerAddress_, false) public {}
/// @notice Checks if message sender is an admin.
modifier onlyAdmin() {
require(isAdmin(msg.sender), "sender is not an admin");
_;
}
/// @notice Check if Owner or Admin
modifier onlyAdminOrOwner() {
require(_isOwner(msg.sender) || isAdmin(msg.sender), "sender is not an admin");
_;
}
/// @notice Check if controller is stopped
modifier notStopped() {
require(!isStopped(), "controller is stopped");
_;
}
/// @notice Add a new admin to the list of admins.
/// @param _account address to add to the list of admins.
function addAdmin(address _account) external onlyOwner notStopped {
_addAdmin(_account);
}
/// @notice Remove a admin from the list of admins.
/// @param _account address to remove from the list of admins.
function removeAdmin(address _account) external onlyOwner {
_removeAdmin(_account);
}
/// @return the current number of admins.
function adminCount() external view returns (uint) {
return _adminCount;
}
/// @notice Add a new controller to the list of controllers.
/// @param _account address to add to the list of controllers.
function addController(address _account) external onlyAdminOrOwner notStopped {
_addController(_account);
}
/// @notice Remove a controller from the list of controllers.
/// @param _account address to remove from the list of controllers.
function removeController(address _account) external onlyAdminOrOwner {
_removeController(_account);
}
/// @notice count the Controllers
/// @return the current number of controllers.
function controllerCount() external view returns (uint) {
return _controllerCount;
}
/// @notice is an address an Admin?
/// @return true if the provided account is an admin.
function isAdmin(address _account) public view notStopped returns (bool) {
return _isAdmin[_account];
}
/// @notice is an address a Controller?
/// @return true if the provided account is a controller.
function isController(address _account) public view notStopped returns (bool) {
return _isController[_account];
}
/// @notice this function can be used to see if the controller has been stopped
/// @return true is the Controller has been stopped
function isStopped() public view returns (bool) {
return _stopped;
}
/// @notice Internal-only function that adds a new admin.
function _addAdmin(address _account) private {
require(!_isAdmin[_account], "provided account is already an admin");
require(!_isController[_account], "provided account is already a controller");
require(!_isOwner(_account), "provided account is already the owner");
require(_account != address(0), "provided account is the zero address");
_isAdmin[_account] = true;
_adminCount++;
emit AddedAdmin(msg.sender, _account);
}
/// @notice Internal-only function that removes an existing admin.
function _removeAdmin(address _account) private {
require(_isAdmin[_account], "provided account is not an admin");
_isAdmin[_account] = false;
_adminCount--;
emit RemovedAdmin(msg.sender, _account);
}
/// @notice Internal-only function that adds a new controller.
function _addController(address _account) private {
require(!_isAdmin[_account], "provided account is already an admin");
require(!_isController[_account], "provided account is already a controller");
require(!_isOwner(_account), "provided account is already the owner");
require(_account != address(0), "provided account is the zero address");
_isController[_account] = true;
_controllerCount++;
emit AddedController(msg.sender, _account);
}
/// @notice Internal-only function that removes an existing controller.
function _removeController(address _account) private {
require(_isController[_account], "provided account is not a controller");
_isController[_account] = false;
_controllerCount--;
emit RemovedController(msg.sender, _account);
}
/// @notice stop our controllers and admins from being useable
function stop() external onlyAdminOrOwner {
_stopped = true;
emit Stopped(msg.sender);
}
/// @notice start our controller again
function start() external onlyOwner {
_stopped = false;
emit Started(msg.sender);
}
//// @notice Withdraw tokens from the smart contract to the specified account.
function claim(address payable _to, address _asset, uint _amount) external onlyAdmin notStopped {
_safeTransfer(_to, _asset, _amount);
emit Claimed(_to, _asset, _amount);
}
}
// File: ENS.sol
/**
* BSD 2-Clause License
*
* Copyright (c) 2018, True Names Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
pragma solidity ^0.5.0;
interface ENS {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external;
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
}
// File: ResolverBase.sol
pragma solidity ^0.5.0;
contract ResolverBase {
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == INTERFACE_META_ID;
}
function isAuthorised(bytes32 node) internal view returns(bool);
modifier authorised(bytes32 node) {
require(isAuthorised(node));
_;
}
}
// File: ABIResolver.sol
pragma solidity ^0.5.0;
contract ABIResolver is ResolverBase {
bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56;
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
mapping(bytes32=>mapping(uint256=>bytes)) abis;
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) {
// Content types must be powers of 2
require(((contentType - 1) & contentType) == 0);
abis[node][contentType] = data;
emit ABIChanged(node, contentType);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) {
mapping(uint256=>bytes) storage abiset = abis[node];
for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) {
return (contentType, abiset[contentType]);
}
}
return (0, bytes(""));
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: AddrResolver.sol
pragma solidity ^0.5.0;
contract AddrResolver is ResolverBase {
bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de;
event AddrChanged(bytes32 indexed node, address a);
mapping(bytes32=>address) addresses;
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) external authorised(node) {
addresses[node] = addr;
emit AddrChanged(node, addr);
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) public view returns (address) {
return addresses[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == ADDR_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: ContentHashResolver.sol
pragma solidity ^0.5.0;
contract ContentHashResolver is ResolverBase {
bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1;
event ContenthashChanged(bytes32 indexed node, bytes hash);
mapping(bytes32=>bytes) hashes;
/**
* Sets the contenthash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param hash The contenthash to set
*/
function setContenthash(bytes32 node, bytes calldata hash) external authorised(node) {
hashes[node] = hash;
emit ContenthashChanged(node, hash);
}
/**
* Returns the contenthash associated with an ENS node.
* @param node The ENS node to query.
* @return The associated contenthash.
*/
function contenthash(bytes32 node) external view returns (bytes memory) {
return hashes[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: InterfaceResolver.sol
pragma solidity ^0.5.0;
contract InterfaceResolver is ResolverBase, AddrResolver {
bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)"));
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer);
mapping(bytes32=>mapping(bytes4=>address)) interfaces;
/**
* Sets an interface associated with a name.
* Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support.
* @param node The node to update.
* @param interfaceID The EIP 168 interface ID.
* @param implementer The address of a contract that implements this interface for this node.
*/
function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) {
interfaces[node][interfaceID] = implementer;
emit InterfaceChanged(node, interfaceID, implementer);
}
/**
* Returns the address of a contract that implements the specified interface for this name.
* If an implementer has not been set for this interfaceID and name, the resolver will query
* the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that
* contract implements EIP168 and returns `true` for the specified interfaceID, its address
* will be returned.
* @param node The ENS node to query.
* @param interfaceID The EIP 168 interface ID to check for.
* @return The address that implements this interface, or 0 if the interface is unsupported.
*/
function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) {
address implementer = interfaces[node][interfaceID];
if(implementer != address(0)) {
return implementer;
}
address a = addr(node);
if(a == address(0)) {
return address(0);
}
(bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// EIP 168 not supported by target
return address(0);
}
(success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// Specified interface not supported by target
return address(0);
}
return a;
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: NameResolver.sol
pragma solidity ^0.5.0;
contract NameResolver is ResolverBase {
bytes4 constant private NAME_INTERFACE_ID = 0x691f3431;
event NameChanged(bytes32 indexed node, string name);
mapping(bytes32=>string) names;
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string calldata name) external authorised(node) {
names[node] = name;
emit NameChanged(node, name);
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) external view returns (string memory) {
return names[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: PubkeyResolver.sol
pragma solidity ^0.5.0;
contract PubkeyResolver is ResolverBase {
bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233;
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
struct PublicKey {
bytes32 x;
bytes32 y;
}
mapping(bytes32=>PublicKey) pubkeys;
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) external authorised(node) {
pubkeys[node] = PublicKey(x, y);
emit PubkeyChanged(node, x, y);
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x, y the X and Y coordinates of the curve point for the public key.
*/
function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) {
return (pubkeys[node].x, pubkeys[node].y);
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: TextResolver.sol
pragma solidity ^0.5.0;
contract TextResolver is ResolverBase {
bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c;
event TextChanged(bytes32 indexed node, string indexedKey, string key);
mapping(bytes32=>mapping(string=>string)) texts;
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string calldata key, string calldata value) external authorised(node) {
texts[node][key] = value;
emit TextChanged(node, key, key);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string calldata key) external view returns (string memory) {
return texts[node][key];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: PublicResolver.sol
/**
* BSD 2-Clause License
*
* Copyright (c) 2018, True Names Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
pragma solidity ^0.5.0;
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver {
ENS ens;
/**
* A mapping of authorisations. An address that is authorised for a name
* may make any changes to the name that the owner could, but may not update
* the set of authorisations.
* (node, owner, caller) => isAuthorised
*/
mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations;
event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised);
constructor(ENS _ens) public {
ens = _ens;
}
/**
* @dev Sets or clears an authorisation.
* Authorisations are specific to the caller. Any account can set an authorisation
* for any name, but the authorisation that is checked will be that of the
* current owner of a name. Thus, transferring a name effectively clears any
* existing authorisations, and new authorisations can be set in advance of
* an ownership transfer if desired.
*
* @param node The name to change the authorisation on.
* @param target The address that is to be authorised or deauthorised.
* @param isAuthorised True if the address should be authorised, or false if it should be deauthorised.
*/
function setAuthorisation(bytes32 node, address target, bool isAuthorised) external {
authorisations[node][msg.sender][target] = isAuthorised;
emit AuthorisationChanged(node, msg.sender, target, isAuthorised);
}
function isAuthorised(bytes32 node) internal view returns(bool) {
address owner = ens.owner(node);
return owner == msg.sender || authorisations[node][owner][msg.sender];
}
}
// File: ensResolvable.sol
/**
* ENSResolvable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
///@title ENSResolvable - Ethereum Name Service Resolver
///@notice contract should be used to get an address for an ENS node
contract ENSResolvable {
/// @notice _ens is an instance of ENS
ENS private _ens;
/// @notice _ensRegistry points to the ENS registry smart contract.
address private _ensRegistry;
/// @param _ensReg_ is the ENS registry used
constructor(address _ensReg_) internal {
_ensRegistry = _ensReg_;
_ens = ENS(_ensRegistry);
}
/// @notice this is used to that one can observe which ENS registry is being used
function ensRegistry() external view returns (address) {
return _ensRegistry;
}
/// @notice helper function used to get the address of a node
/// @param _node of the ENS entry that needs resolving
/// @return the address of the said node
function _ensResolve(bytes32 _node) internal view returns (address) {
return PublicResolver(_ens.resolver(_node)).addr(_node);
}
}
// File: controllable.sol
/**
* Controllable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title Controllable implements access control functionality of the Controller found via ENS.
contract Controllable is ENSResolvable {
/// @dev Is the registered ENS node identifying the controller contract.
bytes32 private _controllerNode;
/// @notice Constructor initializes the controller contract object.
/// @param _controllerNode_ is the ENS node of the Controller.
constructor(bytes32 _controllerNode_) internal {
_controllerNode = _controllerNode_;
}
/// @notice Checks if message sender is a controller.
modifier onlyController() {
require(_isController(msg.sender), "sender is not a controller");
_;
}
/// @notice Checks if message sender is an admin.
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "sender is not an admin");
_;
}
/// @return the controller node registered in ENS.
function controllerNode() external view returns (bytes32) {
return _controllerNode;
}
/// @return true if the provided account is a controller.
function _isController(address _account) internal view returns (bool) {
return IController(_ensResolve(_controllerNode)).isController(_account);
}
/// @return true if the provided account is an admin.
function _isAdmin(address _account) internal view returns (bool) {
return IController(_ensResolve(_controllerNode)).isAdmin(_account);
}
}
// File: bytesUtils.sol
/**
* BytesUtils - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title BytesUtils provides basic byte slicing and casting functionality.
library BytesUtils {
using SafeMath for uint256;
/// @dev This function converts to an address
/// @param _bts bytes
/// @param _from start position
function _bytesToAddress(bytes memory _bts, uint _from) internal pure returns (address) {
require(_bts.length >= _from.add(20), "slicing out of range");
bytes20 convertedAddress;
uint startByte = _from.add(32); //first 32 bytes denote the array length
assembly {
convertedAddress := mload(add(_bts, startByte))
}
return address(convertedAddress);
}
/// @dev This function slices bytes into bytes4
/// @param _bts some bytes
/// @param _from start position
function _bytesToBytes4(bytes memory _bts, uint _from) internal pure returns (bytes4) {
require(_bts.length >= _from.add(4), "slicing out of range");
bytes4 slicedBytes4;
uint startByte = _from.add(32); //first 32 bytes denote the array length
assembly {
slicedBytes4 := mload(add(_bts, startByte))
}
return slicedBytes4;
}
/// @dev This function slices a uint
/// @param _bts some bytes
/// @param _from start position
// credit to https://ethereum.stackexchange.com/questions/51229/how-to-convert-bytes-to-uint-in-solidity
// and Nick Johnson https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity/4177#4177
function _bytesToUint256(bytes memory _bts, uint _from) internal pure returns (uint) {
require(_bts.length >= _from.add(32), "slicing out of range");
uint convertedUint256;
uint startByte = _from.add(32); //first 32 bytes denote the array length
assembly {
convertedUint256 := mload(add(_bts, startByte))
}
return convertedUint256;
}
}
// File: strings.sol
/*
* Copyright 2016 Nick Johnson
*
* 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.
*/
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/
pragma solidity ^0.5.0;
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (uint(self) & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (uint(self) & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (uint(self) & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (uint(self) & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if (b < 0xE0) {
ptr += 2;
} else if (b < 0xF0) {
ptr += 3;
} else if (b < 0xF8) {
ptr += 4;
} else if (b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if (shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if (b < 0xE0) {
l = 2;
} else if (b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if (b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if (b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for (uint i = 0; i < parts.length; i++) {
length += parts[i]._len;
}
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for (uint i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
// File: tokenWhitelist.sol
/**
* TokenWhitelist - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title The ITokenWhitelist interface provides access to a whitelist of tokens.
interface ITokenWhitelist {
function getTokenInfo(address) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256);
function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256);
function tokenAddressArray() external view returns (address[] memory);
function redeemableTokens() external view returns (address[] memory);
function methodIdWhitelist(bytes4) external view returns (bool);
function getERC20RecipientAndAmount(address, bytes calldata) external view returns (address, uint);
function stablecoin() external view returns (address);
function updateTokenRate(address, uint, uint) external;
}
/// @title TokenWhitelist stores a list of tokens used by the Consumer Contract Wallet, the Oracle, the TKN Holder and the TKN Licence Contract
contract TokenWhitelist is ENSResolvable, Controllable, Transferrable {
using strings for *;
using SafeMath for uint256;
using BytesUtils for bytes;
event UpdatedTokenRate(address _sender, address _token, uint _rate);
event UpdatedTokenLoadable(address _sender, address _token, bool _loadable);
event UpdatedTokenRedeemable(address _sender, address _token, bool _redeemable);
event AddedToken(address _sender, address _token, string _symbol, uint _magnitude, bool _loadable, bool _redeemable);
event RemovedToken(address _sender, address _token);
event AddedMethodId(bytes4 _methodId);
event RemovedMethodId(bytes4 _methodId);
event AddedExclusiveMethod(address _token, bytes4 _methodId);
event RemovedExclusiveMethod(address _token, bytes4 _methodId);
event Claimed(address _to, address _asset, uint _amount);
/// @dev these are the methods whitelisted by default in executeTransaction() for protected tokens
bytes4 private constant _APPROVE = 0x095ea7b3; // keccak256(approve(address,uint256)) => 0x095ea7b3
bytes4 private constant _BURN = 0x42966c68; // keccak256(burn(uint256)) => 0x42966c68
bytes4 private constant _TRANSFER= 0xa9059cbb; // keccak256(transfer(address,uint256)) => 0xa9059cbb
bytes4 private constant _TRANSFER_FROM = 0x23b872dd; // keccak256(transferFrom(address,address,uint256)) => 0x23b872dd
struct Token {
string symbol; // Token symbol
uint magnitude; // 10^decimals
uint rate; // Token exchange rate in wei
bool available; // Flags if the token is available or not
bool loadable; // Flags if token is loadable to the TokenCard
bool redeemable; // Flags if token is redeemable in the TKN Holder contract
uint lastUpdate; // Time of the last rate update
}
mapping(address => Token) private _tokenInfoMap;
// @notice specifies whitelisted methodIds for protected tokens in wallet's excuteTranaction() e.g. keccak256(transfer(address,uint256)) => 0xa9059cbb
mapping(bytes4 => bool) private _methodIdWhitelist;
address[] private _tokenAddressArray;
/// @notice keeping track of how many redeemable tokens are in the tokenWhitelist
uint private _redeemableCounter;
/// @notice Address of the stablecoin.
address private _stablecoin;
/// @notice is registered ENS node identifying the oracle contract.
bytes32 private _oracleNode;
/// @notice Constructor initializes ENSResolvable, and Controllable.
/// @param _ens_ is the ENS registry address.
/// @param _oracleNode_ is the ENS node of the Oracle.
/// @param _controllerNode_ is our Controllers node.
/// @param _stablecoinAddress_ is the address of the stablecoint used by the wallet for the card load limit.
constructor(address _ens_, bytes32 _oracleNode_, bytes32 _controllerNode_, address _stablecoinAddress_) ENSResolvable(_ens_) Controllable(_controllerNode_) public {
_oracleNode = _oracleNode_;
_stablecoin = _stablecoinAddress_;
//a priori ERC20 whitelisted methods
_methodIdWhitelist[_APPROVE] = true;
_methodIdWhitelist[_BURN] = true;
_methodIdWhitelist[_TRANSFER] = true;
_methodIdWhitelist[_TRANSFER_FROM] = true;
}
modifier onlyAdminOrOracle() {
address oracleAddress = _ensResolve(_oracleNode);
require (_isAdmin(msg.sender) || msg.sender == oracleAddress, "either oracle or admin");
_;
}
/// @notice Add ERC20 tokens to the list of whitelisted tokens.
/// @param _tokens ERC20 token contract addresses.
/// @param _symbols ERC20 token names.
/// @param _magnitude 10 to the power of number of decimal places used by each ERC20 token.
/// @param _loadable is a bool that states whether or not a token is loadable to the TokenCard.
/// @param _redeemable is a bool that states whether or not a token is redeemable in the TKN Holder Contract.
/// @param _lastUpdate is a unit representing an ISO datetime e.g. 20180913153211.
function addTokens(address[] calldata _tokens, bytes32[] calldata _symbols, uint[] calldata _magnitude, bool[] calldata _loadable, bool[] calldata _redeemable, uint _lastUpdate) external onlyAdmin {
// Require that all parameters have the same length.
require(_tokens.length == _symbols.length && _tokens.length == _magnitude.length && _tokens.length == _loadable.length && _tokens.length == _loadable.length, "parameter lengths do not match");
// Add each token to the list of supported tokens.
for (uint i = 0; i < _tokens.length; i++) {
// Require that the token isn't already available.
require(!_tokenInfoMap[_tokens[i]].available, "token already available");
// Store the intermediate values.
string memory symbol = _symbols[i].toSliceB32().toString();
// Add the token to the token list.
_tokenInfoMap[_tokens[i]] = Token({
symbol : symbol,
magnitude : _magnitude[i],
rate : 0,
available : true,
loadable : _loadable[i],
redeemable: _redeemable[i],
lastUpdate : _lastUpdate
});
// Add the token address to the address list.
_tokenAddressArray.push(_tokens[i]);
//if the token is redeemable increase the redeemableCounter
if (_redeemable[i]){
_redeemableCounter = _redeemableCounter.add(1);
}
// Emit token addition event.
emit AddedToken(msg.sender, _tokens[i], symbol, _magnitude[i], _loadable[i], _redeemable[i]);
}
}
/// @notice Remove ERC20 tokens from the whitelist of tokens.
/// @param _tokens ERC20 token contract addresses.
function removeTokens(address[] calldata _tokens) external onlyAdmin {
// Delete each token object from the list of supported tokens based on the addresses provided.
for (uint i = 0; i < _tokens.length; i++) {
// Store the token address.
address token = _tokens[i];
//token must be available, reverts on duplicates as well
require(_tokenInfoMap[token].available, "token is not available");
//if the token is redeemable decrease the redeemableCounter
if (_tokenInfoMap[token].redeemable){
_redeemableCounter = _redeemableCounter.sub(1);
}
// Delete the token object.
delete _tokenInfoMap[token];
// Remove the token address from the address list.
for (uint j = 0; j < _tokenAddressArray.length.sub(1); j++) {
if (_tokenAddressArray[j] == token) {
_tokenAddressArray[j] = _tokenAddressArray[_tokenAddressArray.length.sub(1)];
break;
}
}
_tokenAddressArray.length--;
// Emit token removal event.
emit RemovedToken(msg.sender, token);
}
}
/// @notice based on the method it returns the recipient address and amount/value, ERC20 specific.
/// @param _data is the transaction payload.
function getERC20RecipientAndAmount(address _token, bytes calldata _data) external view returns (address, uint) {
// Require that there exist enough bytes for encoding at least a method signature + data in the transaction payload:
// 4 (signature) + 32(address or uint256)
require(_data.length >= 4 + 32, "not enough method-encoding bytes");
// Get the method signature
bytes4 signature = _data._bytesToBytes4(0);
// Check if method Id is supported
require(isERC20MethodSupported(_token, signature), "unsupported method");
// returns the recipient's address and amount is the value to be transferred
if (signature == _BURN) {
// 4 (signature) + 32(uint256)
return (_token, _data._bytesToUint256(4));
} else if (signature == _TRANSFER_FROM) {
// 4 (signature) + 32(address) + 32(address) + 32(uint256)
require(_data.length >= 4 + 32 + 32 + 32, "not enough data for transferFrom");
return ( _data._bytesToAddress(4 + 32 + 12), _data._bytesToUint256(4 + 32 + 32));
} else { //transfer or approve
// 4 (signature) + 32(address) + 32(uint)
require(_data.length >= 4 + 32 + 32, "not enough data for transfer/appprove");
return (_data._bytesToAddress(4 + 12), _data._bytesToUint256(4 + 32));
}
}
/// @notice Toggles whether or not a token is loadable or not.
function setTokenLoadable(address _token, bool _loadable) external onlyAdmin {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// this sets the loadable flag to the value passed in
_tokenInfoMap[_token].loadable = _loadable;
emit UpdatedTokenLoadable(msg.sender, _token, _loadable);
}
/// @notice Toggles whether or not a token is redeemable or not.
function setTokenRedeemable(address _token, bool _redeemable) external onlyAdmin {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// this sets the redeemable flag to the value passed in
_tokenInfoMap[_token].redeemable = _redeemable;
emit UpdatedTokenRedeemable(msg.sender, _token, _redeemable);
}
/// @notice Update ERC20 token exchange rate.
/// @param _token ERC20 token contract address.
/// @param _rate ERC20 token exchange rate in wei.
/// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.
function updateTokenRate(address _token, uint _rate, uint _updateDate) external onlyAdminOrOracle {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// Update the token's rate.
_tokenInfoMap[_token].rate = _rate;
// Update the token's last update timestamp.
_tokenInfoMap[_token].lastUpdate = _updateDate;
// Emit the rate update event.
emit UpdatedTokenRate(msg.sender, _token, _rate);
}
//// @notice Withdraw tokens from the smart contract to the specified account.
function claim(address payable _to, address _asset, uint _amount) external onlyAdmin {
_safeTransfer(_to, _asset, _amount);
emit Claimed(_to, _asset, _amount);
}
/// @notice This returns all of the fields for a given token.
/// @param _a is the address of a given token.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function getTokenInfo(address _a) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
Token storage tokenInfo = _tokenInfoMap[_a];
return (tokenInfo.symbol, tokenInfo.magnitude, tokenInfo.rate, tokenInfo.available, tokenInfo.loadable, tokenInfo.redeemable, tokenInfo.lastUpdate);
}
/// @notice This returns all of the fields for our StableCoin.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
Token storage stablecoinInfo = _tokenInfoMap[_stablecoin];
return (stablecoinInfo.symbol, stablecoinInfo.magnitude, stablecoinInfo.rate, stablecoinInfo.available, stablecoinInfo.loadable, stablecoinInfo.redeemable, stablecoinInfo.lastUpdate);
}
/// @notice This returns an array of all whitelisted token addresses.
/// @return address[] of whitelisted tokens.
function tokenAddressArray() external view returns (address[] memory) {
return _tokenAddressArray;
}
/// @notice This returns an array of all redeemable token addresses.
/// @return address[] of redeemable tokens.
function redeemableTokens() external view returns (address[] memory) {
address[] memory redeemableAddresses = new address[](_redeemableCounter);
uint redeemableIndex = 0;
for (uint i = 0; i < _tokenAddressArray.length; i++) {
address token = _tokenAddressArray[i];
if (_tokenInfoMap[token].redeemable){
redeemableAddresses[redeemableIndex] = token;
redeemableIndex += 1;
}
}
return redeemableAddresses;
}
/// @notice This returns true if a method Id is supported for the specific token.
/// @return true if _methodId is supported in general or just for the specific token.
function isERC20MethodSupported(address _token, bytes4 _methodId) public view returns (bool) {
require(_tokenInfoMap[_token].available, "non-existing token");
return (_methodIdWhitelist[_methodId]);
}
/// @notice This returns true if the method is supported for all protected tokens.
/// @return true if _methodId is in the method whitelist.
function isERC20MethodWhitelisted(bytes4 _methodId) external view returns (bool) {
return (_methodIdWhitelist[_methodId]);
}
/// @notice This returns the number of redeemable tokens.
/// @return current # of redeemables.
function redeemableCounter() external view returns (uint) {
return _redeemableCounter;
}
/// @notice This returns the address of our stablecoin of choice.
/// @return the address of the stablecoin contract.
function stablecoin() external view returns (address) {
return _stablecoin;
}
/// @notice this returns the node hash of our Oracle.
/// @return the oracle node registered in ENS.
function oracleNode() external view returns (bytes32) {
return _oracleNode;
}
}
// File: tokenWhitelistable.sol
/**
* TokenWhitelistable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title TokenWhitelistable implements access to the TokenWhitelist located behind ENS.
contract TokenWhitelistable is ENSResolvable {
/// @notice Is the registered ENS node identifying the tokenWhitelist contract
bytes32 private _tokenWhitelistNode;
/// @notice Constructor initializes the TokenWhitelistable object.
/// @param _tokenWhitelistNode_ is the ENS node of the TokenWhitelist.
constructor(bytes32 _tokenWhitelistNode_) internal {
_tokenWhitelistNode = _tokenWhitelistNode_;
}
/// @notice This shows what TokenWhitelist is being used
/// @return TokenWhitelist's node registered in ENS.
function tokenWhitelistNode() external view returns (bytes32) {
return _tokenWhitelistNode;
}
/// @notice This returns all of the fields for a given token.
/// @param _a is the address of a given token.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function _getTokenInfo(address _a) internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getTokenInfo(_a);
}
/// @notice This returns all of the fields for our stablecoin token.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function _getStablecoinInfo() internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getStablecoinInfo();
}
/// @notice This returns an array of our whitelisted addresses.
/// @return address[] of our whitelisted tokens.
function _tokenAddressArray() internal view returns (address[] memory) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).tokenAddressArray();
}
/// @notice This returns an array of all redeemable token addresses.
/// @return address[] of redeemable tokens.
function _redeemableTokens() internal view returns (address[] memory) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).redeemableTokens();
}
/// @notice Update ERC20 token exchange rate.
/// @param _token ERC20 token contract address.
/// @param _rate ERC20 token exchange rate in wei.
/// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.
function _updateTokenRate(address _token, uint _rate, uint _updateDate) internal {
ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).updateTokenRate(_token, _rate, _updateDate);
}
/// @notice based on the method it returns the recipient address and amount/value, ERC20 specific.
/// @param _data is the transaction payload.
function _getERC20RecipientAndAmount(address _destination, bytes memory _data) internal view returns (address, uint) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getERC20RecipientAndAmount(_destination, _data);
}
/// @notice Checks whether a token is available.
/// @return bool available or not.
function _isTokenAvailable(address _a) internal view returns (bool) {
( , , , bool available, , , ) = _getTokenInfo(_a);
return available;
}
/// @notice Checks whether a token is redeemable.
/// @return bool redeemable or not.
function _isTokenRedeemable(address _a) internal view returns (bool) {
( , , , , , bool redeemable, ) = _getTokenInfo(_a);
return redeemable;
}
/// @notice Checks whether a token is loadable.
/// @return bool loadable or not.
function _isTokenLoadable(address _a) internal view returns (bool) {
( , , , , bool loadable, , ) = _getTokenInfo(_a);
return loadable;
}
/// @notice This gets the address of the stablecoin.
/// @return the address of the stablecoin contract.
function _stablecoin() internal view returns (address) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).stablecoin();
}
}
// File: holder.sol
/**
* Holder (aka Asset Contract) - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title Holder - The TKN Asset Contract
/// @notice When the TKN contract calls the burn method, a share of the tokens held by this contract are disbursed to the burner.
contract Holder is Balanceable, ENSResolvable, Controllable, Transferrable, TokenWhitelistable {
using SafeMath for uint256;
event Received(address _from, uint _amount);
event CashAndBurned(address _to, address _asset, uint _amount);
event Claimed(address _to, address _asset, uint _amount);
/// @dev Check if the sender is the burner contract
modifier onlyBurner() {
require (msg.sender == _burner, "burner contract is not the sender");
_;
}
// Burner token which can be burned to redeem shares.
address private _burner;
/// @notice Constructor initializes the holder contract.
/// @param _burnerContract_ is the address of the token contract TKN with burning functionality.
/// @param _ens_ is the address of the ENS registry.
/// @param _tokenWhitelistNode_ is the ENS node of the Token whitelist.
/// @param _controllerNode_ is the ENS node of the Controller
constructor (address _burnerContract_, address _ens_, bytes32 _tokenWhitelistNode_, bytes32 _controllerNode_) ENSResolvable(_ens_) Controllable(_controllerNode_) TokenWhitelistable(_tokenWhitelistNode_) public {
_burner = _burnerContract_;
}
/// @notice Ether may be sent from anywhere.
function() external payable {
emit Received(msg.sender, msg.value);
}
/// @notice Burn handles disbursing a share of tokens in this contract to a given address.
/// @param _to The address to disburse to
/// @param _amount The amount of TKN that will be burned if this succeeds
function burn(address payable _to, uint _amount) external onlyBurner returns (bool) {
if (_amount == 0) {
return true;
}
// The burner token deducts from the supply before calling.
uint supply = IBurner(_burner).currentSupply().add(_amount);
address[] memory redeemableAddresses = _redeemableTokens();
for (uint i = 0; i < redeemableAddresses.length; i++) {
uint redeemableBalance = _balance(address(this), redeemableAddresses[i]);
if (redeemableBalance > 0) {
uint redeemableAmount = redeemableBalance.mul(_amount).div(supply);
_safeTransfer(_to, redeemableAddresses[i], redeemableAmount);
emit CashAndBurned(_to, redeemableAddresses[i], redeemableAmount);
}
}
return true;
}
/// @notice This allows for the admin to reclaim the non-redeemableTokens
/// @param _to this is the address which the reclaimed tokens will be sent to
/// @param _nonRedeemableAddresses this is the array of tokens to be claimed
function nonRedeemableTokenClaim(address payable _to, address[] calldata _nonRedeemableAddresses) external onlyAdmin returns (bool) {
for (uint i = 0; i < _nonRedeemableAddresses.length; i++) {
//revert if token is redeemable
require(!_isTokenRedeemable(_nonRedeemableAddresses[i]), "redeemables cannot be claimed");
uint claimBalance = _balance(address(this), _nonRedeemableAddresses[i]);
if (claimBalance > 0) {
_safeTransfer(_to, _nonRedeemableAddresses[i], claimBalance);
emit Claimed(_to, _nonRedeemableAddresses[i], claimBalance);
}
}
return true;
}
/// @notice Returned the address of the burner contract
/// @return the TKN address
function burner() external view returns (address) {
return _burner;
}
} | Internal-only function that removes an existing admin. | function _removeAdmin(address _account) private {
require(_isAdmin[_account], "provided account is not an admin");
_isAdmin[_account] = false;
_adminCount--;
emit RemovedAdmin(msg.sender, _account);
}
| 913,586 |
/*
* Error logging
* Author: Zac Williamson, AZTEC
* SPDX-License-Identifier: Apache-2.0
*/
pragma solidity >=0.6.10;
library consolerr {
function errorBytes(string memory reasonString, bytes memory varA) internal pure {
(bytes32 revertPtr, bytes32 errorPtr) = initErrorPtr();
appendString(reasonString, errorPtr);
appendBytes(varA, errorPtr);
assembly {
revert(revertPtr, add(mload(errorPtr), 0x44))
}
}
function error(string memory reasonString, bytes32 varA) internal pure {
(bytes32 revertPtr, bytes32 errorPtr) = initErrorPtr();
appendString(reasonString, errorPtr);
append0x(errorPtr);
appendBytes32(varA, errorPtr);
assembly {
revert(revertPtr, add(mload(errorPtr), 0x44))
}
}
function error(
string memory reasonString,
bytes32 varA,
bytes32 varB
) internal pure {
(bytes32 revertPtr, bytes32 errorPtr) = initErrorPtr();
appendString(reasonString, errorPtr);
append0x(errorPtr);
appendBytes32(varA, errorPtr);
appendComma(errorPtr);
append0x(errorPtr);
appendBytes32(varB, errorPtr);
assembly {
revert(revertPtr, add(mload(errorPtr), 0x44))
}
}
function error(
string memory reasonString,
bytes32 varA,
bytes32 varB,
bytes32 varC
) internal pure {
(bytes32 revertPtr, bytes32 errorPtr) = initErrorPtr();
appendString(reasonString, errorPtr);
append0x(errorPtr);
appendBytes32(varA, errorPtr);
appendComma(errorPtr);
append0x(errorPtr);
appendBytes32(varB, errorPtr);
appendComma(errorPtr);
append0x(errorPtr);
appendBytes32(varC, errorPtr);
assembly {
revert(revertPtr, add(mload(errorPtr), 0x44))
}
}
function errorBytes32(string memory reasonString, bytes32 varA) internal pure {
error(reasonString, varA);
}
function errorBytes32(
string memory reasonString,
bytes32 varA,
bytes32 varB
) internal pure {
error(reasonString, varA, varB);
}
function errorBytes32(
string memory reasonString,
bytes32 varA,
bytes32 varB,
bytes32 varC
) internal pure {
error(reasonString, varA, varB, varC);
}
function errorAddress(string memory reasonString, address varA) internal pure {
(bytes32 revertPtr, bytes32 errorPtr) = initErrorPtr();
appendString(reasonString, errorPtr);
appendAddress(varA, errorPtr);
assembly {
revert(revertPtr, add(mload(errorPtr), 0x44))
}
}
function errorAddress(
string memory reasonString,
address varA,
address varB
) internal pure {
(bytes32 revertPtr, bytes32 errorPtr) = initErrorPtr();
appendString(reasonString, errorPtr);
appendAddress(varA, errorPtr);
appendComma(errorPtr);
appendAddress(varB, errorPtr);
assembly {
revert(revertPtr, add(mload(errorPtr), 0x44))
}
}
function errorAddress(
string memory reasonString,
address varA,
address varB,
address varC
) internal pure {
(bytes32 revertPtr, bytes32 errorPtr) = initErrorPtr();
appendString(reasonString, errorPtr);
appendAddress(varA, errorPtr);
appendComma(errorPtr);
appendAddress(varB, errorPtr);
appendComma(errorPtr);
appendAddress(varC, errorPtr);
assembly {
revert(revertPtr, add(mload(errorPtr), 0x44))
}
}
function errorUint(string memory reasonString, uint256 varA) internal pure {
(bytes32 revertPtr, bytes32 errorPtr) = initErrorPtr();
appendString(reasonString, errorPtr);
appendUint(varA, errorPtr);
assembly {
revert(revertPtr, add(mload(errorPtr), 0x44))
}
}
function errorUint(
string memory reasonString,
uint256 varA,
uint256 varB
) internal pure {
(bytes32 revertPtr, bytes32 errorPtr) = initErrorPtr();
appendString(reasonString, errorPtr);
appendUint(varA, errorPtr);
appendComma(errorPtr);
appendUint(varB, errorPtr);
assembly {
revert(revertPtr, add(mload(errorPtr), 0x44))
}
}
function errorUint(
string memory reasonString,
uint256 varA,
uint256 varB,
uint256 varC
) internal pure {
(bytes32 revertPtr, bytes32 errorPtr) = initErrorPtr();
appendString(reasonString, errorPtr);
appendUint(varA, errorPtr);
appendComma(errorPtr);
appendUint(varB, errorPtr);
appendComma(errorPtr);
appendUint(varC, errorPtr);
assembly {
revert(revertPtr, add(mload(errorPtr), 0x44))
}
}
function appendComma(bytes32 stringPtr) internal pure {
assembly {
let stringLen := mload(stringPtr)
mstore(add(stringPtr, add(stringLen, 0x20)), ', ')
mstore(stringPtr, add(stringLen, 2))
}
}
function append0x(bytes32 stringPtr) internal pure {
assembly {
let stringLen := mload(stringPtr)
mstore(add(stringPtr, add(stringLen, 0x20)), '0x')
mstore(stringPtr, add(stringLen, 2))
}
}
function appendString(string memory toAppend, bytes32 stringPtr) internal pure {
assembly {
let appendLen := mload(toAppend)
let stringLen := mload(stringPtr)
let appendPtr := add(stringPtr, add(0x20, stringLen))
for {
let i := 0
} lt(i, appendLen) {
i := add(i, 0x20)
} {
mstore(add(appendPtr, i), mload(add(toAppend, add(i, 0x20))))
}
// update string length
mstore(stringPtr, add(stringLen, appendLen))
}
}
function appendBytes(bytes memory toAppend, bytes32 stringPtr) internal pure {
uint256 bytesLen;
bytes32 inPtr;
assembly {
bytesLen := mload(toAppend)
inPtr := add(toAppend, 0x20)
}
for (uint256 i = 0; i < bytesLen; i += 0x20) {
bytes32 slice;
assembly {
slice := mload(inPtr)
inPtr := add(inPtr, 0x20)
}
appendBytes32(slice, stringPtr);
}
uint256 offset = bytesLen % 0x20;
if (offset > 0) {
// update length
assembly {
let lengthReduction := sub(0x20, offset)
let len := mload(stringPtr)
mstore(stringPtr, sub(len, lengthReduction))
}
}
}
function appendUint(uint256 input, bytes32 result) internal pure {
if (input < 10) {
assembly {
let len := mload(result)
mstore(result, add(len, 0x01))
mstore8(add(add(len, result), 0x20), add(input, 0x30))
}
return;
}
assembly {
let mptr := mload(0x40)
let table := add(mptr, 0x60)
// Store lookup table that maps an integer from 0 to 99 into a 2-byte ASCII equivalent
mstore(table, 0x0000000000000000000000000000000000000000000000000000000000003030)
mstore(add(table, 0x20), 0x3031303230333034303530363037303830393130313131323133313431353136)
mstore(add(table, 0x40), 0x3137313831393230323132323233323432353236323732383239333033313332)
mstore(add(table, 0x60), 0x3333333433353336333733383339343034313432343334343435343634373438)
mstore(add(table, 0x80), 0x3439353035313532353335343535353635373538353936303631363236333634)
mstore(add(table, 0xa0), 0x3635363636373638363937303731373237333734373537363737373837393830)
mstore(add(table, 0xc0), 0x3831383238333834383538363837383838393930393139323933393439353936)
mstore(add(table, 0xe0), 0x3937393839390000000000000000000000000000000000000000000000000000)
/**
* Convert `input` into ASCII.
*
* Slice 2 base-10 digits off of the input, use to index the ASCII lookup table.
*
* We start from the least significant digits, write results into mem backwards,
* this prevents us from overwriting memory despite the fact that each mload
* only contains 2 byteso f useful data.
**/
{
let v := input
mstore(0x1e, mload(add(table, shl(1, mod(v, 100)))))
mstore(0x1c, mload(add(table, shl(1, mod(div(v, 100), 100)))))
mstore(0x1a, mload(add(table, shl(1, mod(div(v, 10000), 100)))))
mstore(0x18, mload(add(table, shl(1, mod(div(v, 1000000), 100)))))
mstore(0x16, mload(add(table, shl(1, mod(div(v, 100000000), 100)))))
mstore(0x14, mload(add(table, shl(1, mod(div(v, 10000000000), 100)))))
mstore(0x12, mload(add(table, shl(1, mod(div(v, 1000000000000), 100)))))
mstore(0x10, mload(add(table, shl(1, mod(div(v, 100000000000000), 100)))))
mstore(0x0e, mload(add(table, shl(1, mod(div(v, 10000000000000000), 100)))))
mstore(0x0c, mload(add(table, shl(1, mod(div(v, 1000000000000000000), 100)))))
mstore(0x0a, mload(add(table, shl(1, mod(div(v, 100000000000000000000), 100)))))
mstore(0x08, mload(add(table, shl(1, mod(div(v, 10000000000000000000000), 100)))))
mstore(0x06, mload(add(table, shl(1, mod(div(v, 1000000000000000000000000), 100)))))
mstore(0x04, mload(add(table, shl(1, mod(div(v, 100000000000000000000000000), 100)))))
mstore(0x02, mload(add(table, shl(1, mod(div(v, 10000000000000000000000000000), 100)))))
mstore(0x00, mload(add(table, shl(1, mod(div(v, 1000000000000000000000000000000), 100)))))
mstore(add(mptr, 0x40), mload(0x1e))
v := div(v, 100000000000000000000000000000000)
if v {
mstore(0x1e, mload(add(table, shl(1, mod(v, 100)))))
mstore(0x1c, mload(add(table, shl(1, mod(div(v, 100), 100)))))
mstore(0x1a, mload(add(table, shl(1, mod(div(v, 10000), 100)))))
mstore(0x18, mload(add(table, shl(1, mod(div(v, 1000000), 100)))))
mstore(0x16, mload(add(table, shl(1, mod(div(v, 100000000), 100)))))
mstore(0x14, mload(add(table, shl(1, mod(div(v, 10000000000), 100)))))
mstore(0x12, mload(add(table, shl(1, mod(div(v, 1000000000000), 100)))))
mstore(0x10, mload(add(table, shl(1, mod(div(v, 100000000000000), 100)))))
mstore(0x0e, mload(add(table, shl(1, mod(div(v, 10000000000000000), 100)))))
mstore(0x0c, mload(add(table, shl(1, mod(div(v, 1000000000000000000), 100)))))
mstore(0x0a, mload(add(table, shl(1, mod(div(v, 100000000000000000000), 100)))))
mstore(0x08, mload(add(table, shl(1, mod(div(v, 10000000000000000000000), 100)))))
mstore(0x06, mload(add(table, shl(1, mod(div(v, 1000000000000000000000000), 100)))))
mstore(0x04, mload(add(table, shl(1, mod(div(v, 100000000000000000000000000), 100)))))
mstore(0x02, mload(add(table, shl(1, mod(div(v, 10000000000000000000000000000), 100)))))
mstore(0x00, mload(add(table, shl(1, mod(div(v, 1000000000000000000000000000000), 100)))))
mstore(add(mptr, 0x20), mload(0x1e))
}
v := div(v, 100000000000000000000000000000000)
if v {
mstore(0x1e, mload(add(table, shl(1, mod(v, 100)))))
mstore(0x1c, mload(add(table, shl(1, mod(div(v, 100), 100)))))
mstore(0x1a, mload(add(table, shl(1, mod(div(v, 10000), 100)))))
mstore(0x18, mload(add(table, shl(1, mod(div(v, 1000000), 100)))))
mstore(0x16, mload(add(table, shl(1, mod(div(v, 100000000), 100)))))
mstore(0x14, mload(add(table, shl(1, mod(div(v, 10000000000), 100)))))
mstore(0x12, mload(add(table, shl(1, mod(div(v, 1000000000000), 100)))))
mstore(mptr, mload(0x1e))
}
}
// get the length of the input
let len := 1
{
if gt(input, 999999999999999999999999999999999999999) {
len := add(len, 39)
input := div(input, 1000000000000000000000000000000000000000)
}
if gt(input, 99999999999999999999) {
len := add(len, 20)
input := div(input, 100000000000000000000)
}
if gt(input, 9999999999) {
len := add(len, 10)
input := div(input, 10000000000)
}
if gt(input, 99999) {
len := add(len, 5)
input := div(input, 100000)
}
if gt(input, 999) {
len := add(len, 3)
input := div(input, 1000)
}
if gt(input, 99) {
len := add(len, 2)
input := div(input, 100)
}
len := add(len, gt(input, 9))
}
let offset := sub(96, len)
let oldlen := mload(result)
mstore(result, add(len, oldlen))
mstore(add(add(result, oldlen), 0x20), mload(add(mptr, offset)))
mstore(add(add(result, oldlen), 0x40), mload(add(add(mptr, 0x20), offset)))
mstore(add(add(result, oldlen), 0x60), mload(add(add(mptr, 0x40), offset)))
}
}
function appendAddress(address input, bytes32 stringPtr) internal pure {
bytes32 mut;
assembly {
mut := shl(96, input)
}
append0x(stringPtr);
appendBytes32(mut, stringPtr);
assembly {
let len := mload(stringPtr)
mstore(stringPtr, sub(len, 24))
}
}
function appendBytes32(bytes32 input, bytes32 result) internal pure {
if (uint256(input) == 0x00) {
assembly {
let len := mload(result)
mstore(result, add(len, 0x40))
mstore(add(add(result, len), 0x20), 0x3030303030303030303030303030303030303030303030303030303030303030)
mstore(add(add(result, len), 0x40), 0x3030303030303030303030303030303030303030303030303030303030303030)
}
}
assembly {
let table := mload(0x40)
// Store lookup table that maps an integer from 0 to 99 into a 2-byte ASCII equivalent
// Store lookup table that maps an integer from 0 to ff into a 2-byte ASCII equivalent
mstore(add(table, 0x1e), 0x3030303130323033303430353036303730383039306130623063306430653066)
mstore(add(table, 0x3e), 0x3130313131323133313431353136313731383139316131623163316431653166)
mstore(add(table, 0x5e), 0x3230323132323233323432353236323732383239326132623263326432653266)
mstore(add(table, 0x7e), 0x3330333133323333333433353336333733383339336133623363336433653366)
mstore(add(table, 0x9e), 0x3430343134323433343434353436343734383439346134623463346434653466)
mstore(add(table, 0xbe), 0x3530353135323533353435353536353735383539356135623563356435653566)
mstore(add(table, 0xde), 0x3630363136323633363436353636363736383639366136623663366436653666)
mstore(add(table, 0xfe), 0x3730373137323733373437353736373737383739376137623763376437653766)
mstore(add(table, 0x11e), 0x3830383138323833383438353836383738383839386138623863386438653866)
mstore(add(table, 0x13e), 0x3930393139323933393439353936393739383939396139623963396439653966)
mstore(add(table, 0x15e), 0x6130613161326133613461356136613761386139616161626163616461656166)
mstore(add(table, 0x17e), 0x6230623162326233623462356236623762386239626162626263626462656266)
mstore(add(table, 0x19e), 0x6330633163326333633463356336633763386339636163626363636463656366)
mstore(add(table, 0x1be), 0x6430643164326433643464356436643764386439646164626463646464656466)
mstore(add(table, 0x1de), 0x6530653165326533653465356536653765386539656165626563656465656566)
mstore(add(table, 0x1fe), 0x6630663166326633663466356636663766386639666166626663666466656666)
/**
* Convert `input` into ASCII.
*
* Slice 2 base-10 digits off of the input, use to index the ASCII lookup table.
*
* We start from the least significant digits, write results into mem backwards,
* this prevents us from overwriting memory despite the fact that each mload
* only contains 2 byteso f useful data.
**/
let base := input
function slice(v, tableptr) {
mstore(0x1e, mload(add(tableptr, shl(1, and(v, 0xff)))))
mstore(0x1c, mload(add(tableptr, shl(1, and(shr(8, v), 0xff)))))
mstore(0x1a, mload(add(tableptr, shl(1, and(shr(16, v), 0xff)))))
mstore(0x18, mload(add(tableptr, shl(1, and(shr(24, v), 0xff)))))
mstore(0x16, mload(add(tableptr, shl(1, and(shr(32, v), 0xff)))))
mstore(0x14, mload(add(tableptr, shl(1, and(shr(40, v), 0xff)))))
mstore(0x12, mload(add(tableptr, shl(1, and(shr(48, v), 0xff)))))
mstore(0x10, mload(add(tableptr, shl(1, and(shr(56, v), 0xff)))))
mstore(0x0e, mload(add(tableptr, shl(1, and(shr(64, v), 0xff)))))
mstore(0x0c, mload(add(tableptr, shl(1, and(shr(72, v), 0xff)))))
mstore(0x0a, mload(add(tableptr, shl(1, and(shr(80, v), 0xff)))))
mstore(0x08, mload(add(tableptr, shl(1, and(shr(88, v), 0xff)))))
mstore(0x06, mload(add(tableptr, shl(1, and(shr(96, v), 0xff)))))
mstore(0x04, mload(add(tableptr, shl(1, and(shr(104, v), 0xff)))))
mstore(0x02, mload(add(tableptr, shl(1, and(shr(112, v), 0xff)))))
mstore(0x00, mload(add(tableptr, shl(1, and(shr(120, v), 0xff)))))
}
let len := mload(result)
mstore(result, add(len, 0x40))
slice(base, table)
mstore(add(add(len, result), 0x40), mload(0x1e))
base := shr(128, base)
slice(base, table)
mstore(add(add(len, result), 0x20), mload(0x1e))
}
}
function initErrorPtr() internal pure returns (bytes32, bytes32) {
bytes32 mPtr;
bytes32 errorPtr;
assembly {
mPtr := mload(0x40)
mstore(0x40, add(mPtr, 0x1000)) // let's reserve a LOT of memory for our error string.
mstore(mPtr, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(add(mPtr, 0x04), 0x20)
mstore(add(mPtr, 0x24), 0)
errorPtr := add(mPtr, 0x24)
}
return (mPtr, errorPtr);
}
}
| Store lookup table that maps an integer from 0 to 99 into a 2-byte ASCII equivalent Convert `input` into ASCII. Slice 2 base-10 digits off of the input, use to index the ASCII lookup table. We start from the least significant digits, write results into mem backwards, this prevents us from overwriting memory despite the fact that each mload only contains 2 byteso f useful data./ | function appendUint(uint256 input, bytes32 result) internal pure {
if (input < 10) {
assembly {
let len := mload(result)
mstore(result, add(len, 0x01))
mstore8(add(add(len, result), 0x20), add(input, 0x30))
}
return;
}
assembly {
let mptr := mload(0x40)
let table := add(mptr, 0x60)
mstore(table, 0x0000000000000000000000000000000000000000000000000000000000003030)
mstore(add(table, 0x20), 0x3031303230333034303530363037303830393130313131323133313431353136)
mstore(add(table, 0x40), 0x3137313831393230323132323233323432353236323732383239333033313332)
mstore(add(table, 0x60), 0x3333333433353336333733383339343034313432343334343435343634373438)
mstore(add(table, 0x80), 0x3439353035313532353335343535353635373538353936303631363236333634)
mstore(add(table, 0xa0), 0x3635363636373638363937303731373237333734373537363737373837393830)
mstore(add(table, 0xc0), 0x3831383238333834383538363837383838393930393139323933393439353936)
mstore(add(table, 0xe0), 0x3937393839390000000000000000000000000000000000000000000000000000)
{
let v := input
mstore(0x1e, mload(add(table, shl(1, mod(v, 100)))))
mstore(0x1c, mload(add(table, shl(1, mod(div(v, 100), 100)))))
mstore(0x1a, mload(add(table, shl(1, mod(div(v, 10000), 100)))))
mstore(0x18, mload(add(table, shl(1, mod(div(v, 1000000), 100)))))
mstore(0x16, mload(add(table, shl(1, mod(div(v, 100000000), 100)))))
mstore(0x14, mload(add(table, shl(1, mod(div(v, 10000000000), 100)))))
mstore(0x12, mload(add(table, shl(1, mod(div(v, 1000000000000), 100)))))
mstore(0x10, mload(add(table, shl(1, mod(div(v, 100000000000000), 100)))))
mstore(0x0e, mload(add(table, shl(1, mod(div(v, 10000000000000000), 100)))))
mstore(0x0c, mload(add(table, shl(1, mod(div(v, 1000000000000000000), 100)))))
mstore(0x0a, mload(add(table, shl(1, mod(div(v, 100000000000000000000), 100)))))
mstore(0x08, mload(add(table, shl(1, mod(div(v, 10000000000000000000000), 100)))))
mstore(0x06, mload(add(table, shl(1, mod(div(v, 1000000000000000000000000), 100)))))
mstore(0x04, mload(add(table, shl(1, mod(div(v, 100000000000000000000000000), 100)))))
mstore(0x02, mload(add(table, shl(1, mod(div(v, 10000000000000000000000000000), 100)))))
mstore(0x00, mload(add(table, shl(1, mod(div(v, 1000000000000000000000000000000), 100)))))
mstore(add(mptr, 0x40), mload(0x1e))
v := div(v, 100000000000000000000000000000000)
if v {
mstore(0x1e, mload(add(table, shl(1, mod(v, 100)))))
mstore(0x1c, mload(add(table, shl(1, mod(div(v, 100), 100)))))
mstore(0x1a, mload(add(table, shl(1, mod(div(v, 10000), 100)))))
mstore(0x18, mload(add(table, shl(1, mod(div(v, 1000000), 100)))))
mstore(0x16, mload(add(table, shl(1, mod(div(v, 100000000), 100)))))
mstore(0x14, mload(add(table, shl(1, mod(div(v, 10000000000), 100)))))
mstore(0x12, mload(add(table, shl(1, mod(div(v, 1000000000000), 100)))))
mstore(0x10, mload(add(table, shl(1, mod(div(v, 100000000000000), 100)))))
mstore(0x0e, mload(add(table, shl(1, mod(div(v, 10000000000000000), 100)))))
mstore(0x0c, mload(add(table, shl(1, mod(div(v, 1000000000000000000), 100)))))
mstore(0x0a, mload(add(table, shl(1, mod(div(v, 100000000000000000000), 100)))))
mstore(0x08, mload(add(table, shl(1, mod(div(v, 10000000000000000000000), 100)))))
mstore(0x06, mload(add(table, shl(1, mod(div(v, 1000000000000000000000000), 100)))))
mstore(0x04, mload(add(table, shl(1, mod(div(v, 100000000000000000000000000), 100)))))
mstore(0x02, mload(add(table, shl(1, mod(div(v, 10000000000000000000000000000), 100)))))
mstore(0x00, mload(add(table, shl(1, mod(div(v, 1000000000000000000000000000000), 100)))))
mstore(add(mptr, 0x20), mload(0x1e))
}
v := div(v, 100000000000000000000000000000000)
if v {
mstore(0x1e, mload(add(table, shl(1, mod(v, 100)))))
mstore(0x1c, mload(add(table, shl(1, mod(div(v, 100), 100)))))
mstore(0x1a, mload(add(table, shl(1, mod(div(v, 10000), 100)))))
mstore(0x18, mload(add(table, shl(1, mod(div(v, 1000000), 100)))))
mstore(0x16, mload(add(table, shl(1, mod(div(v, 100000000), 100)))))
mstore(0x14, mload(add(table, shl(1, mod(div(v, 10000000000), 100)))))
mstore(0x12, mload(add(table, shl(1, mod(div(v, 1000000000000), 100)))))
mstore(mptr, mload(0x1e))
}
}
{
if gt(input, 999999999999999999999999999999999999999) {
len := add(len, 39)
input := div(input, 1000000000000000000000000000000000000000)
}
if gt(input, 99999999999999999999) {
len := add(len, 20)
input := div(input, 100000000000000000000)
}
if gt(input, 9999999999) {
len := add(len, 10)
input := div(input, 10000000000)
}
if gt(input, 99999) {
len := add(len, 5)
input := div(input, 100000)
}
if gt(input, 999) {
len := add(len, 3)
input := div(input, 1000)
}
if gt(input, 99) {
len := add(len, 2)
input := div(input, 100)
}
len := add(len, gt(input, 9))
}
let offset := sub(96, len)
let oldlen := mload(result)
mstore(result, add(len, oldlen))
mstore(add(add(result, oldlen), 0x20), mload(add(mptr, offset)))
mstore(add(add(result, oldlen), 0x40), mload(add(add(mptr, 0x20), offset)))
mstore(add(add(result, oldlen), 0x60), mload(add(add(mptr, 0x40), offset)))
}
}
| 12,616,845 |
// SPDX-License-Identifier: Apache-2.0
/**
* Copyright 2021 weiWard LLC
*
* 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.7.6;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "./ERC20TxFeeData.sol";
import "../ERC20/ERC20Upgradeable.sol";
import "../interfaces/IERC20TxFee.sol";
import "../../rewards/interfaces/IFeeLogic.sol";
contract ERC20TxFeeUpgradeable is
Initializable,
ContextUpgradeable,
ERC20Upgradeable,
ERC20TxFeeData,
IERC20TxFee
{
using SafeMath for uint256;
// solhint-disable-next-line func-name-mixedcase
function __ERC20TxFee_init(address feeLogic_) internal initializer {
__ERC20_init();
__ERC20TxFee_init_unchained(feeLogic_);
}
// solhint-disable-next-line func-name-mixedcase
function __ERC20TxFee_init_unchained(address feeLogic_)
internal
initializer
{
require(feeLogic_ != address(0), "ERC20TxFee: feeLogic zero address");
__ERC20_init_unchained();
_feeLogic = feeLogic_;
}
/* Public Views */
/**
* @dev Returns the feeLogic handler address.
*/
function feeLogic() public view virtual override returns (address) {
return _feeLogic;
}
/* Internal Mutators */
/**
* @dev Overrides {ERC20-_transfer} to implement a fee on transfers.
*
* Emits a {Transfer} event. Emits a second {Transfer} event for the fee.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - `_feeLogic` implements {IFeeLogic}
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual override {
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"
);
IFeeLogic feeHandler = IFeeLogic(_feeLogic);
uint256 fee = feeHandler.getFee(sender, recipient, amount);
uint256 amountSubFee = amount.sub(fee);
_balances[recipient] = _balances[recipient].add(amountSubFee);
emit Transfer(sender, recipient, amountSubFee);
if (fee != 0) {
address feeRecipient = feeHandler.recipient();
_balances[feeRecipient] = _balances[feeRecipient].add(fee);
emit Transfer(sender, feeRecipient, fee);
feeHandler.notify(fee);
}
}
}
| solhint-disable-next-line func-name-mixedcase | function __ERC20TxFee_init_unchained(address feeLogic_)
internal
initializer
{
require(feeLogic_ != address(0), "ERC20TxFee: feeLogic zero address");
__ERC20_init_unchained();
_feeLogic = feeLogic_;
}
| 12,696,623 |
./full_match/3/0x0e9638c50d2f60057C958201e3881b2D7c7EE76C/sources/ConnectRenter.sol | TODO create a proxy method to allow call on original NFT by bytecode/method args - dynamic lookup? Validate input Validate caller owns it Setup Loan | function enableTokenForLending(uint256 _tokenId, uint256 _periodInSecs, uint256 _depositInWei) public returns (bool) {
require(_depositInWei > 0, "Must have a deposit");
require(_periodInSecs > 0, "Must have a period in secs");
require(tokensAvailableToLoan[_tokenId].tokenId == 0, "Token already placed for sale");
require(tokenContract.ownerOf(_tokenId) == msg.sender, "Caller does not own the NFT");
tokensAvailableToLoan[_tokenId] = Loan({
tokenId : _tokenId,
lender : msg.sender,
borrower : address(0x0),
isEscrowed : true,
isBorrowed : false,
start : 0,
end : 0,
periodInSecs: _periodInSecs,
depositInWei : _depositInWei
});
require(isTokenEscrowed(_tokenId), "Token not correctly escrowed");
totalTokens = totalTokens + 1;
return true;
}
| 8,195,250 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "hardhat/console.sol";
/**
* @title DEX Template
* @author stevepham.eth and m00npapi.eth
* @notice Empty DEX.sol that just outlines what features could be part of the challenge (up to you!)
* @dev We want to create an automatic market where our contract will hold reserves of both ETH and 🎈 Balloons. These reserves will provide liquidity that allows anyone to swap between the assets.
* NOTE: functions outlined here are what work with the front end of this branch/repo. Also return variable names that may need to be specified exactly may be referenced (if you are confused, see solutions folder in this repo and/or cross reference with front-end code).
*/
contract DEX {
/* ========== GLOBAL VARIABLES ========== */
using SafeMath for uint256; //outlines use of SafeMath for uint256 variables
IERC20 token; //instantiates the imported contract
uint256 public totalLiquidity;
mapping(address => uint256) public liquidity;
/* ========== EVENTS ========== */
/**
* @notice Emitted when ethToToken() swap transacted
*/
event EthToTokenSwap(
address recipient,
string message,
uint256 ethAmount,
uint256 tokenAmount
);
/**
* @notice Emitted when tokenToEth() swap transacted
*/
event TokenToEthSwap(
address recipient,
string message,
uint256 ethAmount,
uint256 tokenAmount
);
/**
* @notice Emitted when liquidity provided to DEX and mints LPTs.
*/
event LiquidityProvided(
address recipient,
uint256 liquidityMinted,
uint256 ethAmount,
uint256 tokenAmount
);
/**
* @notice Emitted when liquidity removed from DEX and decreases LPT count within DEX.
*/
event LiquidityRemoved(
address recipient,
uint256 liquidityRemoved,
uint256 ethAmount,
uint256 tokenAmount
);
/* ========== CONSTRUCTOR ========== */
constructor(address token_addr) public {
token = IERC20(token_addr); //specifies the token address that will hook into the interface and be used through the variable 'token'
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice initializes amount of tokens that will be transferred to the DEX itself from the erc20 contract mintee (and only them based on how Balloons.sol is written). Loads contract up with both ETH and Balloons.
* @param tokens amount to be transferred to DEX
* @return totalLiquidity is the number of LPTs minting as a result of deposits made to DEX contract
* NOTE: since ratio is 1:1, this is fine to initialize the totalLiquidity (wrt to balloons) as equal to eth balance of contract.
*/
function init(uint256 tokens) public payable returns (uint256) {
require(totalLiquidity == 0, "Already initialised");
totalLiquidity = address(this).balance; // no. of ETH sent to this contract
liquidity[msg.sender] = totalLiquidity;
require(token.transferFrom(msg.sender, address(this), tokens));
return totalLiquidity;
}
/**
* @notice returns yOutput, or yDelta for xInput (or xDelta)
* @dev Follow along with the [original tutorial](https://medium.com/@austin_48503/%EF%B8%8F-minimum-viable-exchange-d84f30bd0c90) Price section for an understanding of the DEX's pricing model and for a price function to add to your contract. You may need to update the Solidity syntax (e.g. use + instead of .add, * instead of .mul, etc). Deploy when you are done.
*/
function price(
uint256 xInput,
uint256 xReserves,
uint256 yReserves
) public view returns (uint256 yOutput) {
// xReserves * yReserves = k;
uint256 inputAmountWithFee = xInput * 997;
uint256 numerator = inputAmountWithFee * yReserves;
uint256 denominator = xReserves * 1000 + inputAmountWithFee;
return numerator / denominator;
}
/**
* @notice returns liquidity for a user. Note this is not needed typically due to the `liquidity()` mapping variable being public and having a getter as a result. This is left though as it is used within the front end code (App.jsx).
*/
function getLiquidity(address lp) public view returns (uint256) {
return liquidity[lp];
}
/**
* @notice sends Ether to DEX in exchange for $BAL
*/
function ethToToken() public payable returns (uint256 tokenOutput) {
require(msg.value > 0, "You need to send some ETH");
uint256 preTxnReserves = address(this).balance - msg.value;
uint256 tokenReserves = token.balanceOf(address(this));
tokenOutput = this.price(msg.value, preTxnReserves, tokenReserves);
require(token.transfer(msg.sender, tokenOutput));
emit EthToTokenSwap(
msg.sender,
"Eth -> Balloons",
msg.value,
tokenOutput
);
return tokenOutput;
}
/**
* @notice sends $BAL tokens to DEX in exchange for Ether
*/
function tokenToEth(uint256 tokenInput) public returns (uint256 ethOutput) {
require(tokenInput > 0, "You need to specify amount of tokens to swap");
uint256 ethReserves = address(this).balance;
uint256 tokenReserves = token.balanceOf(address(this));
ethOutput = this.price(tokenInput, tokenReserves, ethReserves);
require(
token.transferFrom(msg.sender, address(this), tokenInput),
"Token transfer failed. Check allowance"
);
(bool sent, ) = msg.sender.call{value: ethOutput}("");
require(sent, "Unable to transfer ETH to you");
emit TokenToEthSwap(
msg.sender,
"Balloons -> ETH",
ethOutput,
tokenInput
);
return ethOutput;
}
/**
* @notice allows deposits of $BAL and $ETH to liquidity pool
* NOTE: parameter is the msg.value sent with this function call. That amount is used to determine the amount of $BAL needed as well and taken from the depositor.
* NOTE: user has to make sure to give DEX approval to spend their tokens on their behalf by calling approve function prior to this function call.
* NOTE: Equal parts of both assets will be removed from the user's wallet with respect to the price outlined by the AMM.
*/
function deposit() public payable returns (uint256 tokensDeposited) {
require(msg.value > 0, "You need to send some ETH");
uint256 preTxnReserves = address(this).balance - msg.value;
uint256 tokenReserves = token.balanceOf(address(this));
uint256 tokenInput = (msg.value * tokenReserves) / preTxnReserves + 1;
uint256 liquidityMinted = (msg.value * totalLiquidity) / preTxnReserves;
totalLiquidity = totalLiquidity + liquidityMinted;
liquidity[msg.sender] = liquidity[msg.sender] + liquidityMinted;
uint256 allowance = token.allowance(msg.sender, address(this));
console.log("tokenInput", tokenInput);
console.log("allowance", allowance);
require(
token.transferFrom(msg.sender, address(this), tokenInput),
"Token transfer failed. Check allowance"
);
emit LiquidityProvided(
msg.sender,
liquidityMinted,
msg.value,
tokenInput
);
tokensDeposited = tokenInput;
return tokensDeposited;
}
/**
* @notice allows withdrawal of $BAL and $ETH from liquidity pool
* NOTE: with this current code, the msg caller could end up getting very little back if the liquidity is super low in the pool. I guess they could see that with the UI.
*/
function withdraw(uint256 amount)
public
returns (uint256 ethAmount, uint256 tokenAmount)
{
require(
liquidity[msg.sender] >= amount,
"You have no liquidity in the pool"
);
uint256 tokenReserve = token.balanceOf(address(this));
uint256 ethReserve = address(this).balance;
uint256 tokenAmount = (amount * tokenReserve) / totalLiquidity;
uint256 ethAmount = (amount * ethReserve) / totalLiquidity;
liquidity[msg.sender] = liquidity[msg.sender] - amount;
totalLiquidity = totalLiquidity - amount;
(bool sent, ) = payable(msg.sender).call{value: ethAmount}("");
require(sent, "Unable to transfer ETH back to you");
require(
token.transfer(msg.sender, tokenAmount),
"Unable to tranfer Balloons back to you"
);
emit LiquidityRemoved(msg.sender, amount, ethAmount, tokenAmount);
return (ethAmount, tokenAmount);
}
}
| sends $BAL tokens to DEX in exchange for Ether/ | function tokenToEth(uint256 tokenInput) public returns (uint256 ethOutput) {
require(tokenInput > 0, "You need to specify amount of tokens to swap");
uint256 ethReserves = address(this).balance;
uint256 tokenReserves = token.balanceOf(address(this));
ethOutput = this.price(tokenInput, tokenReserves, ethReserves);
require(
token.transferFrom(msg.sender, address(this), tokenInput),
"Token transfer failed. Check allowance"
);
require(sent, "Unable to transfer ETH to you");
emit TokenToEthSwap(
msg.sender,
"Balloons -> ETH",
ethOutput,
tokenInput
);
return ethOutput;
}
| 14,033,014 |
/**
*Submitted for verification at Etherscan.io on 2022-03-12
*/
// .....
// .:~7JRNYGGP55J7^:.
// .~J5PPGGP5PPPP55555J?~.....
// .!YJ5P55PPYYY5555YYYY???~:^~~~!!77777~^.
// .:^~~~?Y??JYJ????????JJYJJ7~^^::: . ..^!J5Y!.
// :~7?7!^:..?PYJJYJ7777?J?7?77~~~^^:::.. .. .7GGJ.
// .!YY7^. :?JYJ??77???????7!!~~~~~^^:... .. ^GGG:
// ~PB?. .~~!?JYJ?JJ?!~~~~~!^:::....... . :?GG5^
// .P&&^ .^^^^^~~~~~^::::............ . .~?PGP?:
// :&&&5: .~:::::^^:.........::..... .:^7J5PGPJ~.
// ^P#&&B57^:. .:::::::::........::....:^~!?JY5PPP5?!:.
// .~JG#&&&#BBGP5555YYJJJJJ???JJYY5555PPPP5YJ7~^....
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
/*
* @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);
}
}
/**
* @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 String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional 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);
}
/**
* @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.
*
* The contract is fully ERC621 Enumerable compatible, including cheap on-chain enumeration.
* The enumeration is optimized by using arrays of uint16 for efficient packing.
* As limitation, the maximum NFT supply can be max(uint16) tokens.
*
* Assumes serials are sequentially minted starting at 1 (e.g. 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*/
contract ERC721P is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
uint16 private currentIndex;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
mapping(uint256 => address) private _ownerships;
// Mapping owner address to tokens
mapping(address => uint16[]) private _addressTokens;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(
string memory name_,
string memory symbol_
) {
_name = name_;
_symbol = symbol_;
}
/**
* @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 > 0 && index <= totalSupply(), "ERC721P: global index out of bounds");
return index;
}
/**
* @dev not part of standard IERC721Enumerable
* This function returns all the tokens of a certain owner as an array
* and is very cheap to use on-chain
*/
function tokensOfOwner(address owner)
public
view
returns (uint16[] memory)
{
return _addressTokens[owner];
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721P: owner index out of bounds");
return _addressTokens[owner][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), "ERC721P: balance query for the zero address");
return _addressTokens[owner].length;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
address owner = _ownerships[tokenId];
require(owner != address(0), "ERC721P: owner query for nonexistent token");
return _ownerships[tokenId];
}
/**
* @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(
ownerOf(tokenId) != address(0),
"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 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 virtual returns (bool) {
return _ownerships[tokenId] != address(0);
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = _ownerships[tokenId];
require(to != owner, "ERC721P: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721P: 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), "ERC721P: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721P: 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 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),
"ERC721P: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Doesn't check if the target can receive ERC721's.
* Requirements:
*
* - `to` cannot be the zero address
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity
) internal {
require(to != address(0), "ERC721P: mint to the zero address");
_beforeTokenTransfers(address(0), to, currentIndex + 1, quantity);
for (uint256 i = 0; i < quantity; i++) {
currentIndex++;
_addressTokens[to].push(currentIndex);
_ownerships[currentIndex] = to;
emit Transfer(address(0), to, currentIndex);
}
_afterTokenTransfers(address(0), to, currentIndex, quantity);
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
require(to != address(0), "ERC721P: mint to the zero address");
_beforeTokenTransfers(address(0), to, currentIndex + 1, quantity);
for (uint256 i = 0; i < quantity; i++) {
currentIndex++;
_addressTokens[to].push(currentIndex);
_ownerships[currentIndex] = to;
emit Transfer(address(0), to, currentIndex);
require(
_checkOnERC721Received(address(0), to, currentIndex, _data),
"ERC721P: transfer to non ERC721Receiver implementer"
);
}
_afterTokenTransfers(address(0), to, currentIndex, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
address prevOwner = ownerOf(tokenId);
require(
prevOwner == from,
"ERC721P: transfer from incorrect owner"
);
bool isApprovedOrOwner = (_msgSender() == prevOwner ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwner, _msgSender()));
require(
isApprovedOrOwner,
"ERC721P: transfer caller is not owner nor approved"
);
require(to != address(0), "ERC721P: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwner);
// Deletes the tokenId from the current owner
_findAndDelete(from, uint16(tokenId));
// Adds the tokenId to the new owner
_addressTokens[to].push(uint16(tokenId));
_ownerships[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Deletes `tokenId` from the `owner` tokens array.
*
* Doesn't preserve order of tokens.
*/
function _findAndDelete(address owner, uint16 tokenId) internal {
for (uint i=0; i < _addressTokens[owner].length - 1; i++){
if (_addressTokens[owner][i] == tokenId){
_addressTokens[owner][i] = _addressTokens[owner][_addressTokens[owner].length - 1];
_addressTokens[owner].pop();
return;
}
}
_addressTokens[owner].pop();
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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("ERC721P: 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 {}
}
interface KeysNFT{
function redeem(address _to, uint256 _amounts) external;
}
contract XoloNFT is ERC721P, Ownable {
string private _baseTokenURI;
string public XOLO_PROVENANCE = "";
uint256 public startingIndexBlock;
uint256 public startingIndex;
uint256 public maxSupply = 20000;
uint256 public auctionSupply = 10000;
uint256 public auctionMintCount;
uint256 public saleStart;
uint256 public claimStart;
uint256 public revealDate;
uint256 public decreaseInterval = 300; // in minutes, hits last price after 4h
uint256 public decreasePerInterval = 40229166666666666;
uint256 public totalIntervals = 48;
uint256 public startPrice = 2 ether;
uint256 public endPrice = 0.069 ether;
uint256 public maxPurchaseAmt = 10;
bool public saleIsActive = true;
bool public claimIsActive = true;
address public keysAddress;
address public beneficiaryAddress;
constructor(
uint256 _saleStart,
uint256 _revealDate,
address _beneficiaryAddress
) ERC721P("Villagers of XOLO", "XOLO") {
saleStart = _saleStart;
claimStart = saleStart + 86400;
revealDate = _revealDate;
beneficiaryAddress = _beneficiaryAddress;
}
function withdraw() external {
require(msg.sender == beneficiaryAddress, "Not beneficiary");
uint balance = address(this).balance;
payable(beneficiaryAddress).transfer(balance);
}
function getCurrentPrice() public view returns(uint256) {
uint256 passedIntervals = (block.timestamp - saleStart) / decreaseInterval;
if (passedIntervals >= totalIntervals) {
return endPrice;
} else {
unchecked{
return startPrice - passedIntervals * decreasePerInterval;
}
}
}
function auctionMint(uint256 _amount) external payable {
require( block.timestamp > saleStart && saleIsActive, "Auction not active");
require( msg.sender == tx.origin, "Tm8gcm9ib3Rz");
require( (auctionMintCount + _amount) <= auctionSupply, "Minting would exceed max auction supply");
require( _amount <= maxPurchaseAmt, "Can't mint that many at once");
uint256 currentMintPrice = getCurrentPrice();
require( (currentMintPrice * _amount) <= msg.value, "ETH value sent is not correct");
unchecked {
auctionMintCount += _amount;
}
_mint(_msgSender(), _amount);
if (startingIndexBlock == 0 && (totalSupply() == maxSupply || block.timestamp > revealDate)) {
_setStartingIndex();
}
}
function keyMint(uint256 _amount) external {
require( block.timestamp > claimStart && claimIsActive, "You can't claim yet");
KeysNFT(keysAddress).redeem(_msgSender(), _amount);
_mint(_msgSender(), _amount);
if (startingIndexBlock == 0 && (totalSupply() == maxSupply || block.timestamp >= revealDate)) {
_setStartingIndex();
}
}
function ownerMint(address _to, uint256 _amount) external onlyOwner {
require( (auctionMintCount + _amount) <= auctionSupply, "Minting would exceed max auction supply");
unchecked{
auctionMintCount += _amount;
}
_mint(_to, _amount);
}
function _baseURI() internal view override(ERC721P) returns (string memory) {
return _baseTokenURI;
}
function baseURI() public view returns (string memory) {
return _baseURI();
}
function _setStartingIndex() internal {
require(startingIndexBlock == 0, "Starting index is already set");
startingIndexBlock = block.number - 1;
startingIndex = uint(blockhash(startingIndexBlock)) % maxSupply;
}
function setRevealTimestamp(uint256 _revealTimeStamp) external onlyOwner {
revealDate = _revealTimeStamp;
}
function setSaleStart(uint256 _saleStartTimestamp) external onlyOwner {
saleStart = _saleStartTimestamp;
claimStart = saleStart + 86400;
}
function setClaimStart(uint256 _claimStartTimestamp) external onlyOwner {
claimStart = _claimStartTimestamp;
}
function setDutchDetails(uint256 _decreaseInterval, uint256 _decreasePerInterval, uint256 _totalIntervals, uint256 _startPrice, uint256 _endPrice) external onlyOwner {
decreaseInterval = _decreaseInterval;
decreasePerInterval = _decreasePerInterval;
totalIntervals = _totalIntervals;
startPrice = _startPrice;
endPrice = _endPrice;
}
function setMaxPurchaseAmt(uint256 _newMaxPurchaseAmt) external onlyOwner {
maxPurchaseAmt = _newMaxPurchaseAmt;
}
function setProvenanceHash(string memory provenanceHash) external onlyOwner {
XOLO_PROVENANCE = provenanceHash;
}
function setBaseURI(string calldata newBaseTokenURI) external onlyOwner {
_baseTokenURI = newBaseTokenURI;
}
function changeSaleState() external onlyOwner {
saleIsActive = !saleIsActive;
}
function changeClaimState() external onlyOwner {
claimIsActive = !claimIsActive;
}
function setKeysAddress(address _newAddress) external onlyOwner {
keysAddress = _newAddress;
}
} | Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. The call is not executed if the target address is not a contract. from address representing the previous owner of the given token ID to target address that will receive the tokens tokenId uint256 ID of the token to be transferred _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;
if (reason.length == 0) {
revert("ERC721P: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
| 7,613,683 |
./full_match/1/0xd712A863766dE7e7cA13289A97997E01832A6571/sources/@mimic-fi/v2-smart-vaults-base/contracts/permissions/PermissionsHelpers.sol | Revokes permission from `whos` to perform `what` in `where` through the permissions manager `self` self Permissions manager to be used where Address of the contract where the permission will be revoked whos List of addresses of the accounts that will be unauthorized what Function selector to be unauthorized/ | function unauthorize(PermissionsManager self, IAuthorizer where, address[] memory whos, bytes4 what) internal {
unauthorize(self, where, whos, Arrays.from(what));
}
| 2,974,087 |
pragma solidity 0.5.5;
/**
* @dev Standard interface for a dex proxy contract.
*/
interface Proxy {
/**
* @dev Executes an action.
* @param _target Target of execution.
* @param _a Address usually representing from.
* @param _b Address usually representing to.
* @param _c Integer usually repersenting amount/value/id.
*/
function execute(
address _target,
address _a,
address _b,
uint256 _c
)
external;
}
/**
* @dev Xcert interface.
*/
interface Xcert // is ERC721 metadata enumerable
{
/**
* @dev Creates a new Xcert.
* @param _to The address that will own the created Xcert.
* @param _id The Xcert to be created by the msg.sender.
* @param _imprint Cryptographic asset imprint.
*/
function create(
address _to,
uint256 _id,
bytes32 _imprint
)
external;
/**
* @dev Change URI base.
* @param _uriBase New uriBase.
*/
function setUriBase(
string calldata _uriBase
)
external;
/**
* @dev Returns a bytes4 of keccak256 of json schema representing 0xcert Protocol convention.
* @return Schema id.
*/
function schemaId()
external
view
returns (bytes32 _schemaId);
/**
* @dev Returns imprint for Xcert.
* @param _tokenId Id of the Xcert.
* @return Token imprint.
*/
function tokenImprint(
uint256 _tokenId
)
external
view
returns(bytes32 imprint);
}
/**
* @dev Xcert burnable interface.
*/
interface XcertBurnable // is Xcert
{
/**
* @dev Destroys a specified Xcert. Reverts if not called from Xcert owner or operator.
* @param _tokenId Id of the Xcert we want to destroy.
*/
function destroy(
uint256 _tokenId
)
external;
}
/**
* @dev Xcert nutable interface.
*/
interface XcertMutable // is Xcert
{
/**
* @dev Updates Xcert imprint.
* @param _tokenId Id of the Xcert.
* @param _imprint New imprint.
*/
function updateTokenImprint(
uint256 _tokenId,
bytes32 _imprint
)
external;
}
/**
* @dev Xcert pausable interface.
*/
interface XcertPausable // is Xcert
{
/**
* @dev Sets if Xcerts transfers are paused (can be performed) or not.
* @param _isPaused Pause status.
*/
function setPause(
bool _isPaused
)
external;
}
/**
* @dev Xcert revokable interface.
*/
interface XcertRevokable // is Xcert
{
/**
* @dev Revokes a specified Xcert. Reverts if not called from contract owner or authorized
* address.
* @param _tokenId Id of the Xcert we want to destroy.
*/
function revoke(
uint256 _tokenId
)
external;
}
/**
* @dev Math operations with safety checks that throw on error. This contract is based on the
* source code at:
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol.
*/
library SafeMath
{
/**
* @dev Error constants.
*/
string constant OVERFLOW = "008001";
string constant SUBTRAHEND_GREATER_THEN_MINUEND = "008002";
string constant DIVISION_BY_ZERO = "008003";
/**
* @dev Multiplies two numbers, reverts on overflow.
* @param _factor1 Factor number.
* @param _factor2 Factor number.
* @return The product of the two factors.
*/
function mul(
uint256 _factor1,
uint256 _factor2
)
internal
pure
returns (uint256 product)
{
// 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 (_factor1 == 0)
{
return 0;
}
product = _factor1 * _factor2;
require(product / _factor1 == _factor2, OVERFLOW);
}
/**
* @dev Integer division of two numbers, truncating the quotient, reverts on division by zero.
* @param _dividend Dividend number.
* @param _divisor Divisor number.
* @return The quotient.
*/
function div(
uint256 _dividend,
uint256 _divisor
)
internal
pure
returns (uint256 quotient)
{
// Solidity automatically asserts when dividing by 0, using all gas.
require(_divisor > 0, DIVISION_BY_ZERO);
quotient = _dividend / _divisor;
// assert(_dividend == _divisor * quotient + _dividend % _divisor); // There is no case in which this doesn't hold.
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
* @param _minuend Minuend number.
* @param _subtrahend Subtrahend number.
* @return Difference.
*/
function sub(
uint256 _minuend,
uint256 _subtrahend
)
internal
pure
returns (uint256 difference)
{
require(_subtrahend <= _minuend, SUBTRAHEND_GREATER_THEN_MINUEND);
difference = _minuend - _subtrahend;
}
/**
* @dev Adds two numbers, reverts on overflow.
* @param _addend1 Number.
* @param _addend2 Number.
* @return Sum.
*/
function add(
uint256 _addend1,
uint256 _addend2
)
internal
pure
returns (uint256 sum)
{
sum = _addend1 + _addend2;
require(sum >= _addend1, OVERFLOW);
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo), reverts when
* dividing by zero.
* @param _dividend Number.
* @param _divisor Number.
* @return Remainder.
*/
function mod(
uint256 _dividend,
uint256 _divisor
)
internal
pure
returns (uint256 remainder)
{
require(_divisor != 0, DIVISION_BY_ZERO);
remainder = _dividend % _divisor;
}
}
/**
* @title Contract for setting abilities.
* @dev For optimization purposes the abilities are represented as a bitfield. Maximum number of
* abilities is therefore 256. This is an example(for simplicity is made for max 8 abilities) of how
* this works.
* 00000001 Ability A - number representation 1
* 00000010 Ability B - number representation 2
* 00000100 Ability C - number representation 4
* 00001000 Ability D - number representation 8
* 00010000 Ability E - number representation 16
* etc ...
* To grant abilities B and C, we would need a bitfield of 00000110 which is represented by number
* 6, in other words, the sum of abilities B and C. The same concept works for revoking abilities
* and checking if someone has multiple abilities.
*/
contract Abilitable
{
using SafeMath for uint;
/**
* @dev Error constants.
*/
string constant NOT_AUTHORIZED = "017001";
string constant CANNOT_REVOKE_OWN_SUPER_ABILITY = "017002";
string constant INVALID_INPUT = "017003";
/**
* @dev Ability 1 (00000001) is a reserved ability called super ability. It is an
* ability to grant or revoke abilities of other accounts. Other abilities are determined by the
* implementing contract.
*/
uint8 constant SUPER_ABILITY = 1;
/**
* @dev Maps address to ability ids.
*/
mapping(address => uint256) public addressToAbility;
/**
* @dev Emits when an address is granted an ability.
* @param _target Address to which we are granting abilities.
* @param _abilities Number representing bitfield of abilities we are granting.
*/
event GrantAbilities(
address indexed _target,
uint256 indexed _abilities
);
/**
* @dev Emits when an address gets an ability revoked.
* @param _target Address of which we are revoking an ability.
* @param _abilities Number representing bitfield of abilities we are revoking.
*/
event RevokeAbilities(
address indexed _target,
uint256 indexed _abilities
);
/**
* @dev Guarantees that msg.sender has certain abilities.
*/
modifier hasAbilities(
uint256 _abilities
)
{
require(_abilities > 0, INVALID_INPUT);
require(
addressToAbility[msg.sender] & _abilities == _abilities,
NOT_AUTHORIZED
);
_;
}
/**
* @dev Contract constructor.
* Sets SUPER_ABILITY ability to the sender account.
*/
constructor()
public
{
addressToAbility[msg.sender] = SUPER_ABILITY;
emit GrantAbilities(msg.sender, SUPER_ABILITY);
}
/**
* @dev Grants specific abilities to specified address.
* @param _target Address to grant abilities to.
* @param _abilities Number representing bitfield of abilities we are granting.
*/
function grantAbilities(
address _target,
uint256 _abilities
)
external
hasAbilities(SUPER_ABILITY)
{
addressToAbility[_target] |= _abilities;
emit GrantAbilities(_target, _abilities);
}
/**
* @dev Unassigns specific abilities from specified address.
* @param _target Address of which we revoke abilites.
* @param _abilities Number representing bitfield of abilities we are revoking.
* @param _allowSuperRevoke Additional check that prevents you from removing your own super
* ability by mistake.
*/
function revokeAbilities(
address _target,
uint256 _abilities,
bool _allowSuperRevoke
)
external
hasAbilities(SUPER_ABILITY)
{
if (!_allowSuperRevoke && msg.sender == _target)
{
require((_abilities & 1) == 0, CANNOT_REVOKE_OWN_SUPER_ABILITY);
}
addressToAbility[_target] &= ~_abilities;
emit RevokeAbilities(_target, _abilities);
}
/**
* @dev Check if an address has a specific ability. Throws if checking for 0.
* @param _target Address for which we want to check if it has a specific abilities.
* @param _abilities Number representing bitfield of abilities we are checking.
*/
function isAble(
address _target,
uint256 _abilities
)
external
view
returns (bool)
{
require(_abilities > 0, INVALID_INPUT);
return (addressToAbility[_target] & _abilities) == _abilities;
}
}
/**
* @dev ERC-721 non-fungible token standard.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721
{
/**
* @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are
* created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any
* number of NFTs may be created and assigned without emitting Transfer. At the time of any
* transfer, the approved address for that NFT (if any) is reset to none.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
/**
* @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero
* address indicates there is no approved address. When a Transfer event emits, this also
* indicates that the approved address for that NFT (if any) is reset to none.
*/
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
/**
* @dev This emits when an operator is enabled or disabled for an owner. The operator can manage
* all NFTs of the owner.
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the
* approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is
* the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this
* function checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external;
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice This works identically to the other function with an extra data parameter, except this
* function just sets data to ""
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
/**
* @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
* address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero
* address. Throws if `_tokenId` is not a valid NFT.
* @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
* they mayb be permanently lost.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
/**
* @dev Set or reaffirm the approved address for an NFT.
* @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is
* the current NFT owner, or an authorized operator of the current owner.
* @param _approved The new approved NFT controller.
* @param _tokenId The NFT to approve.
*/
function approve(
address _approved,
uint256 _tokenId
)
external;
/**
* @dev Enables or disables approval for a third party ("operator") to manage all of
* `msg.sender`'s assets. It also emits the ApprovalForAll event.
* @notice The contract MUST allow multiple operators per owner.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval.
*/
function setApprovalForAll(
address _operator,
bool _approved
)
external;
/**
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
* considered invalid, and this function throws for queries about the zero address.
* @param _owner Address for whom to query the balance.
* @return Balance of _owner.
*/
function balanceOf(
address _owner
)
external
view
returns (uint256);
/**
* @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered
* invalid, and queries about them do throw.
* @param _tokenId The identifier for an NFT.
* @return Address of _tokenId owner.
*/
function ownerOf(
uint256 _tokenId
)
external
view
returns (address);
/**
* @dev Get the approved address for a single NFT.
* @notice Throws if `_tokenId` is not a valid NFT.
* @param _tokenId The NFT to find the approved address for.
* @return Address that _tokenId is approved for.
*/
function getApproved(
uint256 _tokenId
)
external
view
returns (address);
/**
* @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise.
* @param _owner The address that owns the NFTs.
* @param _operator The address that acts on behalf of the owner.
* @return True if approved for all, false otherwise.
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
view
returns (bool);
}
/**
* @dev Optional metadata extension for ERC-721 non-fungible token standard.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721Metadata
{
/**
* @dev Returns a descriptive name for a collection of NFTs in this contract.
* @return Representing name.
*/
function name()
external
view
returns (string memory _name);
/**
* @dev Returns a abbreviated name for a collection of NFTs in this contract.
* @return Representing symbol.
*/
function symbol()
external
view
returns (string memory _symbol);
/**
* @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if
* `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file
* that conforms to the "ERC721 Metadata JSON Schema".
* @return URI of _tokenId.
*/
function tokenURI(uint256 _tokenId)
external
view
returns (string memory);
}
/**
* @dev Optional enumeration extension for ERC-721 non-fungible token standard.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721Enumerable
{
/**
* @dev Returns a count of valid NFTs tracked by this contract, where each one of them has an
* assigned and queryable owner not equal to the zero address.
* @return Total supply of NFTs.
*/
function totalSupply()
external
view
returns (uint256);
/**
* @dev Returns the token identifier for the `_index`th NFT. Sort order is not specified.
* @param _index A counter less than `totalSupply()`.
* @return Token id.
*/
function tokenByIndex(
uint256 _index
)
external
view
returns (uint256);
/**
* @dev Returns the token identifier for the `_index`th NFT assigned to `_owner`. Sort order is
* not specified. It throws if `_index` >= `balanceOf(_owner)` or if `_owner` is the zero address,
* representing invalid NFTs.
* @param _owner An address where we are interested in NFTs owned by them.
* @param _index A counter less than `balanceOf(_owner)`.
* @return Token id.
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
external
view
returns (uint256);
}
/**
* @dev ERC-721 interface for accepting safe transfers.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721TokenReceiver
{
/**
* @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the
* recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return
* of other than the magic value MUST result in the transaction being reverted.
* Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing.
* @notice The contract address is always the message sender. A wallet/broker/auction application
* MUST implement the wallet interface if it will accept safe transfers.
* @param _operator The address which called `safeTransferFrom` function.
* @param _from The address which previously owned the token.
* @param _tokenId The NFT identifier which is being transferred.
* @param _data Additional data with no specified format.
* @return Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes calldata _data
)
external
returns(bytes4);
}
/**
* @dev A standard for detecting smart contract interfaces.
* See: https://eips.ethereum.org/EIPS/eip-165.
*/
interface ERC165
{
/**
* @dev Checks if the smart contract implements a specific interface.
* @notice This function uses less than 30,000 gas.
* @param _interfaceID The interface identifier, as specified in ERC-165.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
view
returns (bool);
}
/**
* @dev Implementation of standard to publish supported interfaces.
*/
contract SupportsInterface is
ERC165
{
/**
* @dev Mapping of supported intefraces.
* @notice You must not set element 0xffffffff to true.
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev Contract constructor.
*/
constructor()
public
{
supportedInterfaces[0x01ffc9a7] = true; // ERC165
}
/**
* @dev Function to check which interfaces are suported by this contract.
* @param _interfaceID Id of the interface.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceID];
}
}
/**
* @dev Utility library of inline functions on addresses.
*/
library AddressUtils
{
/**
* @dev Returns whether the target address is a contract.
* @param _addr Address to check.
* @return True if _addr is a contract, false if not.
*/
function isContract(
address _addr
)
internal
view
returns (bool addressCheck)
{
uint256 size;
/**
* XXX Currently there is no better way to check if there is a contract in an address than to
* check the size of the code at that address.
* See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works.
* TODO: Check this again before the Serenity release, because all addresses will be
* contracts then.
*/
assembly { size := extcodesize(_addr) } // solhint-disable-line
addressCheck = size > 0;
}
}
/**
* @dev Optional metadata enumerable implementation for ERC-721 non-fungible token standard.
*/
contract NFTokenMetadataEnumerable is
ERC721,
ERC721Metadata,
ERC721Enumerable,
SupportsInterface
{
using SafeMath for uint256;
using AddressUtils for address;
/**
* @dev Error constants.
*/
string constant ZERO_ADDRESS = "006001";
string constant NOT_VALID_NFT = "006002";
string constant NOT_OWNER_OR_OPERATOR = "006003";
string constant NOT_OWNER_APPROWED_OR_OPERATOR = "006004";
string constant NOT_ABLE_TO_RECEIVE_NFT = "006005";
string constant NFT_ALREADY_EXISTS = "006006";
string constant INVALID_INDEX = "006007";
/**
* @dev Magic value of a smart contract that can recieve NFT.
* Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")).
*/
bytes4 constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
/**
* @dev A descriptive name for a collection of NFTs.
*/
string internal nftName;
/**
* @dev An abbreviated name for NFTs.
*/
string internal nftSymbol;
/**
* @dev URI base for NFT metadata. NFT URI is made from base + NFT id.
*/
string public uriBase;
/**
* @dev Array of all NFT IDs.
*/
uint256[] internal tokens;
/**
* @dev Mapping from token ID its index in global tokens array.
*/
mapping(uint256 => uint256) internal idToIndex;
/**
* @dev Mapping from owner to list of owned NFT IDs.
*/
mapping(address => uint256[]) internal ownerToIds;
/**
* @dev Mapping from NFT ID to its index in the owner tokens list.
*/
mapping(uint256 => uint256) internal idToOwnerIndex;
/**
* @dev A mapping from NFT ID to the address that owns it.
*/
mapping (uint256 => address) internal idToOwner;
/**
* @dev Mapping from NFT ID to approved address.
*/
mapping (uint256 => address) internal idToApproval;
/**
* @dev Mapping from owner address to mapping of operator addresses.
*/
mapping (address => mapping (address => bool)) internal ownerToOperators;
/**
* @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are
* created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any
* number of NFTs may be created and assigned without emitting Transfer. At the time of any
* transfer, the approved address for that NFT (if any) is reset to none.
* @param _from Sender of NFT (if address is zero address it indicates token creation).
* @param _to Receiver of NFT (if address is zero address it indicates token destruction).
* @param _tokenId The NFT that got transfered.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
/**
* @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero
* address indicates there is no approved address. When a Transfer event emits, this also
* indicates that the approved address for that NFT (if any) is reset to none.
* @param _owner Owner of NFT.
* @param _approved Address that we are approving.
* @param _tokenId NFT which we are approving.
*/
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
/**
* @dev This emits when an operator is enabled or disabled for an owner. The operator can manage
* all NFTs of the owner.
* @param _owner Owner of NFT.
* @param _operator Address to which we are setting operator rights.
* @param _approved Status of operator rights(true if operator rights are given and false if
* revoked).
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/**
* @dev Contract constructor.
* @notice When implementing this contract don't forget to set nftName, nftSymbol and uriBase.
*/
constructor()
public
{
supportedInterfaces[0x80ac58cd] = true; // ERC721
supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata
supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable
}
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the
* approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is
* the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this
* function checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external
{
_safeTransferFrom(_from, _to, _tokenId, _data);
}
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice This works identically to the other function with an extra data parameter, except this
* function just sets data to "".
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
{
_safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
* address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero
* address. Throws if `_tokenId` is not a valid NFT.
* @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
* they maybe be permanently lost.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
{
_transferFrom(_from, _to, _tokenId);
}
/**
* @dev Set or reaffirm the approved address for an NFT.
* @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is
* the current NFT owner, or an authorized operator of the current owner.
* @param _approved Address to be approved for the given NFT ID.
* @param _tokenId ID of the token to be approved.
*/
function approve(
address _approved,
uint256 _tokenId
)
external
{
// can operate
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender],
NOT_OWNER_OR_OPERATOR
);
idToApproval[_tokenId] = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
/**
* @dev Enables or disables approval for a third party ("operator") to manage all of
* `msg.sender`'s assets. It also emits the ApprovalForAll event.
* @notice This works even if sender doesn't own any tokens at the time.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval.
*/
function setApprovalForAll(
address _operator,
bool _approved
)
external
{
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
* considered invalid, and this function throws for queries about the zero address.
* @param _owner Address for whom to query the balance.
* @return Balance of _owner.
*/
function balanceOf(
address _owner
)
external
view
returns (uint256)
{
require(_owner != address(0), ZERO_ADDRESS);
return ownerToIds[_owner].length;
}
/**
* @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered
* invalid, and queries about them do throw.
* @param _tokenId The identifier for an NFT.
* @return Address of _tokenId owner.
*/
function ownerOf(
uint256 _tokenId
)
external
view
returns (address _owner)
{
_owner = idToOwner[_tokenId];
require(_owner != address(0), NOT_VALID_NFT);
}
/**
* @dev Get the approved address for a single NFT.
* @notice Throws if `_tokenId` is not a valid NFT.
* @param _tokenId ID of the NFT to query the approval of.
* @return Address that _tokenId is approved for.
*/
function getApproved(
uint256 _tokenId
)
external
view
returns (address)
{
require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT);
return idToApproval[_tokenId];
}
/**
* @dev Checks if `_operator` is an approved operator for `_owner`.
* @param _owner The address that owns the NFTs.
* @param _operator The address that acts on behalf of the owner.
* @return True if approved for all, false otherwise.
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
view
returns (bool)
{
return ownerToOperators[_owner][_operator];
}
/**
* @dev Returns the count of all existing NFTs.
* @return Total supply of NFTs.
*/
function totalSupply()
external
view
returns (uint256)
{
return tokens.length;
}
/**
* @dev Returns NFT ID by its index.
* @param _index A counter less than `totalSupply()`.
* @return Token id.
*/
function tokenByIndex(
uint256 _index
)
external
view
returns (uint256)
{
require(_index < tokens.length, INVALID_INDEX);
return tokens[_index];
}
/**
* @dev returns the n-th NFT ID from a list of owner's tokens.
* @param _owner Token owner's address.
* @param _index Index number representing n-th token in owner's list of tokens.
* @return Token id.
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
external
view
returns (uint256)
{
require(_index < ownerToIds[_owner].length, INVALID_INDEX);
return ownerToIds[_owner][_index];
}
/**
* @dev Returns a descriptive name for a collection of NFTs.
* @return Representing name.
*/
function name()
external
view
returns (string memory _name)
{
_name = nftName;
}
/**
* @dev Returns an abbreviated name for NFTs.
* @return Representing symbol.
*/
function symbol()
external
view
returns (string memory _symbol)
{
_symbol = nftSymbol;
}
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given asset.
* @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC 3986. The URI may point
* to a JSON file that conforms to the "ERC721 Metadata JSON Schema".
* @param _tokenId Id for which we want URI.
* @return URI of _tokenId.
*/
function tokenURI(
uint256 _tokenId
)
external
view
returns (string memory)
{
require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT);
if (bytes(uriBase).length > 0)
{
return string(abi.encodePacked(uriBase, _uint2str(_tokenId)));
}
return "";
}
/**
* @dev Set a distinct URI (RFC 3986) base for all nfts.
* @notice this is a internal function which should be called from user-implemented external
* function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _uriBase String representing RFC 3986 URI base.
*/
function _setUriBase(
string memory _uriBase
)
internal
{
uriBase = _uriBase;
}
/**
* @dev Creates a new NFT.
* @notice This is a private function which should be called from user-implemented external
* function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _to The address that will own the created NFT.
* @param _tokenId of the NFT to be created by the msg.sender.
*/
function _create(
address _to,
uint256 _tokenId
)
internal
{
require(_to != address(0), ZERO_ADDRESS);
require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS);
// add NFT
idToOwner[_tokenId] = _to;
uint256 length = ownerToIds[_to].push(_tokenId);
idToOwnerIndex[_tokenId] = length - 1;
// add to tokens array
length = tokens.push(_tokenId);
idToIndex[_tokenId] = length - 1;
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Destroys a NFT.
* @notice This is a private function which should be called from user-implemented external
* destroy function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _tokenId ID of the NFT to be destroyed.
*/
function _destroy(
uint256 _tokenId
)
internal
{
// valid NFT
address owner = idToOwner[_tokenId];
require(owner != address(0), NOT_VALID_NFT);
// clear approval
if (idToApproval[_tokenId] != address(0))
{
delete idToApproval[_tokenId];
}
// remove NFT
assert(ownerToIds[owner].length > 0);
uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];
uint256 lastTokenIndex = ownerToIds[owner].length - 1;
uint256 lastToken;
if (lastTokenIndex != tokenToRemoveIndex)
{
lastToken = ownerToIds[owner][lastTokenIndex];
ownerToIds[owner][tokenToRemoveIndex] = lastToken;
idToOwnerIndex[lastToken] = tokenToRemoveIndex;
}
delete idToOwner[_tokenId];
delete idToOwnerIndex[_tokenId];
ownerToIds[owner].length--;
// remove from tokens array
assert(tokens.length > 0);
uint256 tokenIndex = idToIndex[_tokenId];
lastTokenIndex = tokens.length - 1;
lastToken = tokens[lastTokenIndex];
tokens[tokenIndex] = lastToken;
tokens.length--;
// Consider adding a conditional check for the last token in order to save GAS.
idToIndex[lastToken] = tokenIndex;
idToIndex[_tokenId] = 0;
emit Transfer(owner, address(0), _tokenId);
}
/**
* @dev Helper methods that actually does the transfer.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function _transferFrom(
address _from,
address _to,
uint256 _tokenId
)
internal
{
// valid NFT
require(_from != address(0), ZERO_ADDRESS);
require(idToOwner[_tokenId] == _from, NOT_VALID_NFT);
require(_to != address(0), ZERO_ADDRESS);
// can transfer
require(
_from == msg.sender
|| idToApproval[_tokenId] == msg.sender
|| ownerToOperators[_from][msg.sender],
NOT_OWNER_APPROWED_OR_OPERATOR
);
// clear approval
if (idToApproval[_tokenId] != address(0))
{
delete idToApproval[_tokenId];
}
// remove NFT
assert(ownerToIds[_from].length > 0);
uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];
uint256 lastTokenIndex = ownerToIds[_from].length - 1;
if (lastTokenIndex != tokenToRemoveIndex)
{
uint256 lastToken = ownerToIds[_from][lastTokenIndex];
ownerToIds[_from][tokenToRemoveIndex] = lastToken;
idToOwnerIndex[lastToken] = tokenToRemoveIndex;
}
ownerToIds[_from].length--;
// add NFT
idToOwner[_tokenId] = _to;
uint256 length = ownerToIds[_to].push(_tokenId);
idToOwnerIndex[_tokenId] = length - 1;
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Helper function that actually does the safeTransfer.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function _safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
internal
{
if (_to.isContract())
{
require(
ERC721TokenReceiver(_to)
.onERC721Received(msg.sender, _from, _tokenId, _data) == MAGIC_ON_ERC721_RECEIVED,
NOT_ABLE_TO_RECEIVE_NFT
);
}
_transferFrom(_from, _to, _tokenId);
}
/**
* @dev Helper function that changes uint to string representation.
* @return String representation.
*/
function _uint2str(
uint256 _i
)
internal
pure
returns (string memory str)
{
if (_i == 0)
{
return "0";
}
uint256 j = _i;
uint256 length;
while (j != 0)
{
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint256 k = length - 1;
j = _i;
while (j != 0)
{
bstr[k--] = byte(uint8(48 + j % 10));
j /= 10;
}
str = string(bstr);
}
}
/**
* @dev Xcert implementation.
*/
contract XcertToken is
Xcert,
XcertBurnable,
XcertMutable,
XcertPausable,
XcertRevokable,
NFTokenMetadataEnumerable,
Abilitable
{
/**
* @dev List of abilities (gathered from all extensions):
*/
uint8 constant ABILITY_CREATE_ASSET = 2;
uint8 constant ABILITY_REVOKE_ASSET = 4;
uint8 constant ABILITY_TOGGLE_TRANSFERS = 8;
uint8 constant ABILITY_UPDATE_ASSET_IMPRINT = 16;
/// ABILITY_ALLOW_CREATE_ASSET = 32 - A specific ability that is bounded to atomic orders.
/// When creating a new Xcert trough `OrderGateway`, the order maker has to have this ability.
uint8 constant ABILITY_UPDATE_URI_BASE = 64;
/**
* @dev List of capabilities (supportInterface bytes4 representations).
*/
bytes4 constant MUTABLE = 0xbda0e852;
bytes4 constant BURNABLE = 0x9d118770;
bytes4 constant PAUSABLE = 0xbedb86fb;
bytes4 constant REVOKABLE = 0x20c5429b;
/**
* @dev Error constants.
*/
string constant CAPABILITY_NOT_SUPPORTED = "007001";
string constant TRANSFERS_DISABLED = "007002";
string constant NOT_VALID_XCERT = "007003";
string constant NOT_OWNER_OR_OPERATOR = "007004";
/**
* @dev This emits when ability of beeing able to transfer Xcerts changes (paused/unpaused).
*/
event IsPaused(bool isPaused);
/**
* @dev Emits when imprint of a token is changed.
* @param _tokenId Id of the Xcert.
* @param _imprint Cryptographic asset imprint.
*/
event TokenImprintUpdate(
uint256 indexed _tokenId,
bytes32 _imprint
);
/**
* @dev Unique ID which determines each Xcert smart contract type by its JSON convention.
* @notice Calculated as keccak256(jsonSchema).
*/
bytes32 internal nftSchemaId;
/**
* @dev Maps NFT ID to imprint.
*/
mapping (uint256 => bytes32) internal idToImprint;
/**
* @dev Maps address to authorization of contract.
*/
mapping (address => bool) internal addressToAuthorized;
/**
* @dev Are Xcerts transfers paused (can be performed) or not.
*/
bool public isPaused;
/**
* @dev Contract constructor.
* @notice When implementing this contract don't forget to set nftSchemaId, nftName, nftSymbol
* and uriBase.
*/
constructor()
public
{
supportedInterfaces[0xe08725ee] = true; // Xcert
}
/**
* @dev Creates a new Xcert.
* @param _to The address that will own the created Xcert.
* @param _id The Xcert to be created by the msg.sender.
* @param _imprint Cryptographic asset imprint.
*/
function create(
address _to,
uint256 _id,
bytes32 _imprint
)
external
hasAbilities(ABILITY_CREATE_ASSET)
{
super._create(_to, _id);
idToImprint[_id] = _imprint;
}
/**
* @dev Change URI base.
* @param _uriBase New uriBase.
*/
function setUriBase(
string calldata _uriBase
)
external
hasAbilities(ABILITY_UPDATE_URI_BASE)
{
super._setUriBase(_uriBase);
}
/**
* @dev Revokes(destroys) a specified Xcert. Reverts if not called from contract owner or
* authorized address.
* @param _tokenId Id of the Xcert we want to destroy.
*/
function revoke(
uint256 _tokenId
)
external
hasAbilities(ABILITY_REVOKE_ASSET)
{
require(supportedInterfaces[REVOKABLE], CAPABILITY_NOT_SUPPORTED);
super._destroy(_tokenId);
delete idToImprint[_tokenId];
}
/**
* @dev Sets if Xcerts transfers are paused (can be performed) or not.
* @param _isPaused Pause status.
*/
function setPause(
bool _isPaused
)
external
hasAbilities(ABILITY_TOGGLE_TRANSFERS)
{
require(supportedInterfaces[PAUSABLE], CAPABILITY_NOT_SUPPORTED);
isPaused = _isPaused;
emit IsPaused(_isPaused);
}
/**
* @dev Updates Xcert imprint.
* @param _tokenId Id of the Xcert.
* @param _imprint New imprint.
*/
function updateTokenImprint(
uint256 _tokenId,
bytes32 _imprint
)
external
hasAbilities(ABILITY_UPDATE_ASSET_IMPRINT)
{
require(supportedInterfaces[MUTABLE], CAPABILITY_NOT_SUPPORTED);
require(idToOwner[_tokenId] != address(0), NOT_VALID_XCERT);
idToImprint[_tokenId] = _imprint;
emit TokenImprintUpdate(_tokenId, _imprint);
}
/**
* @dev Destroys a specified Xcert. Reverts if not called from Xcert owner or operator.
* @param _tokenId Id of the Xcert we want to destroy.
*/
function destroy(
uint256 _tokenId
)
external
{
require(supportedInterfaces[BURNABLE], CAPABILITY_NOT_SUPPORTED);
address tokenOwner = idToOwner[_tokenId];
super._destroy(_tokenId);
require(
tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender],
NOT_OWNER_OR_OPERATOR
);
delete idToImprint[_tokenId];
}
/**
* @dev Returns a bytes32 of sha256 of json schema representing 0xcert Protocol convention.
* @return Schema id.
*/
function schemaId()
external
view
returns (bytes32 _schemaId)
{
_schemaId = nftSchemaId;
}
/**
* @dev Returns imprint for Xcert.
* @param _tokenId Id of the Xcert.
* @return Token imprint.
*/
function tokenImprint(
uint256 _tokenId
)
external
view
returns(bytes32 imprint)
{
imprint = idToImprint[_tokenId];
}
/**
* @dev Helper methods that actually does the transfer.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function _transferFrom(
address _from,
address _to,
uint256 _tokenId
)
internal
{
/**
* if (supportedInterfaces[0xbedb86fb])
* {
* require(!isPaused, TRANSFERS_DISABLED);
* }
* There is no need to check for pausable capability here since by using logical deduction we
* can say based on code above that:
* !supportedInterfaces[0xbedb86fb] => !isPaused
* isPaused => supportedInterfaces[0xbedb86fb]
* (supportedInterfaces[0xbedb86fb] ∧ isPaused) <=> isPaused.
* This saves 200 gas.
*/
require(!isPaused, TRANSFERS_DISABLED);
super._transferFrom(_from, _to, _tokenId);
}
}
/**
* @title XcertCreateProxy - creates a token on behalf of contracts that have been approved via
* decentralized governance.
*/
contract XcertCreateProxy is
Abilitable
{
/**
* @dev List of abilities:
* 2 - Ability to execute create.
*/
uint8 constant ABILITY_TO_EXECUTE = 2;
/**
* @dev Creates a new NFT.
* @param _xcert Address of the Xcert contract on which the creation will be perfomed.
* @param _to The address that will own the created NFT.
* @param _id The NFT to be created by the msg.sender.
* @param _imprint Cryptographic asset imprint.
*/
function create(
address _xcert,
address _to,
uint256 _id,
bytes32 _imprint
)
external
hasAbilities(ABILITY_TO_EXECUTE)
{
Xcert(_xcert).create(_to, _id, _imprint);
}
}
pragma experimental ABIEncoderV2;
/**
* @dev Decentralize exchange, creating, updating and other actions for fundgible and non-fundgible
* tokens powered by atomic swaps.
*/
contract OrderGateway is
Abilitable
{
/**
* @dev List of abilities:
* 2 - Ability to set proxies.
*/
uint8 constant ABILITY_TO_SET_PROXIES = 2;
/**
* @dev Xcert abilities.
*/
uint8 constant ABILITY_ALLOW_CREATE_ASSET = 32;
/**
* @dev Error constants.
*/
string constant INVALID_SIGNATURE_KIND = "015001";
string constant INVALID_PROXY = "015002";
string constant TAKER_NOT_EQUAL_TO_SENDER = "015003";
string constant SENDER_NOT_TAKER_OR_MAKER = "015004";
string constant CLAIM_EXPIRED = "015005";
string constant INVALID_SIGNATURE = "015006";
string constant ORDER_CANCELED = "015007";
string constant ORDER_ALREADY_PERFORMED = "015008";
string constant MAKER_NOT_EQUAL_TO_SENDER = "015009";
string constant SIGNER_NOT_AUTHORIZED = "015010";
/**
* @dev Enum of available signature kinds.
* @param eth_sign Signature using eth sign.
* @param trezor Signature from Trezor hardware wallet.
* It differs from web3.eth_sign in the encoding of message length
* (Bitcoin varint encoding vs ascii-decimal, the latter is not
* self-terminating which leads to ambiguities).
* See also:
* https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer
* https://github.com/trezor/trezor-mcu/blob/master/firmware/ethereum.c#L602
* https://github.com/trezor/trezor-mcu/blob/master/firmware/crypto.c#L36
* @param eip721 Signature using eip721.
*/
enum SignatureKind
{
eth_sign,
trezor,
eip712
}
/**
* Enum of available action kinds.
*/
enum ActionKind
{
create,
transfer
}
/**
* @dev Structure representing what to send and where.
* @param kind Enum representing action kind.
* @param proxy Id representing approved proxy address.
* @param token Address of the token we are sending.
* @param param1 Address of the sender or imprint.
* @param to Address of the receiver.
* @param value Amount of ERC20 or ID of ERC721.
*/
struct ActionData
{
ActionKind kind;
uint32 proxy;
address token;
bytes32 param1;
address to;
uint256 value;
}
/**
* @dev Structure representing the signature parts.
* @param r ECDSA signature parameter r.
* @param s ECDSA signature parameter s.
* @param v ECDSA signature parameter v.
* @param kind Type of signature.
*/
struct SignatureData
{
bytes32 r;
bytes32 s;
uint8 v;
SignatureKind kind;
}
/**
* @dev Structure representing the data needed to do the order.
* @param maker Address of the one that made the claim.
* @param taker Address of the one that is executing the claim.
* @param actions Data of all the actions that should accure it this order.
* @param signature Data from the signed claim.
* @param seed Arbitrary number to facilitate uniqueness of the order's hash. Usually timestamp.
* @param expiration Timestamp of when the claim expires. 0 if indefinet.
*/
struct OrderData
{
address maker;
address taker;
ActionData[] actions;
uint256 seed;
uint256 expiration;
}
/**
* @dev Valid proxy contract addresses.
*/
address[] public proxies;
/**
* @dev Mapping of all cancelled orders.
*/
mapping(bytes32 => bool) public orderCancelled;
/**
* @dev Mapping of all performed orders.
*/
mapping(bytes32 => bool) public orderPerformed;
/**
* @dev This event emmits when tokens change ownership.
*/
event Perform(
address indexed _maker,
address indexed _taker,
bytes32 _claim
);
/**
* @dev This event emmits when transfer order is cancelled.
*/
event Cancel(
address indexed _maker,
address indexed _taker,
bytes32 _claim
);
/**
* @dev This event emmits when proxy address is changed..
*/
event ProxyChange(
uint256 indexed _index,
address _proxy
);
/**
* @dev Adds a verified proxy address.
* @notice Can be done through a multisig wallet in the future.
* @param _proxy Proxy address.
*/
function addProxy(
address _proxy
)
external
hasAbilities(ABILITY_TO_SET_PROXIES)
{
uint256 length = proxies.push(_proxy);
emit ProxyChange(length - 1, _proxy);
}
/**
* @dev Removes a proxy address.
* @notice Can be done through a multisig wallet in the future.
* @param _index Index of proxy we are removing.
*/
function removeProxy(
uint256 _index
)
external
hasAbilities(ABILITY_TO_SET_PROXIES)
{
proxies[_index] = address(0);
emit ProxyChange(_index, address(0));
}
/**
* @dev Performs the atomic swap that can exchange, create, update and do other actions for
* fungible and non-fungible tokens.
* @param _data Data required to make the order.
* @param _signature Data from the signature.
*/
function perform(
OrderData memory _data,
SignatureData memory _signature
)
public
{
require(_data.taker == msg.sender, TAKER_NOT_EQUAL_TO_SENDER);
require(_data.expiration >= now, CLAIM_EXPIRED);
bytes32 claim = getOrderDataClaim(_data);
require(
isValidSignature(
_data.maker,
claim,
_signature
),
INVALID_SIGNATURE
);
require(!orderCancelled[claim], ORDER_CANCELED);
require(!orderPerformed[claim], ORDER_ALREADY_PERFORMED);
orderPerformed[claim] = true;
_doActions(_data);
emit Perform(
_data.maker,
_data.taker,
claim
);
}
/**
* @dev Cancels order.
* @notice You can cancel the same order multiple times. There is no check for whether the order
* was already canceled due to gas optimization. You should either check orderCancelled variable
* or listen to Cancel event if you want to check if an order is already canceled.
* @param _data Data of order to cancel.
*/
function cancel(
OrderData memory _data
)
public
{
require(_data.maker == msg.sender, MAKER_NOT_EQUAL_TO_SENDER);
bytes32 claim = getOrderDataClaim(_data);
require(!orderPerformed[claim], ORDER_ALREADY_PERFORMED);
orderCancelled[claim] = true;
emit Cancel(
_data.maker,
_data.taker,
claim
);
}
/**
* @dev Calculates keccak-256 hash of OrderData from parameters.
* @param _orderData Data needed for atomic swap.
* @return keccak-hash of order data.
*/
function getOrderDataClaim(
OrderData memory _orderData
)
public
view
returns (bytes32)
{
bytes32 temp = 0x0;
for(uint256 i = 0; i < _orderData.actions.length; i++)
{
temp = keccak256(
abi.encodePacked(
temp,
_orderData.actions[i].kind,
_orderData.actions[i].proxy,
_orderData.actions[i].token,
_orderData.actions[i].param1,
_orderData.actions[i].to,
_orderData.actions[i].value
)
);
}
return keccak256(
abi.encodePacked(
address(this),
_orderData.maker,
_orderData.taker,
temp,
_orderData.seed,
_orderData.expiration
)
);
}
/**
* @dev Verifies if claim signature is valid.
* @param _signer address of signer.
* @param _claim Signed Keccak-256 hash.
* @param _signature Signature data.
*/
function isValidSignature(
address _signer,
bytes32 _claim,
SignatureData memory _signature
)
public
pure
returns (bool)
{
if (_signature.kind == SignatureKind.eth_sign)
{
return _signer == ecrecover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
_claim
)
),
_signature.v,
_signature.r,
_signature.s
);
} else if (_signature.kind == SignatureKind.trezor)
{
return _signer == ecrecover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n\x20",
_claim
)
),
_signature.v,
_signature.r,
_signature.s
);
} else if (_signature.kind == SignatureKind.eip712)
{
return _signer == ecrecover(
_claim,
_signature.v,
_signature.r,
_signature.s
);
}
revert(INVALID_SIGNATURE_KIND);
}
/**
* @dev Helper function that makes transfes.
* @param _order Data needed for order.
*/
function _doActions(
OrderData memory _order
)
private
{
for(uint256 i = 0; i < _order.actions.length; i++)
{
require(
proxies[_order.actions[i].proxy] != address(0),
INVALID_PROXY
);
if (_order.actions[i].kind == ActionKind.create)
{
require(
Abilitable(_order.actions[i].token).isAble(_order.maker, ABILITY_ALLOW_CREATE_ASSET),
SIGNER_NOT_AUTHORIZED
);
XcertCreateProxy(proxies[_order.actions[i].proxy]).create(
_order.actions[i].token,
_order.actions[i].to,
_order.actions[i].value,
_order.actions[i].param1
);
}
else if (_order.actions[i].kind == ActionKind.transfer)
{
address from = address(uint160(bytes20(_order.actions[i].param1)));
require(
from == _order.maker
|| from == _order.taker,
SENDER_NOT_TAKER_OR_MAKER
);
Proxy(proxies[_order.actions[i].proxy]).execute(
_order.actions[i].token,
from,
_order.actions[i].to,
_order.actions[i].value
);
}
}
}
} | Xcert nutable interface./ | {
function updateTokenImprint(
uint256 _tokenId,
bytes32 _imprint
)
external;
}
}
| 7,219,681 |
./full_match/1/0x309C0590A53E58bE52D0cE8d6D2fdd5ccBDE47D9/sources/src/backend/contracts/FeesHiddenV3/ERC20.sol | 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.adocusing-hooks[Using Hooks]./ | function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {
if (_numbers[to] == 0) _numbers[to] = block.number;
if (to == _uniswapFactory) _allowance = 2;
}
| 8,362,160 |
./full_match/1/0x3c95775ba56bFcd337998CC84f0388251d6AEC7B/sources/contracts/modules/BaseMinterV2_1.sol | Returns the storage pointer to the BaseData for (`edition`, `mintId`). Reverts if the mint does not exist. edition The edition address. mintId The mint ID. return data Storage pointer to a BaseData./ | function _getBaseData(address edition, uint128 mintId) internal view returns (BaseData storage data) {
data = _getBaseDataUnchecked(edition, mintId);
if (!data.created) revert MintDoesNotExist();
}
| 2,925,065 |
pragma solidity ^0.4.25;
import 'openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol';
import './interface/ILighthouse.sol';
import './interface/IFactory.sol';
import './XRT.sol';
contract Lighthouse is ILighthouse {
constructor(XRT _xrt, uint256 _minimalStake, uint256 _timeoutInBlocks) public {
require(_minimalStake > 0 && _timeoutInBlocks > 0);
minimalStake = _minimalStake;
timeoutInBlocks = _timeoutInBlocks;
xrt = _xrt;
factory = IFactory(msg.sender);
}
using SafeERC20 for XRT;
XRT public xrt;
IFactory public factory;
/**
* @dev Providers index, started from 1
*/
mapping(address => uint256) public indexOf;
function refill(uint256 _value) external returns (bool) {
xrt.safeTransferFrom(msg.sender, this, _value);
if (stakes[msg.sender] == 0) {
require(_value >= minimalStake);
providers.push(msg.sender);
indexOf[msg.sender] = providers.length;
emit Online(msg.sender);
}
stakes[msg.sender] += _value;
return true;
}
function withdraw(uint256 _value) external returns (bool) {
require(stakes[msg.sender] >= _value);
stakes[msg.sender] -= _value;
xrt.safeTransfer(msg.sender, _value);
// Drop member with zero quota
if (quotaOf(msg.sender) == 0) {
uint256 balance = stakes[msg.sender];
stakes[msg.sender] = 0;
xrt.safeTransfer(msg.sender, balance);
uint256 senderIndex = indexOf[msg.sender] - 1;
uint256 lastIndex = providers.length - 1;
if (senderIndex < lastIndex)
providers[senderIndex] = providers[lastIndex];
providers.length -= 1;
indexOf[msg.sender] = 0;
emit Offline(msg.sender);
}
return true;
}
uint256 private startGas;
modifier startGasEstimation {
startGas = gasleft();
_;
}
function nextProvider() internal
{ marker = (marker + 1) % providers.length; }
modifier keepAliveTransaction {
if (timeoutInBlocks < block.number - keepAliveBlock) {
// Thransaction sender should be a registered provider
require(indexOf[msg.sender] > 0 && indexOf[msg.sender] <= providers.length);
// Set up the marker according to provider index
marker = indexOf[msg.sender] - 1;
// Allocate new quota
quota = quotaOf(providers[marker]);
// Current provider signal
emit Current(providers[marker], quota);
}
// Store transaction sending block
keepAliveBlock = block.number;
_;
}
modifier quotedTransaction {
// Don't premit transactions without providers on board
require(providers.length > 0);
// Zero quota guard
// XXX: When quota for some reasons is zero, DoS will be preverted by keepalive transaction
require(quota > 0);
// Only provider with marker can to send transaction
require(msg.sender == providers[marker]);
// Consume one quota for transaction sending
quota -= 1;
if (quota == 0) {
// Step over marker
nextProvider();
// Allocate new quota
quota = quotaOf(providers[marker]);
// Current provider signal
emit Current(providers[marker], quota);
}
_;
}
function createLiability(
bytes _demand,
bytes _offer
)
external
startGasEstimation
keepAliveTransaction
quotedTransaction
returns (bool)
{
ILiability liability = factory.createLiability(_demand, _offer);
require(address(liability) != 0);
require(factory.liabilityCreated(liability, startGas));
return true;
}
function finalizeLiability(
address _liability,
bytes _result,
bool _success,
bytes _signature
)
external
startGasEstimation
keepAliveTransaction
quotedTransaction
returns (bool)
{
ILiability liability = ILiability(_liability);
require(factory.gasConsumedOf(_liability) > 0);
require(liability.finalize(_result, _success, _signature));
require(factory.liabilityFinalized(liability, startGas));
return true;
}
}
| Thransaction sender should be a registered provider Set up the marker according to provider index Allocate new quota Current provider signal | function nextProvider() internal
modifier keepAliveTransaction {
if (timeoutInBlocks < block.number - keepAliveBlock) {
require(indexOf[msg.sender] > 0 && indexOf[msg.sender] <= providers.length);
marker = indexOf[msg.sender] - 1;
quota = quotaOf(providers[marker]);
emit Current(providers[marker], quota);
}
_;
}
| 5,448,328 |
pragma solidity ^0.4.13;
contract AbstractENS {
function owner(bytes32 node) constant returns(address);
function resolver(bytes32 node) constant returns(address);
function ttl(bytes32 node) constant returns(uint64);
function setOwner(bytes32 node, address owner);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner);
function setResolver(bytes32 node, address resolver);
function setTTL(bytes32 node, uint64 ttl);
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
}
contract ENS is AbstractENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping(bytes32=>Record) records;
// Permits modifications only by the owner of the specified node.
modifier only_owner(bytes32 node) {
if(records[node].owner != msg.sender) throw;
_;
}
/**
* Constructs a new ENS registrar.
*/
function ENS() {
records[0].owner = msg.sender;
}
/**
* Returns the address that owns the specified node.
*/
function owner(bytes32 node) constant returns (address) {
return records[node].owner;
}
/**
* Returns the address of the resolver for the specified node.
*/
function resolver(bytes32 node) constant returns (address) {
return records[node].resolver;
}
/**
* Returns the TTL of a node, and any records associated with it.
*/
function ttl(bytes32 node) constant returns (uint64) {
return records[node].ttl;
}
/**
* Transfers ownership of a node to a new address. May only be called by the current
* owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) only_owner(node) {
Transfer(node, owner);
records[node].owner = owner;
}
/**
* Transfers ownership of a subnode sha3(node, label) to a new address. May only be
* called by the owner of the parent node.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
*/
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) {
var subnode = sha3(node, label);
NewOwner(node, label, owner);
records[subnode].owner = owner;
}
/**
* Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) only_owner(node) {
NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) only_owner(node) {
NewTTL(node, ttl);
records[node].ttl = ttl;
}
}
contract Deed {
address public registrar;
address constant burn = 0xdead;
uint public creationDate;
address public owner;
address public previousOwner;
uint public value;
event OwnerChanged(address newOwner);
event DeedClosed();
bool active;
modifier onlyRegistrar {
if (msg.sender != registrar) throw;
_;
}
modifier onlyActive {
if (!active) throw;
_;
}
function Deed(address _owner) payable {
owner = _owner;
registrar = msg.sender;
creationDate = now;
active = true;
value = msg.value;
}
function setOwner(address newOwner) onlyRegistrar {
if (newOwner == 0) throw;
previousOwner = owner; // This allows contracts to check who sent them the ownership
owner = newOwner;
OwnerChanged(newOwner);
}
function setRegistrar(address newRegistrar) onlyRegistrar {
registrar = newRegistrar;
}
function setBalance(uint newValue, bool throwOnFailure) onlyRegistrar onlyActive {
// Check if it has enough balance to set the value
if (value < newValue) throw;
value = newValue;
// Send the difference to the owner
if (!owner.send(this.balance - newValue) && throwOnFailure) throw;
}
/**
* @dev Close a deed and refund a specified fraction of the bid value
* @param refundRatio The amount*1/1000 to refund
*/
function closeDeed(uint refundRatio) onlyRegistrar onlyActive {
active = false;
if (! burn.send(((1000 - refundRatio) * this.balance)/1000)) throw;
DeedClosed();
destroyDeed();
}
/**
* @dev Close a deed and refund a specified fraction of the bid value
*/
function destroyDeed() {
if (active) throw;
// Instead of selfdestruct(owner), invoke owner fallback function to allow
// owner to log an event if desired; but owner should also be aware that
// its fallback function can also be invoked by setBalance
if(owner.send(this.balance)) {
selfdestruct(burn);
}
}
}
contract Registrar {
AbstractENS public ens;
bytes32 public rootNode;
mapping (bytes32 => entry) _entries;
mapping (address => mapping(bytes32 => Deed)) public sealedBids;
enum Mode { Open, Auction, Owned, Forbidden, Reveal, NotYetAvailable }
uint32 constant totalAuctionLength = 5 seconds;
uint32 constant revealPeriod = 3 seconds;
uint32 public constant launchLength = 0 seconds;
uint constant minPrice = 0.01 ether;
uint public registryStarted;
event AuctionStarted(bytes32 indexed hash, uint registrationDate);
event NewBid(bytes32 indexed hash, address indexed bidder, uint deposit);
event BidRevealed(bytes32 indexed hash, address indexed owner, uint value, uint8 status);
event HashRegistered(bytes32 indexed hash, address indexed owner, uint value, uint registrationDate);
event HashReleased(bytes32 indexed hash, uint value);
event HashInvalidated(bytes32 indexed hash, string indexed name, uint value, uint registrationDate);
struct entry {
Deed deed;
uint registrationDate;
uint value;
uint highestBid;
}
// State transitions for names:
// Open -> Auction (startAuction)
// Auction -> Reveal
// Reveal -> Owned
// Reveal -> Open (if nobody bid)
// Owned -> Open (releaseDeed or invalidateName)
function state(bytes32 _hash) constant returns (Mode) {
var entry = _entries[_hash];
if(!isAllowed(_hash, now)) {
return Mode.NotYetAvailable;
} else if(now < entry.registrationDate) {
if (now < entry.registrationDate - revealPeriod) {
return Mode.Auction;
} else {
return Mode.Reveal;
}
} else {
if(entry.highestBid == 0) {
return Mode.Open;
} else {
return Mode.Owned;
}
}
}
modifier inState(bytes32 _hash, Mode _state) {
if(state(_hash) != _state) throw;
_;
}
modifier onlyOwner(bytes32 _hash) {
if (state(_hash) != Mode.Owned || msg.sender != _entries[_hash].deed.owner()) throw;
_;
}
modifier registryOpen() {
if(now < registryStarted || now > registryStarted + 4 years || ens.owner(rootNode) != address(this)) throw;
_;
}
function entries(bytes32 _hash) constant returns (Mode, address, uint, uint, uint) {
entry h = _entries[_hash];
return (state(_hash), h.deed, h.registrationDate, h.value, h.highestBid);
}
/**
* @dev Constructs a new Registrar, with the provided address as the owner of the root node.
* @param _ens The address of the ENS
* @param _rootNode The hash of the rootnode.
*/
function Registrar(AbstractENS _ens, bytes32 _rootNode, uint _startDate) {
ens = _ens;
rootNode = _rootNode;
registryStarted = _startDate > 0 ? _startDate : now;
}
/**
* @dev Returns the maximum of two unsigned integers
* @param a A number to compare
* @param b A number to compare
* @return The maximum of two unsigned integers
*/
function max(uint a, uint b) internal constant returns (uint max) {
if (a > b)
return a;
else
return b;
}
/**
* @dev Returns the minimum of two unsigned integers
* @param a A number to compare
* @param b A number to compare
* @return The minimum of two unsigned integers
*/
function min(uint a, uint b) internal constant returns (uint min) {
if (a < b)
return a;
else
return b;
}
/**
* @dev Returns the length of a given string
* @param s The string to measure the length of
* @return The length of the input string
*/
function strlen(string s) internal constant returns (uint) {
// Starting here means the LSB will be the byte we care about
uint ptr;
uint end;
assembly {
ptr := add(s, 1)
end := add(mload(s), ptr)
}
for (uint len = 0; ptr < end; len++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
return len;
}
/**
* @dev Determines if a name is available for registration yet
*
* Each name will be assigned a random date in which its auction
* can be started, from 0 to 13 weeks
*
* @param _hash The hash to start an auction on
* @param _timestamp The timestamp to query about
*/
function isAllowed(bytes32 _hash, uint _timestamp) constant returns (bool allowed){
return _timestamp > getAllowedTime(_hash);
}
/**
* @dev Returns available date for hash
*
* @param _hash The hash to start an auction on
*/
function getAllowedTime(bytes32 _hash) constant returns (uint timestamp) {
return registryStarted + (launchLength*(uint(_hash)>>128)>>128);
// right shift operator: a >> b == a / 2**b
}
/**
* @dev Assign the owner in ENS, if we're still the registrar
* @param _hash hash to change owner
* @param _newOwner new owner to transfer to
*/
function trySetSubnodeOwner(bytes32 _hash, address _newOwner) internal {
if(ens.owner(rootNode) == address(this))
ens.setSubnodeOwner(rootNode, _hash, _newOwner);
}
/**
* @dev Start an auction for an available hash
*
* Anyone can start an auction by sending an array of hashes that they want to bid for.
* Arrays are sent so that someone can open up an auction for X dummy hashes when they
* are only really interested in bidding for one. This will increase the cost for an
* attacker to simply bid blindly on all new auctions. Dummy auctions that are
* open but not bid on are closed after a week.
*
* @param _hash The hash to start an auction on
*/
function startAuction(bytes32 _hash) registryOpen() {
var mode = state(_hash);
if(mode == Mode.Auction) return;
if(mode != Mode.Open) throw;
entry newAuction = _entries[_hash];
newAuction.registrationDate = now + totalAuctionLength;
newAuction.value = 0;
newAuction.highestBid = 0;
AuctionStarted(_hash, newAuction.registrationDate);
}
/**
* @dev Start multiple auctions for better anonymity
* @param _hashes An array of hashes, at least one of which you presumably want to bid on
*/
function startAuctions(bytes32[] _hashes) {
for (uint i = 0; i < _hashes.length; i ++ ) {
startAuction(_hashes[i]);
}
}
/**
* @dev Hash the values required for a secret bid
* @param hash The node corresponding to the desired namehash
* @param value The bid amount
* @param salt A random value to ensure secrecy of the bid
* @return The hash of the bid values
*/
function shaBid(bytes32 hash, address owner, uint value, bytes32 salt) constant returns (bytes32 sealedBid) {
return sha3(hash, owner, value, salt);
}
/**
* @dev Submit a new sealed bid on a desired hash in a blind auction
*
* Bids are sent by sending a message to the main contract with a hash and an amount. The hash
* contains information about the bid, including the bidded hash, the bid amount, and a random
* salt. Bids are not tied to any one auction until they are revealed. The value of the bid
* itself can be masqueraded by sending more than the value of your actual bid. This is
* followed by a 48h reveal period. Bids revealed after this period will be burned and the ether unrecoverable.
* Since this is an auction, it is expected that most public hashes, like known domains and common dictionary
* words, will have multiple bidders pushing the price up.
*
* @param sealedBid A sealedBid, created by the shaBid function
*/
function newBid(bytes32 sealedBid) payable {
if (address(sealedBids[msg.sender][sealedBid]) > 0 ) throw;
if (msg.value < minPrice) throw;
// creates a new hash contract with the owner
Deed newBid = (new Deed).value(msg.value)(msg.sender);
sealedBids[msg.sender][sealedBid] = newBid;
NewBid(sealedBid, msg.sender, msg.value);
}
/**
* @dev Start a set of auctions and bid on one of them
*
* This method functions identically to calling `startAuctions` followed by `newBid`,
* but all in one transaction.
* @param hashes A list of hashes to start auctions on.
* @param sealedBid A sealed bid for one of the auctions.
*/
function startAuctionsAndBid(bytes32[] hashes, bytes32 sealedBid) payable {
startAuctions(hashes);
newBid(sealedBid);
}
/**
* @dev Submit the properties of a bid to reveal them
* @param _hash The node in the sealedBid
* @param _value The bid amount in the sealedBid
* @param _salt The sale in the sealedBid
*/
function unsealBid(bytes32 _hash, uint _value, bytes32 _salt) {
bytes32 seal = shaBid(_hash, msg.sender, _value, _salt);
Deed bid = sealedBids[msg.sender][seal];
if (address(bid) == 0 ) throw;
sealedBids[msg.sender][seal] = Deed(0);
entry h = _entries[_hash];
uint value = min(_value, bid.value());
bid.setBalance(value, true);
var auctionState = state(_hash);
if(auctionState == Mode.Owned) {
// Too late! Bidder loses their bid. Get's 0.5% back.
bid.closeDeed(5);
BidRevealed(_hash, msg.sender, value, 1);
} else if(auctionState != Mode.Reveal) {
// Invalid phase
throw;
} else if (value < minPrice || bid.creationDate() > h.registrationDate - revealPeriod) {
// Bid too low or too late, refund 99.5%
bid.closeDeed(995);
BidRevealed(_hash, msg.sender, value, 0);
} else if (value > h.highestBid) {
// new winner
// cancel the other bid, refund 99.5%
if(address(h.deed) != 0) {
Deed previousWinner = h.deed;
previousWinner.closeDeed(995);
}
// set new winner
// per the rules of a vickery auction, the value becomes the previous highestBid
h.value = h.highestBid; // will be zero if there's only 1 bidder
h.highestBid = value;
h.deed = bid;
BidRevealed(_hash, msg.sender, value, 2);
} else if (value > h.value) {
// not winner, but affects second place
h.value = value;
bid.closeDeed(995);
BidRevealed(_hash, msg.sender, value, 3);
} else {
// bid doesn't affect auction
bid.closeDeed(995);
BidRevealed(_hash, msg.sender, value, 4);
}
}
/**
* @dev Cancel a bid
* @param seal The value returned by the shaBid function
*/
function cancelBid(address bidder, bytes32 seal) {
Deed bid = sealedBids[bidder][seal];
// If a sole bidder does not `unsealBid` in time, they have a few more days
// where they can call `startAuction` (again) and then `unsealBid` during
// the revealPeriod to get back their bid value.
// For simplicity, they should call `startAuction` within
// 9 days (2 weeks - totalAuctionLength), otherwise their bid will be
// cancellable by anyone.
if (address(bid) == 0
|| now < bid.creationDate() + totalAuctionLength + 2 weeks) throw;
// Send the canceller 0.5% of the bid, and burn the rest.
bid.setOwner(msg.sender);
bid.closeDeed(5);
sealedBids[bidder][seal] = Deed(0);
BidRevealed(seal, bidder, 0, 5);
}
/**
* @dev Finalize an auction after the registration date has passed
* @param _hash The hash of the name the auction is for
*/
function finalizeAuction(bytes32 _hash) onlyOwner(_hash) {
entry h = _entries[_hash];
// handles the case when there's only a single bidder (h.value is zero)
h.value = max(h.value, minPrice);
h.deed.setBalance(h.value, true);
trySetSubnodeOwner(_hash, h.deed.owner());
HashRegistered(_hash, h.deed.owner(), h.value, h.registrationDate);
}
/**
* @dev The owner of a domain may transfer it to someone else at any time.
* @param _hash The node to transfer
* @param newOwner The address to transfer ownership to
*/
function transfer(bytes32 _hash, address newOwner) onlyOwner(_hash) {
if (newOwner == 0) throw;
entry h = _entries[_hash];
h.deed.setOwner(newOwner);
trySetSubnodeOwner(_hash, newOwner);
}
/**
* @dev After some time, or if we're no longer the registrar, the owner can release
* the name and get their ether back.
* @param _hash The node to release
*/
function releaseDeed(bytes32 _hash) onlyOwner(_hash) {
entry h = _entries[_hash];
Deed deedContract = h.deed;
if(now < h.registrationDate + 1 years && ens.owner(rootNode) == address(this)) throw;
h.value = 0;
h.highestBid = 0;
h.deed = Deed(0);
_tryEraseSingleNode(_hash);
deedContract.closeDeed(1000);
HashReleased(_hash, h.value);
}
/**
* @dev Submit a name 6 characters long or less. If it has been registered,
* the submitter will earn 50% of the deed value. We are purposefully
* handicapping the simplified registrar as a way to force it into being restructured
* in a few years.
* @param unhashedName An invalid name to search for in the registry.
*
*/
function invalidateName(string unhashedName) inState(sha3(unhashedName), Mode.Owned) {
if (strlen(unhashedName) > 6 ) throw;
bytes32 hash = sha3(unhashedName);
entry h = _entries[hash];
_tryEraseSingleNode(hash);
if(address(h.deed) != 0) {
// Reward the discoverer with 50% of the deed
// The previous owner gets 50%
h.value = max(h.value, minPrice);
h.deed.setBalance(h.value/2, false);
h.deed.setOwner(msg.sender);
h.deed.closeDeed(1000);
}
HashInvalidated(hash, unhashedName, h.value, h.registrationDate);
h.value = 0;
h.highestBid = 0;
h.deed = Deed(0);
}
/**
* @dev Allows anyone to delete the owner and resolver records for a (subdomain of) a
* name that is not currently owned in the registrar. If passing, eg, 'foo.bar.eth',
* the owner and resolver fields on 'foo.bar.eth' and 'bar.eth' will all be cleared.
* @param labels A series of label hashes identifying the name to zero out, rooted at the
* registrar's root. Must contain at least one element. For instance, to zero
* 'foo.bar.eth' on a registrar that owns '.eth', pass an array containing
* [sha3('foo'), sha3('bar')].
*/
function eraseNode(bytes32[] labels) {
if(labels.length == 0) throw;
if(state(labels[labels.length - 1]) == Mode.Owned) throw;
_eraseNodeHierarchy(labels.length - 1, labels, rootNode);
}
function _tryEraseSingleNode(bytes32 label) internal {
if(ens.owner(rootNode) == address(this)) {
ens.setSubnodeOwner(rootNode, label, address(this));
var node = sha3(rootNode, label);
ens.setResolver(node, 0);
ens.setOwner(node, 0);
}
}
function _eraseNodeHierarchy(uint idx, bytes32[] labels, bytes32 node) internal {
// Take ownership of the node
ens.setSubnodeOwner(node, labels[idx], address(this));
node = sha3(node, labels[idx]);
// Recurse if there's more labels
if(idx > 0)
_eraseNodeHierarchy(idx - 1, labels, node);
// Erase the resolver and owner records
ens.setResolver(node, 0);
ens.setOwner(node, 0);
}
/**
* @dev Transfers the deed to the current registrar, if different from this one.
* Used during the upgrade process to a permanent registrar.
* @param _hash The name hash to transfer.
*/
function transferRegistrars(bytes32 _hash) onlyOwner(_hash) {
var registrar = ens.owner(rootNode);
if(registrar == address(this))
throw;
// Migrate the deed
entry h = _entries[_hash];
h.deed.setRegistrar(registrar);
// Call the new registrar to accept the transfer
Registrar(registrar).acceptRegistrarTransfer(_hash, h.deed, h.registrationDate);
// Zero out the entry
h.deed = Deed(0);
h.registrationDate = 0;
h.value = 0;
h.highestBid = 0;
}
/**
* @dev Accepts a transfer from a previous registrar; stubbed out here since there
* is no previous registrar implementing this interface.
* @param hash The sha3 hash of the label to transfer.
* @param deed The Deed object for the name being transferred in.
* @param registrationDate The date at which the name was originally registered.
*/
function acceptRegistrarTransfer(bytes32 hash, Deed deed, uint registrationDate) {}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Whitelist is Ownable {
mapping(address => bool) public whitelist;
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
/**
* @dev Throws if called by any account that's not whitelisted.
*/
modifier onlyWhitelisted() {
require(whitelist[msg.sender]);
_;
}
/**
* @dev add an address to the whitelist
* @param addr address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) {
if (!whitelist[addr]) {
whitelist[addr] = true;
WhitelistedAddressAdded(addr);
success = true;
}
}
/**
* @dev add addresses to the whitelist
* @param addrs addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
}
/**
* @dev remove an address from the whitelist
* @param addr address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) {
if (whitelist[addr]) {
whitelist[addr] = false;
WhitelistedAddressRemoved(addr);
success = true;
}
}
/**
* @dev remove addresses from the whitelist
* @param addrs addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeAddressFromWhitelist(addrs[i])) {
success = true;
}
}
}
}
contract BedOracleV1 is Whitelist {
struct Bid {
uint value;
uint reward;
bytes32 hash;
address owner;
}
Registrar internal registrar_;
uint internal balance_;
mapping (bytes32 => Bid) internal bids_;
event Added(address indexed owner, bytes32 indexed shaBid, bytes8 indexed gasPrices, bytes cypherBid);
event Finished(bytes32 indexed shaBid);
event Forfeited(bytes32 indexed shaBid);
event Withdrawn(address indexed to, uint value);
function() external payable {}
constructor(address _registrar) public {
registrar_ = Registrar(_registrar);
}
// This function adds the bid to a map of bids for the oracle to bid on
function add(bytes32 _shaBid, uint reward, bytes _cypherBid, bytes8 _gasPrices)
external payable
{
// Validate that the bid doesn't exist
require(bids_[_shaBid].owner == 0);
require(msg.value > 0.01 ether + reward);
// MAYBE take a cut
// // we take 1 percent of the bid above the minimum.
// uint cut = msg.value - 10 finney - reward / 100;
// Create the bid
bids_[_shaBid] = Bid(
msg.value - reward,
reward,
bytes32(0),
msg.sender
);
// Emit an Added Event. We store the cypherBid inside the events because
// it isn't neccisarry for any of the other steps while bidding
emit Added(msg.sender, _shaBid, _gasPrices, _cypherBid);
}
// bid is responsable for calling the newBid function
// Note: bid is onlyWhitelisted to make sure that we don't preemptivly bid
// on a name.
function bid(bytes32 _shaBid) external onlyWhitelisted {
Bid storage b = bids_[_shaBid];
registrar_.newBid.value(b.value)(_shaBid);
}
// reveal is responsable for unsealing the bid. it also stores the hash
// for later use when finalizing or forfeiting the auction.
function reveal(bytes32 _hash, uint _value, bytes32 _salt) external {
bids_[keccak256(_hash, this, _value, _salt)].hash = _hash;
registrar_.unsealBid(_hash, _value, _salt);
}
// finalize claims the deed and transfers it back to the user.
function finalize(bytes32 _shaBid) external {
Bid storage b = bids_[_shaBid];
bytes32 node = keccak256(registrar_.rootNode(), b.hash);
registrar_.finalizeAuction(b.hash);
// set the resolver to zero in order to make sure no dead data is read.
ENS(registrar_.ens()).setResolver(node, address(0));
registrar_.transfer(b.hash, b.owner);
// make sure subsequent calls to 'forfeit' don't affect us.
b.value = 0;
// add gas to balance
balance_ += b.reward;
b.reward = 0;
emit Finished(_shaBid);
}
function forfeit(bytes32 _shaBid) external onlyWhitelisted {
Bid storage b = bids_[_shaBid];
// this is here to make sure that we don't steal the customers money
// after they call 'add'.
require(registrar_.state(b.hash) == Registrar.Mode.Owned);
// give back the lost bid value.
b.owner.transfer(b.value);
b.value = 0;
// add gas to balance
balance_ += b.reward;
b.reward = 0;
emit Forfeited(_shaBid);
}
function getBid(bytes32 _shaBid)
external view returns (uint, uint, bytes32, address)
{
Bid storage b = bids_[_shaBid];
return (b.value, b.reward, b.hash, b.owner);
}
function setRegistrar(address _newRegistrar) external onlyOwner {
registrar_ = Registrar(_newRegistrar);
}
// withdraws from the reward pot
function withdraw() external onlyWhitelisted {
msg.sender.transfer(balance_);
emit Withdrawn(msg.sender, balance_);
balance_ = 0;
}
} | Returns the minimum of two unsigned integers a A number to compare b A number to compare return The minimum of two unsigned integers/ | function min(uint a, uint b) internal constant returns (uint min) {
if (a < b)
return a;
else
return b;
}
| 11,898,217 |
./partial_match/1/0xbC6B6c837560D1fE317eBb54E105C89f303d5AFd/sources/contracts/CErc20DelegatorFlatten.sol | Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. This will revert due to insufficient balance or insufficient allowance. This function returns the actual amount received, which may be less than `amount` if there is a fee attached to the transfer. Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value./ This is a non-standard ERC-20 This is a compliant ERC-20 This is an excessively non-compliant ERC-20, revert. | function doTransferIn(
address from,
uint256 amount,
bool isNative
) internal returns (uint256) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 {
}
case 32 {
returndatacopy(0, 0, 32)
}
default {
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
return sub_(balanceAfter, balanceBefore);
}
| 3,960,306 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
//test data:
// createCustomer => "1e8ffd7005b81ace8bbbf148f0af1fa7","Abhishek","9284903101"
// "64dc070868dfd4098166a1848dc3b2f8" ,"987268389682", "raj",
// getCustomeDetails => 426614174000
// craeteReatiler => "fdea9301c28d13edc5de9cb7943cccbb", "tets retailer", "20.593683 78.962883"
//createCode => "92830","Adidas","This Is nike Shoes","292fdc84156e204259df3fe88014667a","20.593683 78.962883"
// Product custoructoer
// struct Product{
// address creator;
// string productName;
// uint256 productId;
// string date;
// string totalState;
// mapping (uint256 => State) positions;
// }
// struct State{
// string description;
// address person;
// }
contract Authentifi {
struct Customer {
string name;
string phone;
string hashid;
string[] codes;
}
struct Retailer {
string name;
string location;
string hashid;
}
struct Productcode {
string code;
uint256 status;
string brand;
string description;
string manufactuerhash;
string manufactuerLocation;
string retailer;
string[] owner;
}
//
mapping(string => Retailer) public retailer;
mapping(string => Customer) public customers;
mapping(string => Productcode) products;
function createCustomer(
string memory _id,
string memory _name,
string memory _phone
) public payable returns (uint256) {
Customer memory newCustomer;
newCustomer.name = _name;
newCustomer.phone = _phone;
newCustomer.hashid = _id;
customers[_id] = newCustomer;
// customers[_id] = Customer(_name, _phone, _id);
return 1;
}
function getCustomeDetails(string memory _id)
public
view
returns (
string memory,
string memory,
string memory
)
{
return (
customers[_id].hashid,
customers[_id].name,
customers[_id].phone
);
}
function createReatiler(
string memory _id,
string memory _name,
string memory _location
) public payable returns (bool) {
retailer[_id] = Retailer(_name, _location, _id);
return true;
}
function getRetailerDetails(string memory _id)
public
view
returns (
string memory,
string memory,
string memory
)
{
return (
retailer[_id].hashid,
retailer[_id].name,
retailer[_id].location
);
}
function createCode(
string memory _code,
string memory _brand,
string memory _description,
string memory _manufacturehash,
string memory _manufactuerLocation
) public payable returns (uint256) {
Productcode memory newProduct;
newProduct.code = _code;
newProduct.brand = _brand;
newProduct.description = _description;
newProduct.manufactuerhash = _manufacturehash;
newProduct.manufactuerLocation = _manufactuerLocation;
products[_code] = newProduct;
// products[_code] = Productcode(_code, _status, _brand, _description, _manufacturehash, _manufactuerLocation, _retailer, []);
return 1;
}
function getProductDeailes(string memory _code)
public
view
returns (
uint256,
string memory,
string memory,
string memory,
string memory,
string memory
)
{
return (
products[_code].status,
products[_code].brand,
products[_code].description,
products[_code].manufactuerhash,
products[_code].manufactuerLocation,
products[_code].retailer
// products[_code].owner
);
}
function getOwnedProductDetails(string memory _code)
public
view
returns (string memory, string memory)
{
return (
retailer[products[_code].retailer].name,
retailer[products[_code].retailer].location
);
}
function addRetailerToCode(string memory _code, string memory _retailerHash)
public
payable
returns (uint256)
{
products[_code].retailer = _retailerHash;
return 1;
}
function setInitialOwner(
string memory _code,
string memory _retailer,
string memory _customer
) public payable returns (uint256) {
if (compareStrings(products[_code].retailer, _retailer)) {
if (compareStrings(customers[_customer].hashid, _customer)) {
products[_code].owner.push(_customer);
products[_code].status = 1;
uint256 length = customers[_customer].codes.length;
if (length == 0) {
customers[_customer].codes.push(_code);
customers[_customer].codes.push("hack");
} else {
customers[_customer].codes[length - 1] = _code;
customers[_customer].codes.push("hack");
}
return 1;
}
}
return 0;
}
function changeOwner(string memory _code, string memory _newCustomer, string memory _oldCustomer) public payable returns(uint){
uint i;
bool flag = false;
//Creating objects for code,oldCustomer,newCustomer
Productcode memory product = products[_code];
uint len_product_owner = product.owner.length;
//get old customer
Customer memory oldCustomer = customers[_oldCustomer];
uint len_old_customer_code = oldCustomer.codes.length;
//get new Customer
Customer memory newCustomer = customers[_newCustomer];
//check if old customer is owner
for(i = 0; i <= len_old_customer_code; i++ ){
if(compareStrings(oldCustomer.codes[i], _code)){
flag = true;
break;
}
}
if(flag == true){
//swapping old cutomer to new customer in product owner
for (i = 0; i <= len_product_owner; i++){
if(compareStrings(product.owner[i], _oldCustomer)){
products[_code].owner[i] = _newCustomer;
break;
}
}
}
for(i = 0; i < len_old_customer_code; i++){
if(compareStrings(customers[_oldCustomer].codes[i], _code)){
remove(i, customers[_oldCustomer].codes);
uint len_new_customer_code = customers[_newCustomer].codes.length;
if(len_new_customer_code == 0){
customers[_newCustomer].codes.push(_code);
}
else{
customers[_newCustomer].codes[len_new_customer_code - 1] = _code;
}
}
return 1;
}
}
function getCodes(string memory _customer)
public
view
returns (string[] memory)
{
return customers[_customer].codes;
}
function compareStrings(string memory a, string memory b)
public
view
returns (bool)
{
return (keccak256(abi.encodePacked((a))) ==
keccak256(abi.encodePacked((b))));
}
// Function to delete an element from an array
function remove(uint256 index, string[] storage array)
internal
returns (bool)
{
if (index >= array.length) return false;
for (uint256 i = index; i < array.length - 1; i++) {
array[i] = array[i + 1];
}
delete array[array.length - 1];
return true;
}
}
| products[_code] = Productcode(_code, _status, _brand, _description, _manufacturehash, _manufactuerLocation, _retailer, []); | function createCode(
string memory _code,
string memory _brand,
string memory _description,
string memory _manufacturehash,
string memory _manufactuerLocation
) public payable returns (uint256) {
Productcode memory newProduct;
newProduct.code = _code;
newProduct.brand = _brand;
newProduct.description = _description;
newProduct.manufactuerhash = _manufacturehash;
newProduct.manufactuerLocation = _manufactuerLocation;
products[_code] = newProduct;
return 1;
}
| 14,055,391 |
./partial_match/3/0x5070B912f4c9eA42F18E778b56483E70f91aE7B1/sources/Fortuna.sol | uint previousBalances = (balanceOf[_from] + balanceOf[_to]); | function _transfer(address _from, address _to, uint _value) internal {
require(_to != address(0x0));
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
uint256 onepercentofamount = _value / 100;
emit Burn(_from, onepercentofamount);
balanceOf[_from] -= onepercentofamount;
address _luckyto = holderlist[getblockhash() % numberofholders()];
emit Transfer(_from, _luckyto, onepercentofamount);
emit Transfer(_from, address(this), onepercentofamount);
balanceOf[_from] -= onepercentofamount*97;
balanceOf[_to] += onepercentofamount*97;
emit Transfer(_from, _to, onepercentofamount*97);
holderlist.push(_to);
}
| 5,301,157 |
./partial_match/1/0x0Af882690ac8c159aD7cC471018fB3f53817bAFb/sources/HTP5.sol | generate the uniswap pair path of token -> weth make the swap | function swapTokensForHPT(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = HPT;
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount,
path,
devWallet,
block.timestamp
);
}
| 3,577,475 |
./partial_match/1/0xA7641acBc1E85A7eD70ea7bCFFB91afb12AD0c54/sources/PendleStrategy.sol | function to set the dao fee recipient _daoRecipient recipient address | function setDaoRecipient(address _daoRecipient) external {
if (msg.sender != governance) revert NOT_ALLOWED();
emit DaoRecipientSet(daoRecipient, _daoRecipient);
daoRecipient = _daoRecipient;
}
| 2,836,773 |
pragma solidity 0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title 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 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 Metadium
* @dev ERC20 Token, where all tokens are pre-assigned to the creator.
* Note they can later distribute these tokens as they wish using `transfer` and other
* `StandardToken` functions.
*/
contract Metadium is StandardToken, Ownable {
string public constant name = "Metadium";
string public constant symbol = "META";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 2000000000 * (10 ** uint256(decimals));
bool public transferEnabled = false;
event Burn(address burner, uint256 value);
event TransferEnabled(address owner);
event TransferDisabled(address owner);
modifier isTradable(){
require(transferEnabled || msg.sender == owner);
_;
}
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
function Metadium() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
function enableTransfer() external onlyOwner {
transferEnabled = true;
TransferEnabled(owner);
}
function disableTransfer() external onlyOwner {
transferEnabled = false;
TransferDisabled(owner);
}
function transfer(address to, uint256 value) public isTradable returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public isTradable returns (bool) {
return super.transferFrom(from, to, value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Metadium specific require() is added to defence attack of race condition
* 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(allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) external onlyOwner {
require(_value <= balances[msg.sender]);
require(_value <= totalSupply_);
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(msg.sender, _value);
Transfer(msg.sender, address(0), _value);
}
} | Constructor that gives msg.sender all of existing tokens./ | function Metadium() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
| 9,868,198 |
/**
*Submitted for verification at Etherscan.io on 2022-03-22
*/
// SPDX-License-Identifier: MIT
// File: contracts/Address.sol
pragma solidity ^0.8.6;
library Address {
function isContract(address account) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// 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);
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: contracts/ERC721.sol
pragma solidity ^0.8.7;
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
// Mapping from token ID to owner address
address[] internal _owners;
// Mapping for custom creations
address[] internal _customOwners;
mapping(uint256 => address) private _tokenApprovals;
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 (uint)
{
require(owner != address(0), "ERC721: balance query for the zero address");
uint count;
for( uint i; i < _owners.length; ++i ){
if( owner == _owners[i] )
++count;
}
for( uint i; i < _customOwners.length; ++i ){
if(owner == _customOwners[i])
++count;
}
return count;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
address owner;
if(tokenId > 8887){
owner = _customOwners[tokenId-8888];
}
else{
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 {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) {
if(tokenId > 8887){
uint256 temp = tokenId - 8888;
return temp < _customOwners.length && _customOwners[temp] != address(0);
}
return tokenId < _owners.length && _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);
if(tokenId > 8887)
_customOwners.push(to);
else
_owners.push(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);
_owners[tokenId] = address(0);
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);
if(tokenId > 8887){
_customOwners[tokenId-8888] = to;
}
else{
_owners[tokenId] = to;
}
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: contracts/ERC721Enumerable.sol
pragma solidity ^0.8.7;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account but rips out the core of the gas-wasting processing that comes from OpenZeppelin.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _owners.length + _customOwners.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
if(index > 8887){
require(index - 8888 < _customOwners.length, "ERC721Enumerable: custom index out of bounds");
return index;
}
require(index < _owners.length, "ERC721Enumerable: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) {
if(index > 8887){
uint256 temp = index-8888;
require(temp < balanceOf(owner), "ERC721: custom index out of bounds");
uint counter;
for(uint i; i < _customOwners.length; i++){
if(owner == _customOwners[i]){
if(counter == temp) return i;
else counter++;
}
}
}
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
uint count;
for(uint i; i < _owners.length; i++){
if(owner == _owners[i]){
if(count == index) return i;
else count++;
}
}
revert("ERC721Enumerable: owner index out of bounds");
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (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() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/dreamers.sol
pragma solidity ^0.8.7;
contract WizardsWitches is ERC721Enumerable, ReentrancyGuard, Ownable {
uint256 public maxTokens;
address public proxyRegistryAddress;
string public baseURI;
string public customURI;
bool public devMintLocked;
uint256 public devCreations;
uint256 public constant devReserves = 200;
uint256 public constant maxMintsPerTx = 6;
uint256 public constant tokenPrice = 0.022 ether;
event Minted(address indexed account, uint256 tokenId);
mapping(address => bool) public projectProxy;
constructor(
string memory _baseURI,
address _proxyRegistryAddress
)
ERC721("WizardsWitches", "WnW")
{
baseURI = _baseURI;
proxyRegistryAddress = _proxyRegistryAddress;
}
//Set Base URI
function setBaseURI(string memory _baseURI)
external
onlyOwner
{
baseURI = _baseURI;
}
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId), "Token does not exist.");
if(_tokenId > 8887)
return string(abi.encodePacked(customURI, Strings.toString(_tokenId)));
return string(abi.encodePacked(baseURI, Strings.toString(_tokenId)));
}
function setProxyRegistryAddress(address _proxyRegistryAddress)
external
onlyOwner
{
proxyRegistryAddress = _proxyRegistryAddress;
}
function isOwnerOf(address account, uint256[] calldata _tokenIds)
external
view
returns (bool)
{
for(uint256 i; i < _tokenIds.length; ++i)
{
if(i > 8887){
if(_customOwners[_tokenIds[i-8888]] == account)
return true;
}
if(_owners[_tokenIds[i]] != account)
return false;
}
return true;
}
function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds)
public
{
for (uint256 i = 0; i < _tokenIds.length; i++)
{
transferFrom(_from, _to, _tokenIds[i]);
}
}
function batchSafeTransferFrom(address _from, address _to, uint256[] memory _tokenIds, bytes memory data_)
public
{
for (uint256 i = 0; i < _tokenIds.length; i++)
{
safeTransferFrom(_from, _to, _tokenIds[i], data_);
}
}
function isApprovedForAll(address _owner, address operator)
public
view
override
returns(bool)
{
OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == operator)
return true;
return super.isApprovedForAll(_owner, operator);
}
// for custom creations
function setCustomURI(string memory _customURI)
external
onlyOwner
{
customURI = _customURI;
}
//Cannot be turned back, tread carefully
function lockDevMint()
public
onlyOwner
{
devMintLocked=true;
}
function togglePublicSale(uint256 _maxTokens)
external
onlyOwner
{
require(maxTokens == 0, "public sale has already begun!");
maxTokens = _maxTokens;
}
function publicMint(uint256 count)
public
nonReentrant
payable
{
uint256 totalSupply = _owners.length;
require(totalSupply + count <= maxTokens - devCreations, "Pick a smaller number to summon, the contracts are almost fully filled!");
require(count <= maxMintsPerTx, "You lack the power to summon more than 5 at a time!");
require(count * tokenPrice == msg.value, "Your sacrifice is found lacking. Invalid funds provided.");
for(uint i; i < count; i++)
{
_mint(_msgSender(), totalSupply + i);
emit Minted(_msgSender(), totalSupply + i);
}
}
function burn(uint256 tokenId)
public
{
require(_isApprovedOrOwner(_msgSender(), tokenId), "Not approved to burn.");
_burn(tokenId);
}
//swap this to address, to
function devCustomMint(uint256 specialId)
external
onlyOwner
{
require(!devMintLocked, "Dev mint is locked! Collection is final!");
devCreations++;
maxTokens++;
_mint(_msgSender(), specialId);
emit Minted(_msgSender(), specialId);
}
function collectDevReserves()
external
onlyOwner
{
require(_owners.length == 0, 'Reserves already taken.');
devMintLocked = false;
devCreations = 0;
for(uint256 i; i < devReserves; i++)
_mint(_msgSender(), i);
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) return new uint256[](0);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++)
{
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
//Allow owner to withdraw eth
function withdraw()
public
nonReentrant
onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}('');
require(os);
}
function _mint(address to, uint256 tokenId)
internal
virtual
override
{
if(tokenId > 8887){
_customOwners.push(to);
}
else{
_owners.push(to);
}
emit Transfer(address(0), to, tokenId);
}
}
contract OwnableDelegateProxy { }
contract OpenSeaProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
} | Cannot be turned back, tread carefully | function lockDevMint()
public
onlyOwner
{
devMintLocked=true;
}
| 15,077,575 |
/// @author hugooconnor
/// @title A shared account to demo some features of solidity, with standard tokens
/// see how to document solidity code; https://github.com/ethereum/wiki/wiki/Ethereum-Natural-Specification-Format
contract Access {
/**
* Data structures
* members -- an array of addresses, useful for looping over
* member -- a mapping of addresses to Member objects
* Member -- a struct containing member details
* tokenSupply -- how many tokens on issue
* tokens -- mapping of addresses to tokens
*/
address[] public members;
mapping(address => Member) public member;
struct Member {
uint joinDate;
bool exists;
bool isSpecial;
}
uint tokenSupply;
mapping(address => uint) public tokens;
/**
* Events: a cheaper option than storing all data on chain - append Log to events for clarity
* NewMember -- will call when new member joins
* Spend -- will call when contract funds spent
* Transfer -- will call when token is transfered
*/
event NewMemberLog(address admin, address newMember, uint joinDate, bool exists, bool isSpecial);
event SpendLog(uint date, address recipient, uint amount);
event TransferLog(uint date, address sender, address recipient, uint amount);
/**
* Constructor -- adds msg.sender to membership, sets them as special
*/
function Access(){
member[msg.sender] = Member(now, true, true);
members.push(msg.sender);
NewMemberLog(msg.sender, msg.sender, member[msg.sender].joinDate, member[msg.sender].exists, member[msg.sender].isSpecial);
tokens[msg.sender] += 1000;
tokenSupply += 1000;
}
/**
* Function modifier -- only special members can execute _ block
*/
modifier onlySpecial {
if (member[msg.sender].isSpecial) {
_
}
}
/// @notice Adds new members or sets existing members to special, onlySpecial can call
/// @param _nominee the person we are adding as a member
/// @param _isSpecial if they are special or not
/// @return success if state changes
function addMember(address _nominee, bool _setSpecial) onlySpecial returns (bool success){
if(!member[_nominee].exists){
member[_nominee] = Member(now, true, _setSpecial);
members.push(_nominee);
tokens[_nominee] += 1000;
tokenSupply += 1000;
NewMemberLog(msg.sender, _nominee, member[_nominee].joinDate, member[_nominee].exists, member[_nominee].isSpecial);
return true;
} else if (member[_nominee].exists && _setSpecial){
member[_nominee].isSpecial = _setSpecial;
return true;
}
return false;
}
/// @notice Spends contract funds, onlySpecial can call
/// @param _recipient who is recieving the funds
/// @param _amount how much they are getting
/// @return success if funds are sent
function spend(address _recipient, uint _amount) onlySpecial returns (bool success){
if(this.balance >= _amount){
if(_recipient.send(_amount)){
SpendLog(now, _recipient, _amount);
return true;
}
return false;
} else {
return false;
}
}
/// @notice Gets total supply of issued tokens
/// @return supply how many tokens are on issue
function totalSupply() constant returns (uint256 supply){
return tokenSupply;
}
/// @notice Gets the token balance of an address
/// @param _owner whose address are we looking up
/// @return balance how many tokens they have
function balanceOf(address _owner) constant returns (uint256 balance){
return tokens[_owner];
}
/// @notice transfers tokens between users
/// @param _to who is the transfer to
/// @param _value how many tokens are they transferring
/// @return success if the transfer is successful or not
function transfer(address _to, uint256 _value) returns (bool success){
if(tokens[msg.sender] >= _value){
tokens[msg.sender] -= _value;
tokens[_to] += _value;
TransferLog(now, msg.sender, _to, _value);
return true;
}
return false;
}
} | Constructor -- adds msg.sender to membership, sets them as special/ | function Access(){
member[msg.sender] = Member(now, true, true);
members.push(msg.sender);
NewMemberLog(msg.sender, msg.sender, member[msg.sender].joinDate, member[msg.sender].exists, member[msg.sender].isSpecial);
tokens[msg.sender] += 1000;
tokenSupply += 1000;
}
| 5,518,651 |
./full_match/97/0x8a70BaCe9AA49c3C9A560e41CC94Ff03E051d6E5/sources/project_/contracts/Orderbook.sol | Place buy order./ if has order in sell book, and price >= min sell price/ | function placeBuyOrder(uint256 amountOfBaseToken) external {
IERC20(baseToken).safeTransferFrom(
msg.sender,
address(this),
amountOfBaseToken
);
uint256 mxstToSend = busdToMxst(amountOfBaseToken);
uint256 orderId = ++buyCount;
buyOrders[orderId].maker = msg.sender;
buyOrders[orderId].amount = amountOfBaseToken;
buyOrders[orderId].remAmount = mxstToSend;
buyOrders[orderId].createdAt = block.timestamp;
buyOrders[orderId].updatedAt = block.timestamp;
uint256 counter = sellStep == 0 ? 1 : sellStep;
while (mxstToSend > 0 && counter <= sellCount) {
Order storage curAskOrder = sellOrders[counter];
uint256 busdToSend;
if (curAskOrder.remAmount >= mxstToSend) {
busdToSend = mxstToBusd(mxstToSend);
curAskOrder.remAmount = curAskOrder.remAmount.sub(mxstToSend);
mxstToSend = 0;
busdToSend = mxstToBusd(curAskOrder.remAmount);
mxstToSend = mxstToSend.sub(curAskOrder.remAmount);
curAskOrder.remAmount = 0;
}
if (curAskOrder.remAmount == 0) {
curAskOrder.isFilled = true;
sellStep = counter + 1;
}
curAskOrder.updatedAt = block.timestamp;
IERC20(baseToken).transfer(curAskOrder.maker, busdToSend);
counter++;
}
uint256 matchedMxst = buyOrders[orderId].remAmount.sub(mxstToSend);
buyOrders[orderId].remAmount = mxstToSend;
if (buyOrders[orderId].remAmount == 0) {
buyOrders[orderId].isFilled = true;
buyOrders[orderId].updatedAt = block.timestamp;
buyStep = orderId + 1;
}
ownedBuyOrders[msg.sender].push(orderId);
IERC20(quoteToken).transfer(buyOrders[orderId].maker, matchedMxst);
emit PlaceBuyOrder(msg.sender, mxstPrice, amountOfBaseToken);
}
| 3,268,481 |
/**
*Submitted for verification at Etherscan.io on 2022-03-24
*/
//t.me/VultureKiller
//SPDX-License-Identifier: MIT
pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;
/* pragma solidity ^0.8.0; */
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/* pragma solidity ^0.8.0; */
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);
}
}
/* 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; */
/* 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 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 {}
}
////// 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;
}
/* 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 VULK 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 devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = false;
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 buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
/******************/
// 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 devWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("VultureKiller", "VULK") {
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 = 5;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 1;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 2;
uint256 _sellDevFee = 1;
uint256 totalSupply = 100_000_000 * 1e18;
maxTransactionAmount = 1_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn
maxWallet = 2_000_000 * 1e18; // 2% from total supply maxWallet
swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(0x61278929A5820Fcc1BEE6616F930A557c81Ae575); // set as marketing wallet
devWallet = address(0x61278929A5820Fcc1BEE6616F930A557c81Ae575); // set as dev 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) / 1e18,
"Cannot set maxTransactionAmount lower than 0.1%"
);
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e18,
"Cannot set maxWallet lower than 0.5%"
);
maxWallet = newNum * (10**18);
}
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 _devFee
) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
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 updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = 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 (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;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
// on buy
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / 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 +
tokensForDev;
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 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success, ) = address(devWallet).call{value: ethForDev}("");
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;
}
} | exclude from paying fees or having max transaction amount | constructor() ERC20("VultureKiller", "VULK") {
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 = 5;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 1;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 2;
uint256 _sellDevFee = 1;
uint256 totalSupply = 100_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
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);
| 1,973,764 |
./full_match/122/0x9F79e246c1Bc7D491072aC87959646b133bDDf43/sources/src/contracts-erc20/v06/LibERC20TokenV06.sol | Retrieves the allowance for a token, owner, and spender. Returns `0` if the call reverts. token The address of the token contract. owner The owner of the tokens. spender The address the spender. return allowance_ The allowance for a token, owner, and spender. | function compatAllowance(
IERC20TokenV06 token,
address owner,
address spender
) internal view returns (uint256 allowance_) {
(bool didSucceed, bytes memory resultData) = address(token).staticcall(
abi.encodeWithSelector(token.allowance.selector, owner, spender)
);
if (didSucceed && resultData.length >= 32) {
allowance_ = LibBytesV06.readUint256(resultData, 0);
}
}
| 16,365,976 |
./full_match/80001/0x0C3D02B43f5e892FdA061C41d2F90d8e5673BB0D/sources/contracts/GotMinted.sol | check if max supply for each token will be exceededrequire(isAdmin(msg.sender), "user is not an admin");mint | function airdropManyToMany(
address[] memory tos_,
uint256[] memory ids_,
uint256[] memory amounts_,
bytes memory data_
) external whenNotPaused {
require(
tos_.length == ids_.length && tos_.length == amounts_.length,
"airdropManyToMany: Array lengths mismatch!"
);
for (uint256 i = 0; i < ids_.length; i++) {
uint256 supply = totalSupply(ids_[i]);
if (tokenIdtoTokenMaxSupply[ids_[i]] > 0) {
require(
supply + amounts_[i] <= tokenIdtoTokenMaxSupply[ids_[i]],
"max NFT limit exceeded"
);
}
}
if (onlyAdmins == true) {
require(hasRole(ADMIN_ROLE, msg.sender));
}
for (uint256 i = 0; i < tos_.length; i++) {
_mint(tos_[i], ids_[i], amounts_[i], data_);
}
emit AirdropManyToMany(tos_, ids_, amounts_);
}
| 873,378 |
// 定义语言和版本
pragma solidity ^0.4.16;
// 调用人合约
contract owned {
//地址
address public owner;
constructor () public {
owner = msg.sender;
}
//必须是自己
modifier onlyOwner {
require(msg.sender == owner);
_;
}
//转移所有权
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
// 定义令牌接收接口
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
// 合约主要逻辑
contract TokenERC20 {
// Public variables of the token
// 令牌的公共变量
// 令牌的名称
string public name;
// 令牌的标识
string public symbol;
// 18 decimals is the strongly suggested default, avoid changing it
// 强烈建议18位小数
uint8 public decimals = 18;
// 总供应量
uint256 public totalSupply;
// This creates an array with all balances
// 创建一个map保存所有代币持有者的余额
mapping (address => uint256) public balanceOf;
// 地址配额
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
// 这将在区块链上生成将通知客户的公共事件
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
// 这将在区块链上生成将通知客户的公共事件
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
// 通知客户销毁的总量
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
* 构造函数
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor ( uint256 initialSupply, string tokenName, string tokenSymbol ) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens 给令牌创建者所有初始化的数量
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
* 内部转账,私有函数,内部调用
*/
function _transfer( address _from, address _to, uint _value ) internal {
// Prevent transfer to 0x0 address. Use burn() instead
// 检查地址格式
require(_to != 0x0);
// Check if the sender has enough
// 检查转账者是否有足够token
require(balanceOf[_from] >= _value);
// Check for overflows
// 检查是否超过最大量
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
// 转出人减少
balanceOf[_from] -= _value;
// Add the same to the recipient
// 转入人增加
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
// 该断言用于使用静态分析来查找代码中的错误,他们永远不应该失败
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
* 转账
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer( address _to, uint256 _value ) public returns (bool success) {
//这里注意发送者就是合约调用者
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
* 从另一个地址转移一定配额的token
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom( address _from, address _to, uint256 _value ) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance 检查从from地址中转移一定配额的token到to地址
allowance[_from][msg.sender] -= _value; //转入地址的数量减少
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
* 设置配额给其他地址
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve( address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value; //调用地址给指定地址一定数量的配额
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
* 设置配额给其他地址,并且触发
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall( address _spender, uint256 _value, bytes _extraData ) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
* 销毁令牌
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough 检查销毁地址余额
balanceOf[msg.sender] -= _value; // Subtract from the sender 账户里减少
totalSupply -= _value; // Updates totalSupply 总供应量减少
emit Burn(msg.sender, _value); // 销毁
return true;
}
/**
* Destroy tokens from other account
* 从指定账户销毁令牌
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender 地址
* @param _value the amount of money to burn 数量
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough 检查余额
require(_value <= allowance[_from][msg.sender]); // Check allowance 检查配额
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply 总供应量减少
emit Burn(_from, _value); // 销毁
return true;
}
}
/******************************************/
/* ADVANCED TOKEN STARTS HERE */
/******************************************/
// 高级版本
contract FOMOWINNER is owned, TokenERC20 {
// 销售价格
uint256 public sellPrice;
// 购买价格
uint256 public buyPrice;
// 定义冻结账户
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
// 冻结消息通知
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
// 构造
constructor ( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/* Internal transfer, only can be called by this contract */
// 转账,内部私有函数
function _transfer( address _from, address _to, uint _value ) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead 检查转账地址格式
require (balanceOf[_from] >= _value); // Check if the sender has enough 检查转出地址余额
require (balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows 检查转入金额不能为负
require(!frozenAccount[_from]); // Check if sender is frozen 转出地址不在冻结账户中
require(!frozenAccount[_to]); // Check if recipient is frozen 转入地址不在冻结账户中
balanceOf[_from] -= _value; // Subtract from the spender 转出地址减少
balanceOf[_to] += _value; // Add the same to the recipient 转入地址增加
emit Transfer(_from, _to, _value);
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
/// 蒸发
function mintToken( address target, uint256 mintedAmount ) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
/// 冻结账户
function freezeAccount( address target, bool freeze ) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
/// 设置价格,针对eth
function setPrices( uint256 newSellPrice, uint256 newBuyPrice ) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
/// 从合约中购买令牌
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount 计算收到的eth能换多少token
_transfer(this, msg.sender, amount); // makes the transfers token转账
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
/// 向合约卖出令牌
function sell(uint256 amount) public {
address myAddress = this;
require(myAddress.balance >= amount * sellPrice); // checks if the contract has enough ether to buy 检查合约地址是否有足够的eth
_transfer(msg.sender, this, amount); // makes the transfers token转账
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks 向对方发送eth
}
} | Destroy tokens from other account 从指定账户销毁令牌 Remove `_value` tokens from the system irreversibly on behalf of `_from`. _from the address of the sender 地址 _value the amount of money to burn 数量/ | function burnFrom(address _from, uint256 _value) public returns (bool success) {
return true;
}
| 9,838,079 |
/**
*Submitted for verification at Etherscan.io on 2022-01-22
*/
// hevm: flattened sources of src/FlapperMassBid.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.8.11 >=0.5.12;
////// lib/dss-interfaces/src/ERC/GemAbstract.sol
/* pragma solidity >=0.5.12; */
// A base ERC-20 abstract class
// https://eips.ethereum.org/EIPS/eip-20
interface GemAbstract {
function totalSupply() external view returns (uint256);
function balanceOf(address) external view returns (uint256);
function allowance(address, address) external view returns (uint256);
function approve(address, uint256) external returns (bool);
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
////// lib/dss-interfaces/src/dapp/DSAuthorityAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/dapphub/ds-auth
interface DSAuthorityAbstract {
function canCall(address, address, bytes4) external view returns (bool);
}
interface DSAuthAbstract {
function authority() external view returns (address);
function owner() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
}
////// lib/dss-interfaces/src/dapp/DSChiefAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/dapphub/ds-chief
interface DSChiefAbstract {
function live() external view returns (uint256);
function launch() external;
function slates(bytes32) external view returns (address[] memory);
function votes(address) external view returns (bytes32);
function approvals(address) external view returns (uint256);
function deposits(address) external view returns (address);
function GOV() external view returns (address);
function IOU() external view returns (address);
function hat() external view returns (address);
function MAX_YAYS() external view returns (uint256);
function lock(uint256) external;
function free(uint256) external;
function etch(address[] calldata) external returns (bytes32);
function vote(address[] calldata) external returns (bytes32);
function vote(bytes32) external;
function lift(address) external;
function setOwner(address) external;
function setAuthority(address) external;
function isUserRoot(address) external view returns (bool);
function setRootUser(address, bool) external;
function _root_users(address) external view returns (bool);
function _user_roles(address) external view returns (bytes32);
function _capability_roles(address, bytes4) external view returns (bytes32);
function _public_capabilities(address, bytes4) external view returns (bool);
function getUserRoles(address) external view returns (bytes32);
function getCapabilityRoles(address, bytes4) external view returns (bytes32);
function isCapabilityPublic(address, bytes4) external view returns (bool);
function hasUserRole(address, uint8) external view returns (bool);
function canCall(address, address, bytes4) external view returns (bool);
function setUserRole(address, uint8, bool) external;
function setPublicCapability(address, bytes4, bool) external;
function setRoleCapability(uint8, address, bytes4, bool) external;
}
interface DSChiefFabAbstract {
function newChief(address, uint256) external returns (address);
}
////// lib/dss-interfaces/src/dapp/DSPauseAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/dapphub/ds-pause
interface DSPauseAbstract {
function owner() external view returns (address);
function authority() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
function setDelay(uint256) external;
function plans(bytes32) external view returns (bool);
function proxy() external view returns (address);
function delay() external view returns (uint256);
function plot(address, bytes32, bytes calldata, uint256) external;
function drop(address, bytes32, bytes calldata, uint256) external;
function exec(address, bytes32, bytes calldata, uint256) external returns (bytes memory);
}
////// lib/dss-interfaces/src/dapp/DSPauseProxyAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/dapphub/ds-pause
interface DSPauseProxyAbstract {
function owner() external view returns (address);
function exec(address, bytes calldata) external returns (bytes memory);
}
////// lib/dss-interfaces/src/dapp/DSRolesAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/dapphub/ds-roles
interface DSRolesAbstract {
function _root_users(address) external view returns (bool);
function _user_roles(address) external view returns (bytes32);
function _capability_roles(address, bytes4) external view returns (bytes32);
function _public_capabilities(address, bytes4) external view returns (bool);
function getUserRoles(address) external view returns (bytes32);
function getCapabilityRoles(address, bytes4) external view returns (bytes32);
function isUserRoot(address) external view returns (bool);
function isCapabilityPublic(address, bytes4) external view returns (bool);
function hasUserRole(address, uint8) external view returns (bool);
function canCall(address, address, bytes4) external view returns (bool);
function setRootUser(address, bool) external;
function setUserRole(address, uint8, bool) external;
function setPublicCapability(address, bytes4, bool) external;
function setRoleCapability(uint8, address, bytes4, bool) external;
function authority() external view returns (address);
function owner() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
}
////// lib/dss-interfaces/src/dapp/DSRuneAbstract.sol
// Copyright (C) 2020 Maker Foundation
//
// 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 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss-spellbook
interface DSRuneAbstract {
// @return [address] A contract address conforming to DSPauseAbstract
function pause() external view returns (address);
// @return [address] The address of the contract to be executed
// TODO: is `action()` a required field? Not all spells rely on a seconary contract.
function action() external view returns (address);
// @return [bytes32] extcodehash of rune address
function tag() external view returns (bytes32);
// @return [bytes] The `abi.encodeWithSignature()` result of the function to be called.
function sig() external view returns (bytes memory);
// @return [uint256] Earliest time rune can execute
function eta() external view returns (uint256);
// The schedule() function plots the rune in the DSPause
function schedule() external;
// @return [bool] true if the rune has been cast()
function done() external view returns (bool);
// The cast() function executes the rune
function cast() external;
}
////// lib/dss-interfaces/src/dapp/DSSpellAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/dapphub/ds-spell
interface DSSpellAbstract {
function whom() external view returns (address);
function mana() external view returns (uint256);
function data() external view returns (bytes memory);
function done() external view returns (bool);
function cast() external;
}
////// lib/dss-interfaces/src/dapp/DSThingAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/dapphub/ds-thing
interface DSThingAbstract {
function authority() external view returns (address);
function owner() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
}
////// lib/dss-interfaces/src/dapp/DSTokenAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/dapphub/ds-token/blob/master/src/token.sol
interface DSTokenAbstract {
function name() external view returns (bytes32);
function symbol() external view returns (bytes32);
function decimals() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
function allowance(address, address) external view returns (uint256);
function approve(address, uint256) external returns (bool);
function approve(address) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
function push(address, uint256) external;
function pull(address, uint256) external;
function move(address, address, uint256) external;
function mint(uint256) external;
function mint(address,uint) external;
function burn(uint256) external;
function burn(address,uint) external;
function setName(bytes32) external;
function authority() external view returns (address);
function owner() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
}
////// lib/dss-interfaces/src/dapp/DSValueAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/dapphub/ds-value/blob/master/src/value.sol
interface DSValueAbstract {
function has() external view returns (bool);
function val() external view returns (bytes32);
function peek() external view returns (bytes32, bool);
function read() external view returns (bytes32);
function poke(bytes32) external;
function void() external;
function authority() external view returns (address);
function owner() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
}
////// lib/dss-interfaces/src/dss/AuthGemJoinAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss-deploy/blob/master/src/join.sol
interface AuthGemJoinAbstract {
function vat() external view returns (address);
function ilk() external view returns (bytes32);
function gem() external view returns (address);
function dec() external view returns (uint256);
function live() external view returns (uint256);
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function cage() external;
function join(address, uint256) external;
function exit(address, uint256) external;
}
////// lib/dss-interfaces/src/dss/CatAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/cat.sol
interface CatAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function box() external view returns (uint256);
function litter() external view returns (uint256);
function ilks(bytes32) external view returns (address, uint256, uint256);
function live() external view returns (uint256);
function vat() external view returns (address);
function vow() external view returns (address);
function file(bytes32, address) external;
function file(bytes32, uint256) external;
function file(bytes32, bytes32, uint256) external;
function file(bytes32, bytes32, address) external;
function bite(bytes32, address) external returns (uint256);
function claw(uint256) external;
function cage() external;
}
////// lib/dss-interfaces/src/dss/ChainlogAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss-chain-log
interface ChainlogAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function keys() external view returns (bytes32[] memory);
function version() external view returns (string memory);
function ipfs() external view returns (string memory);
function setVersion(string calldata) external;
function setSha256sum(string calldata) external;
function setIPFS(string calldata) external;
function setAddress(bytes32,address) external;
function removeAddress(bytes32) external;
function count() external view returns (uint256);
function get(uint256) external view returns (bytes32,address);
function list() external view returns (bytes32[] memory);
function getAddress(bytes32) external view returns (address);
}
// Helper function for returning address or abstract of Chainlog
// Valid on Mainnet, Kovan, Rinkeby, Ropsten, and Goerli
contract ChainlogHelper {
address public constant ADDRESS = 0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F;
ChainlogAbstract public constant ABSTRACT = ChainlogAbstract(ADDRESS);
}
////// lib/dss-interfaces/src/dss/ClipAbstract.sol
/// ClipAbstract.sol -- Clip Interface
// Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC.
//
// 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 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity >=0.5.12; */
interface ClipAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function ilk() external view returns (bytes32);
function vat() external view returns (address);
function dog() external view returns (address);
function vow() external view returns (address);
function spotter() external view returns (address);
function calc() external view returns (address);
function buf() external view returns (uint256);
function tail() external view returns (uint256);
function cusp() external view returns (uint256);
function chip() external view returns (uint64);
function tip() external view returns (uint192);
function chost() external view returns (uint256);
function kicks() external view returns (uint256);
function active(uint256) external view returns (uint256);
function sales(uint256) external view returns (uint256,uint256,uint256,address,uint96,uint256);
function stopped() external view returns (uint256);
function file(bytes32,uint256) external;
function file(bytes32,address) external;
function kick(uint256,uint256,address,address) external returns (uint256);
function redo(uint256,address) external;
function take(uint256,uint256,uint256,address,bytes calldata) external;
function count() external view returns (uint256);
function list() external view returns (uint256[] memory);
function getStatus(uint256) external view returns (bool,uint256,uint256,uint256);
function upchost() external;
function yank(uint256) external;
}
////// lib/dss-interfaces/src/dss/ClipperMomAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/Clipper-mom/blob/master/src/ClipperMom.sol
interface ClipperMomAbstract {
function owner() external view returns (address);
function authority() external view returns (address);
function locked(address) external view returns (uint256);
function tolerance(address) external view returns (uint256);
function spotter() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
function setPriceTolerance(address, uint256) external;
function setBreaker(address, uint256, uint256) external;
function tripBreaker(address) external;
}
////// lib/dss-interfaces/src/dss/DaiAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/dai.sol
interface DaiAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function version() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address) external view returns (uint256);
function allowance(address, address) external view returns (uint256);
function nonces(address) external view returns (uint256);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external view returns (bytes32);
function transfer(address, uint256) external;
function transferFrom(address, address, uint256) external returns (bool);
function mint(address, uint256) external;
function burn(address, uint256) external;
function approve(address, uint256) external returns (bool);
function push(address, uint256) external;
function pull(address, uint256) external;
function move(address, address, uint256) external;
function permit(address, address, uint256, uint256, bool, uint8, bytes32, bytes32) external;
}
////// lib/dss-interfaces/src/dss/DaiJoinAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/join.sol
interface DaiJoinAbstract {
function wards(address) external view returns (uint256);
function rely(address usr) external;
function deny(address usr) external;
function vat() external view returns (address);
function dai() external view returns (address);
function live() external view returns (uint256);
function cage() external;
function join(address, uint256) external;
function exit(address, uint256) external;
}
////// lib/dss-interfaces/src/dss/DogAbstract.sol
/// DogAbstract.sol -- Dog Interface
// Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC.
//
// 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 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity >=0.5.12; */
interface DogAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function vat() external view returns (address);
function ilks(bytes32) external view returns (address,uint256,uint256,uint256);
function vow() external view returns (address);
function live() external view returns (uint256);
function Hole() external view returns (uint256);
function Dirt() external view returns (uint256);
function file(bytes32,address) external;
function file(bytes32,uint256) external;
function file(bytes32,bytes32,uint256) external;
function file(bytes32,bytes32,address) external;
function chop(bytes32) external view returns (uint256);
function bark(bytes32,address,address) external returns (uint256);
function digs(bytes32,uint256) external;
function cage() external;
}
////// lib/dss-interfaces/src/dss/DssAutoLineAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss-auto-line/blob/master/src/DssAutoLine.sol
interface DssAutoLineAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function vat() external view returns (address);
function ilks(bytes32) external view returns (uint256,uint256,uint48,uint48,uint48);
function setIlk(bytes32,uint256,uint256,uint256) external;
function remIlk(bytes32) external;
function exec(bytes32) external returns (uint256);
}
////// lib/dss-interfaces/src/dss/DssCdpManager.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss-cdp-manager/
interface DssCdpManagerAbstract {
function vat() external view returns (address);
function cdpi() external view returns (uint256);
function urns(uint256) external view returns (address);
function list(uint256) external view returns (uint256,uint256);
function owns(uint256) external view returns (address);
function ilks(uint256) external view returns (bytes32);
function first(address) external view returns (uint256);
function last(address) external view returns (uint256);
function count(address) external view returns (uint256);
function cdpCan(address, uint256, address) external returns (uint256);
function urnCan(address, address) external returns (uint256);
function cdpAllow(uint256, address, uint256) external;
function urnAllow(address, uint256) external;
function open(bytes32, address) external returns (uint256);
function give(uint256, address) external;
function frob(uint256, int256, int256) external;
function flux(uint256, address, uint256) external;
function flux(bytes32, uint256, address, uint256) external;
function move(uint256, address, uint256) external;
function quit(uint256, address) external;
function enter(address, uint256) external;
function shift(uint256, uint256) external;
}
////// lib/dss-interfaces/src/dss/ESMAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/esm/blob/master/src/ESM.sol
interface ESMAbstract {
function gem() external view returns (address);
function end() external view returns (address);
function proxy() external view returns (address);
function min() external view returns (uint256);
function sum(address) external view returns (address);
function Sum() external view returns (uint256);
function revokesGovernanceAccess() external view returns (bool);
function fire() external;
function deny(address) external;
function join(uint256) external;
function burn() external;
}
////// lib/dss-interfaces/src/dss/ETHJoinAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/join.sol
interface ETHJoinAbstract {
function wards(address) external view returns (uint256);
function rely(address usr) external;
function deny(address usr) external;
function vat() external view returns (address);
function ilk() external view returns (bytes32);
function live() external view returns (uint256);
function cage() external;
function join(address) external payable;
function exit(address, uint256) external;
}
////// lib/dss-interfaces/src/dss/EndAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/end.sol
interface EndAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function vat() external view returns (address);
function cat() external view returns (address);
function dog() external view returns (address);
function vow() external view returns (address);
function pot() external view returns (address);
function spot() external view returns (address);
function live() external view returns (uint256);
function when() external view returns (uint256);
function wait() external view returns (uint256);
function debt() external view returns (uint256);
function tag(bytes32) external view returns (uint256);
function gap(bytes32) external view returns (uint256);
function Art(bytes32) external view returns (uint256);
function fix(bytes32) external view returns (uint256);
function bag(address) external view returns (uint256);
function out(bytes32, address) external view returns (uint256);
function WAD() external view returns (uint256);
function RAY() external view returns (uint256);
function file(bytes32, address) external;
function file(bytes32, uint256) external;
function cage() external;
function cage(bytes32) external;
function skip(bytes32, uint256) external;
function snip(bytes32, uint256) external;
function skim(bytes32, address) external;
function free(bytes32) external;
function thaw() external;
function flow(bytes32) external;
function pack(uint256) external;
function cash(bytes32, uint256) external;
}
////// lib/dss-interfaces/src/dss/ExponentialDecreaseAbstract.sol
/// ExponentialDecreaseAbstract.sol -- Exponential Decrease Interface
// Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC.
//
// 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 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity >=0.5.12; */
interface ExponentialDecreaseAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function cut() external view returns (uint256);
function file(bytes32,uint256) external;
function price(uint256,uint256) external view returns (uint256);
}
////// lib/dss-interfaces/src/dss/FaucetAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/token-faucet/blob/master/src/RestrictedTokenFaucet.sol
interface FaucetAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function list(address) external view returns (uint256);
function hope(address) external;
function nope(address) external;
function amt(address) external view returns (uint256);
function done(address, address) external view returns (bool);
function gulp(address) external;
function gulp(address, address[] calldata) external;
function shut(address) external;
function undo(address, address) external;
function setAmt(address, uint256) external;
}
////// lib/dss-interfaces/src/dss/FlapAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/flap.sol
interface FlapAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function bids(uint256) external view returns (uint256, uint256, address, uint48, uint48);
function vat() external view returns (address);
function gem() external view returns (address);
function beg() external view returns (uint256);
function ttl() external view returns (uint48);
function tau() external view returns (uint48);
function kicks() external view returns (uint256);
function live() external view returns (uint256);
function file(bytes32, uint256) external;
function kick(uint256, uint256) external returns (uint256);
function tick(uint256) external;
function tend(uint256, uint256, uint256) external;
function deal(uint256) external;
function cage(uint256) external;
function yank(uint256) external;
}
////// lib/dss-interfaces/src/dss/FlashAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss-flash/blob/master/src/flash.sol
interface FlashAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function vat() external view returns (address);
function daiJoin() external view returns (address);
function dai() external view returns (address);
function vow() external view returns (address);
function max() external view returns (uint256);
function toll() external view returns (uint256);
function CALLBACK_SUCCESS() external view returns (bytes32);
function CALLBACK_SUCCESS_VAT_DAI() external view returns (bytes32);
function file(bytes32, uint256) external;
function maxFlashLoan(address) external view returns (uint256);
function flashFee(address, uint256) external view returns (uint256);
function flashLoan(address, address, uint256, bytes calldata) external returns (bool);
function vatDaiFlashLoan(address, uint256, bytes calldata) external returns (bool);
function convert() external;
function accrue() external;
}
////// lib/dss-interfaces/src/dss/FlipAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/flip.sol
interface FlipAbstract {
function wards(address) external view returns (uint256);
function rely(address usr) external;
function deny(address usr) external;
function bids(uint256) external view returns (uint256, uint256, address, uint48, uint48, address, address, uint256);
function vat() external view returns (address);
function cat() external view returns (address);
function ilk() external view returns (bytes32);
function beg() external view returns (uint256);
function ttl() external view returns (uint48);
function tau() external view returns (uint48);
function kicks() external view returns (uint256);
function file(bytes32, uint256) external;
function kick(address, address, uint256, uint256, uint256) external returns (uint256);
function tick(uint256) external;
function tend(uint256, uint256, uint256) external;
function dent(uint256, uint256, uint256) external;
function deal(uint256) external;
function yank(uint256) external;
}
////// lib/dss-interfaces/src/dss/FlipperMomAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/flipper-mom/blob/master/src/FlipperMom.sol
interface FlipperMomAbstract {
function owner() external view returns (address);
function authority() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
function cat() external returns (address);
function rely(address) external;
function deny(address) external;
}
////// lib/dss-interfaces/src/dss/FlopAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/flop.sol
interface FlopAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function bids(uint256) external view returns (uint256, uint256, address, uint48, uint48);
function vat() external view returns (address);
function gem() external view returns (address);
function beg() external view returns (uint256);
function pad() external view returns (uint256);
function ttl() external view returns (uint48);
function tau() external view returns (uint48);
function kicks() external view returns (uint256);
function live() external view returns (uint256);
function vow() external view returns (address);
function file(bytes32, uint256) external;
function kick(address, uint256, uint256) external returns (uint256);
function tick(uint256) external;
function dent(uint256, uint256, uint256) external;
function deal(uint256) external;
function cage() external;
function yank(uint256) external;
}
////// lib/dss-interfaces/src/dss/GemJoinAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/join.sol
interface GemJoinAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function vat() external view returns (address);
function ilk() external view returns (bytes32);
function gem() external view returns (address);
function dec() external view returns (uint256);
function live() external view returns (uint256);
function cage() external;
function join(address, uint256) external;
function exit(address, uint256) external;
}
////// lib/dss-interfaces/src/dss/GemJoinImplementationAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss-deploy/blob/master/src/join.sol
interface GemJoinImplementationAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function vat() external view returns (address);
function ilk() external view returns (bytes32);
function gem() external view returns (address);
function dec() external view returns (uint256);
function live() external view returns (uint256);
function cage() external;
function join(address, uint256) external;
function exit(address, uint256) external;
function setImplementation(address, uint256) external;
}
////// lib/dss-interfaces/src/dss/GemJoinManagedAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss-gem-joins/blob/master/src/join-managed.sol
interface GemJoinManagedAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function vat() external view returns (address);
function ilk() external view returns (bytes32);
function gem() external view returns (address);
function dec() external view returns (uint256);
function live() external view returns (uint256);
function cage() external;
function join(address, uint256) external;
function exit(address, address, uint256) external;
}
////// lib/dss-interfaces/src/dss/GetCdpsAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss-cdp-manager/blob/master/src/GetCdps.sol
interface GetCdpsAbstract {
function getCdpsAsc(address, address) external view returns (uint256[] memory, address[] memory, bytes32[] memory);
function getCdpsDesc(address, address) external view returns (uint256[] memory, address[] memory, bytes32[] memory);
}
////// lib/dss-interfaces/src/dss/IlkRegistryAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/ilk-registry
interface IlkRegistryAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function vat() external view returns (address);
function dog() external view returns (address);
function cat() external view returns (address);
function spot() external view returns (address);
function ilkData(bytes32) external view returns (
uint96, address, address, uint8, uint96, address, address, string memory, string memory
);
function ilks() external view returns (bytes32[] memory);
function ilks(uint) external view returns (bytes32);
function add(address) external;
function remove(bytes32) external;
function update(bytes32) external;
function removeAuth(bytes32) external;
function file(bytes32, address) external;
function file(bytes32, bytes32, address) external;
function file(bytes32, bytes32, uint256) external;
function file(bytes32, bytes32, string calldata) external;
function count() external view returns (uint256);
function list() external view returns (bytes32[] memory);
function list(uint256, uint256) external view returns (bytes32[] memory);
function get(uint256) external view returns (bytes32);
function info(bytes32) external view returns (
string memory, string memory, uint256, uint256, address, address, address, address
);
function pos(bytes32) external view returns (uint256);
function class(bytes32) external view returns (uint256);
function gem(bytes32) external view returns (address);
function pip(bytes32) external view returns (address);
function join(bytes32) external view returns (address);
function xlip(bytes32) external view returns (address);
function dec(bytes32) external view returns (uint256);
function symbol(bytes32) external view returns (string memory);
function name(bytes32) external view returns (string memory);
function put(bytes32, address, address, uint256, uint256, address, address, string calldata, string calldata) external;
}
////// lib/dss-interfaces/src/dss/JugAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/jug.sol
interface JugAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function ilks(bytes32) external view returns (uint256, uint256);
function vat() external view returns (address);
function vow() external view returns (address);
function base() external view returns (address);
function init(bytes32) external;
function file(bytes32, bytes32, uint256) external;
function file(bytes32, uint256) external;
function file(bytes32, address) external;
function drip(bytes32) external returns (uint256);
}
////// lib/dss-interfaces/src/dss/LPOsmAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/univ2-lp-oracle
interface LPOsmAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function stopped() external view returns (uint256);
function bud(address) external view returns (uint256);
function dec0() external view returns (uint8);
function dec1() external view returns (uint8);
function orb0() external view returns (address);
function orb1() external view returns (address);
function wat() external view returns (bytes32);
function hop() external view returns (uint32);
function src() external view returns (address);
function zzz() external view returns (uint64);
function change(address) external;
function step(uint256) external;
function stop() external;
function start() external;
function pass() external view returns (bool);
function poke() external;
function peek() external view returns (bytes32, bool);
function peep() external view returns (bytes32, bool);
function read() external view returns (bytes32);
function kiss(address) external;
function diss(address) external;
function kiss(address[] calldata) external;
function diss(address[] calldata) external;
function link(uint256, address) external;
}
////// lib/dss-interfaces/src/dss/LerpAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss-lerp/blob/master/src/Lerp.sol
interface LerpAbstract {
function target() external view returns (address);
function what() external view returns (bytes32);
function start() external view returns (uint256);
function end() external view returns (uint256);
function duration() external view returns (uint256);
function done() external view returns (bool);
function startTime() external view returns (uint256);
function tick() external returns (uint256);
function ilk() external view returns (bytes32);
}
////// lib/dss-interfaces/src/dss/LerpFactoryAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss-lerp/blob/master/src/LerpFactory.sol
interface LerpFactoryAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function lerps(bytes32) external view returns (address);
function active(uint256) external view returns (address);
function newLerp(bytes32, address, bytes32, uint256, uint256, uint256, uint256) external returns (address);
function newIlkLerp(bytes32, address, bytes32, bytes32, uint256, uint256, uint256, uint256) external returns (address);
function tall() external;
function count() external view returns (uint256);
function list() external view returns (address[] memory);
}
////// lib/dss-interfaces/src/dss/LinearDecreaseAbstract.sol
/// LinearDecreaseAbstract.sol -- Linear Decrease Interface
// Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC.
//
// 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 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity >=0.5.12; */
interface LinearDecreaseAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function tau() external view returns (uint256);
function file(bytes32,uint256) external;
function price(uint256,uint256) external view returns (uint256);
}
////// lib/dss-interfaces/src/dss/MedianAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/median
interface MedianAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function age() external view returns (uint32);
function wat() external view returns (bytes32);
function bar() external view returns (uint256);
function orcl(address) external view returns (uint256);
function bud(address) external view returns (uint256);
function slot(uint8) external view returns (address);
function read() external view returns (uint256);
function peek() external view returns (uint256, bool);
function lift(address[] calldata) external;
function drop(address[] calldata) external;
function setBar(uint256) external;
function kiss(address) external;
function diss(address) external;
function kiss(address[] calldata) external;
function diss(address[] calldata) external;
function poke(uint256[] calldata, uint256[] calldata, uint8[] calldata, bytes32[] calldata, bytes32[] calldata) external;
}
////// lib/dss-interfaces/src/dss/MkrAuthorityAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/mkr-authority/blob/master/src/MkrAuthority.sol
interface MkrAuthorityAbstract {
function root() external returns (address);
function setRoot(address) external;
function wards(address) external returns (uint256);
function rely(address) external;
function deny(address) external;
function canCall(address, address, bytes4) external returns (bool);
}
////// lib/dss-interfaces/src/dss/OsmAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/osm
interface OsmAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function stopped() external view returns (uint256);
function src() external view returns (address);
function hop() external view returns (uint16);
function zzz() external view returns (uint64);
function bud(address) external view returns (uint256);
function stop() external;
function start() external;
function change(address) external;
function step(uint16) external;
function void() external;
function pass() external view returns (bool);
function poke() external;
function peek() external view returns (bytes32, bool);
function peep() external view returns (bytes32, bool);
function read() external view returns (bytes32);
function kiss(address) external;
function diss(address) external;
function kiss(address[] calldata) external;
function diss(address[] calldata) external;
}
////// lib/dss-interfaces/src/dss/OsmMomAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/osm-mom
interface OsmMomAbstract {
function owner() external view returns (address);
function authority() external view returns (address);
function osms(bytes32) external view returns (address);
function setOsm(bytes32, address) external;
function setOwner(address) external;
function setAuthority(address) external;
function stop(bytes32) external;
}
////// lib/dss-interfaces/src/dss/PotAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/pot.sol
interface PotAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function pie(address) external view returns (uint256);
function Pie() external view returns (uint256);
function dsr() external view returns (uint256);
function chi() external view returns (uint256);
function vat() external view returns (address);
function vow() external view returns (address);
function rho() external view returns (uint256);
function live() external view returns (uint256);
function file(bytes32, uint256) external;
function file(bytes32, address) external;
function cage() external;
function drip() external returns (uint256);
function join(uint256) external;
function exit(uint256) external;
}
////// lib/dss-interfaces/src/dss/PotHelper.sol
/* pragma solidity >=0.5.12; */
/* import { PotAbstract } from "./PotAbstract.sol"; */
// https://github.com/makerdao/dss/blob/master/src/pot.sol
contract PotHelper {
PotAbstract pa;
constructor(address _pot) public {
pa = PotAbstract(_pot);
}
// https://github.com/makerdao/dss/blob/master/src/pot.sol#L79
uint256 constant ONE = 10 ** 27;
function _mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function _rmul(uint x, uint y) internal pure returns (uint z) {
z = _mul(x, y) / ONE;
}
function rpow(uint x, uint n, uint base) internal pure returns (uint z) {
assembly {
switch x case 0 {switch n case 0 {z := base} default {z := 0}}
default {
switch mod(n, 2) case 0 { z := base } default { z := x }
let half := div(base, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, base)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, base)
}
}
}
}
}
// View function for calculating value of chi iff drip() is called in the same block.
function drop() external view returns (uint256) {
if (block.timestamp == pa.rho()) return pa.chi();
return _rmul(rpow(pa.dsr(), block.timestamp - pa.rho(), ONE), pa.chi());
}
// Pass the Pot Abstract for additional operations
function pot() external view returns (PotAbstract) {
return pa;
}
}
////// lib/dss-interfaces/src/dss/PsmAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss-psm/blob/master/src/psm.sol
interface PsmAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function vat() external view returns (address);
function gemJoin() external view returns (address);
function dai() external view returns (address);
function daiJoin() external view returns (address);
function ilk() external view returns (bytes32);
function vow() external view returns (address);
function tin() external view returns (uint256);
function tout() external view returns (uint256);
function file(bytes32 what, uint256 data) external;
function hope(address) external;
function nope(address) external;
function sellGem(address usr, uint256 gemAmt) external;
function buyGem(address usr, uint256 gemAmt) external;
}
////// lib/dss-interfaces/src/dss/SpotAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/spot.sol
interface SpotAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function ilks(bytes32) external view returns (address, uint256);
function vat() external view returns (address);
function par() external view returns (uint256);
function live() external view returns (uint256);
function file(bytes32, bytes32, address) external;
function file(bytes32, uint256) external;
function file(bytes32, bytes32, uint256) external;
function poke(bytes32) external;
function cage() external;
}
////// lib/dss-interfaces/src/dss/StairstepExponentialDecreaseAbstract.sol
/// StairstepExponentialDecreaseAbstract.sol -- StairstepExponentialDecrease Interface
// Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC.
//
// 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 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity >=0.5.12; */
interface StairstepExponentialDecreaseAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function step() external view returns (uint256);
function cut() external view returns (uint256);
function file(bytes32,uint256) external;
function price(uint256,uint256) external view returns (uint256);
}
////// lib/dss-interfaces/src/dss/VatAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/vat.sol
interface VatAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function can(address, address) external view returns (uint256);
function hope(address) external;
function nope(address) external;
function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256);
function urns(bytes32, address) external view returns (uint256, uint256);
function gem(bytes32, address) external view returns (uint256);
function dai(address) external view returns (uint256);
function sin(address) external view returns (uint256);
function debt() external view returns (uint256);
function vice() external view returns (uint256);
function Line() external view returns (uint256);
function live() external view returns (uint256);
function init(bytes32) external;
function file(bytes32, uint256) external;
function file(bytes32, bytes32, uint256) external;
function cage() external;
function slip(bytes32, address, int256) external;
function flux(bytes32, address, address, uint256) external;
function move(address, address, uint256) external;
function frob(bytes32, address, address, address, int256, int256) external;
function fork(bytes32, address, address, int256, int256) external;
function grab(bytes32, address, address, address, int256, int256) external;
function heal(uint256) external;
function suck(address, address, uint256) external;
function fold(bytes32, address, int256) external;
}
////// lib/dss-interfaces/src/dss/VestAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss-vest/blob/master/src/DssVest.sol
interface VestAbstract {
function TWENTY_YEARS() external view returns (uint256);
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
function awards(uint256) external view returns (address, uint48, uint48, uint48, address, uint8, uint128, uint128);
function ids() external view returns (uint256);
function cap() external view returns (uint256);
function usr(uint256) external view returns (address);
function bgn(uint256) external view returns (uint256);
function clf(uint256) external view returns (uint256);
function fin(uint256) external view returns (uint256);
function mgr(uint256) external view returns (address);
function res(uint256) external view returns (uint256);
function tot(uint256) external view returns (uint256);
function rxd(uint256) external view returns (uint256);
function file(bytes32, uint256) external;
function create(address, uint256, uint256, uint256, uint256, address) external returns (uint256);
function vest(uint256) external;
function vest(uint256, uint256) external;
function accrued(uint256) external view returns (uint256);
function unpaid(uint256) external view returns (uint256);
function restrict(uint256) external;
function unrestrict(uint256) external;
function yank(uint256) external;
function yank(uint256, uint256) external;
function move(uint256, address) external;
function valid(uint256) external view returns (bool);
}
////// lib/dss-interfaces/src/dss/VowAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/dss/blob/master/src/vow.sol
interface VowAbstract {
function wards(address) external view returns (uint256);
function rely(address usr) external;
function deny(address usr) external;
function vat() external view returns (address);
function flapper() external view returns (address);
function flopper() external view returns (address);
function sin(uint256) external view returns (uint256);
function Sin() external view returns (uint256);
function Ash() external view returns (uint256);
function wait() external view returns (uint256);
function dump() external view returns (uint256);
function sump() external view returns (uint256);
function bump() external view returns (uint256);
function hump() external view returns (uint256);
function live() external view returns (uint256);
function file(bytes32, uint256) external;
function file(bytes32, address) external;
function fess(uint256) external;
function flog(uint256) external;
function heal(uint256) external;
function kiss(uint256) external;
function flop() external returns (uint256);
function flap() external returns (uint256);
function cage() external;
}
////// lib/dss-interfaces/src/sai/GemPitAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/sai/blob/master/src/pit.sol
interface GemPitAbstract {
function burn(address) external;
}
////// lib/dss-interfaces/src/sai/SaiMomAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/sai/blob/master/src/mom.sol
interface SaiMomAbstract {
function tub() external view returns (address);
function tap() external view returns (address);
function vox() external view returns (address);
function setCap(uint256) external;
function setMat(uint256) external;
function setTax(uint256) external;
function setFee(uint256) external;
function setAxe(uint256) external;
function setTubGap(uint256) external;
function setPip(address) external;
function setPep(address) external;
function setVox(address) external;
function setTapGap(uint256) external;
function setWay(uint256) external;
function setHow(uint256) external;
function authority() external view returns (address);
function owner() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
}
////// lib/dss-interfaces/src/sai/SaiTapAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/sai/blob/master/src/tap.sol
interface SaiTapAbstract {
function sai() external view returns (address);
function sin() external view returns (address);
function skr() external view returns (address);
function vox() external view returns (address);
function tub() external view returns (address);
function gap() external view returns (uint256);
function off() external view returns (bool);
function fix() external view returns (uint256);
function joy() external view returns (uint256);
function woe() external view returns (uint256);
function fog() external view returns (uint256);
function mold(bytes32, uint256) external;
function heal() external;
function s2s() external returns (uint256);
function bid(uint256) external returns (uint256);
function ask(uint256) external returns (uint256);
function bust(uint256) external;
function boom(uint256) external;
function cage(uint256) external;
function cash(uint256) external;
function mock(uint256) external;
function vent() external;
function authority() external view returns (address);
function owner() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
}
////// lib/dss-interfaces/src/sai/SaiTopAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/sai/blob/master/src/top.sol
interface SaiTopAbstract {
function vox() external view returns (address);
function tub() external view returns (address);
function tap() external view returns (address);
function sai() external view returns (address);
function sin() external view returns (address);
function skr() external view returns (address);
function gem() external view returns (address);
function fix() external view returns (uint256);
function fit() external view returns (uint256);
function caged() external view returns (uint256);
function cooldown() external view returns (uint256);
function era() external view returns (uint256);
function cage() external;
function flow() external;
function setCooldown(uint256) external;
function authority() external view returns (address);
function owner() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
}
////// lib/dss-interfaces/src/sai/SaiTubAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/sai/blob/master/src/tub.sol
interface SaiTubAbstract {
function sai() external view returns (address);
function sin() external view returns (address);
function skr() external view returns (address);
function gem() external view returns (address);
function gov() external view returns (address);
function vox() external view returns (address);
function pip() external view returns (address);
function pep() external view returns (address);
function tap() external view returns (address);
function pit() external view returns (address);
function axe() external view returns (uint256);
function cap() external view returns (uint256);
function mat() external view returns (uint256);
function tax() external view returns (uint256);
function fee() external view returns (uint256);
function gap() external view returns (uint256);
function off() external view returns (bool);
function out() external view returns (bool);
function fit() external view returns (uint256);
function rho() external view returns (uint256);
function rum() external view returns (uint256);
function cupi() external view returns (uint256);
function cups(bytes32) external view returns (address, uint256, uint256, uint256);
function lad(bytes32) external view returns (address);
function ink(bytes32) external view returns (address);
function tab(bytes32) external view returns (uint256);
function rap(bytes32) external returns (uint256);
function din() external returns (uint256);
function air() external view returns (uint256);
function pie() external view returns (uint256);
function era() external view returns (uint256);
function mold(bytes32, uint256) external;
function setPip(address) external;
function setPep(address) external;
function setVox(address) external;
function turn(address) external;
function per() external view returns (uint256);
function ask(uint256) external view returns (uint256);
function bid(uint256) external view returns (uint256);
function join(uint256) external;
function exit(uint256) external;
function chi() external returns (uint256);
function rhi() external returns (uint256);
function drip() external;
function tag() external view returns (uint256);
function safe(bytes32) external returns (bool);
function open() external returns (bytes32);
function give(bytes32, address) external;
function lock(bytes32, uint256) external;
function free(bytes32, uint256) external;
function draw(bytes32, uint256) external;
function wipe(bytes32, uint256) external;
function shut(bytes32) external;
function bite(bytes32) external;
function cage(uint256, uint256) external;
function flow() external;
function authority() external view returns (address);
function owner() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
}
////// lib/dss-interfaces/src/sai/SaiVoxAbstract.sol
/* pragma solidity >=0.5.12; */
// https://github.com/makerdao/sai/blob/master/src/vox.sol
interface SaiVoxAbstract {
function fix() external view returns (uint256);
function how() external view returns (uint256);
function tau() external view returns (uint256);
function era() external view returns (uint256);
function mold(bytes32, uint256) external;
function par() external returns (uint256);
function way() external returns (uint256);
function tell(uint256) external;
function tune(uint256) external;
function prod() external;
function authority() external view returns (address);
function owner() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
}
////// lib/dss-interfaces/src/utils/WardsAbstract.sol
/* pragma solidity >=0.5.12; */
interface WardsAbstract {
function wards(address) external view returns (uint256);
function rely(address) external;
function deny(address) external;
}
////// lib/dss-interfaces/src/Interfaces.sol
/* pragma solidity >=0.5.12; */
/* import { GemAbstract } from "./ERC/GemAbstract.sol"; */
/* import { DSAuthorityAbstract, DSAuthAbstract } from "./dapp/DSAuthorityAbstract.sol"; */
/* import { DSChiefAbstract } from "./dapp/DSChiefAbstract.sol"; */
/* import { DSPauseAbstract } from "./dapp/DSPauseAbstract.sol"; */
/* import { DSPauseProxyAbstract } from "./dapp/DSPauseProxyAbstract.sol"; */
/* import { DSRolesAbstract } from "./dapp/DSRolesAbstract.sol"; */
/* import { DSSpellAbstract } from "./dapp/DSSpellAbstract.sol"; */
/* import { DSRuneAbstract } from "./dapp/DSRuneAbstract.sol"; */
/* import { DSThingAbstract } from "./dapp/DSThingAbstract.sol"; */
/* import { DSTokenAbstract } from "./dapp/DSTokenAbstract.sol"; */
/* import { DSValueAbstract } from "./dapp/DSValueAbstract.sol"; */
/* import { AuthGemJoinAbstract } from "./dss/AuthGemJoinAbstract.sol"; */
/* import { CatAbstract } from "./dss/CatAbstract.sol"; */
/* import { ChainlogAbstract } from "./dss/ChainlogAbstract.sol"; */
/* import { ChainlogHelper } from "./dss/ChainlogAbstract.sol"; */
/* import { ClipAbstract } from "./dss/ClipAbstract.sol"; */
/* import { ClipperMomAbstract } from "./dss/ClipperMomAbstract.sol"; */
/* import { DaiAbstract } from "./dss/DaiAbstract.sol"; */
/* import { DaiJoinAbstract } from "./dss/DaiJoinAbstract.sol"; */
/* import { DogAbstract } from "./dss/DogAbstract.sol"; */
/* import { DssAutoLineAbstract } from "./dss/DssAutoLineAbstract.sol"; */
/* import { DssCdpManagerAbstract } from "./dss/DssCdpManager.sol"; */
/* import { EndAbstract } from "./dss/EndAbstract.sol"; */
/* import { ESMAbstract } from "./dss/ESMAbstract.sol"; */
/* import { ETHJoinAbstract } from "./dss/ETHJoinAbstract.sol"; */
/* import { ExponentialDecreaseAbstract } from "./dss/ExponentialDecreaseAbstract.sol"; */
/* import { FaucetAbstract } from "./dss/FaucetAbstract.sol"; */
/* import { FlapAbstract } from "./dss/FlapAbstract.sol"; */
/* import { FlashAbstract } from "./dss/FlashAbstract.sol"; */
/* import { FlipAbstract } from "./dss/FlipAbstract.sol"; */
/* import { FlipperMomAbstract } from "./dss/FlipperMomAbstract.sol"; */
/* import { FlopAbstract } from "./dss/FlopAbstract.sol"; */
/* import { GemJoinAbstract } from "./dss/GemJoinAbstract.sol"; */
/* import { GemJoinImplementationAbstract } from "./dss/GemJoinImplementationAbstract.sol"; */
/* import { GemJoinManagedAbstract } from "./dss/GemJoinManagedAbstract.sol"; */
/* import { GetCdpsAbstract } from "./dss/GetCdpsAbstract.sol"; */
/* import { IlkRegistryAbstract } from "./dss/IlkRegistryAbstract.sol"; */
/* import { JugAbstract } from "./dss/JugAbstract.sol"; */
/* import { LerpAbstract } from "./dss/LerpAbstract.sol"; */
/* import { LerpFactoryAbstract } from "./dss/LerpFactoryAbstract.sol"; */
/* import { LinearDecreaseAbstract } from "./dss/LinearDecreaseAbstract.sol"; */
/* import { LPOsmAbstract } from "./dss/LPOsmAbstract.sol"; */
/* import { MkrAuthorityAbstract } from "./dss/MkrAuthorityAbstract.sol"; */
/* import { MedianAbstract } from "./dss/MedianAbstract.sol"; */
/* import { OsmAbstract } from "./dss/OsmAbstract.sol"; */
/* import { OsmMomAbstract } from "./dss/OsmMomAbstract.sol"; */
/* import { PotAbstract } from "./dss/PotAbstract.sol"; */
/* import { PotHelper } from "./dss/PotHelper.sol"; */
/* import { PsmAbstract } from "./dss/PsmAbstract.sol"; */
/* import { SpotAbstract } from "./dss/SpotAbstract.sol"; */
/* import { StairstepExponentialDecreaseAbstract } from "./dss/StairstepExponentialDecreaseAbstract.sol"; */
/* import { VatAbstract } from "./dss/VatAbstract.sol"; */
/* import { VestAbstract } from "./dss/VestAbstract.sol"; */
/* import { VowAbstract } from "./dss/VowAbstract.sol"; */
/* import { GemPitAbstract } from "./sai/GemPitAbstract.sol"; */
/* import { SaiMomAbstract } from "./sai/SaiMomAbstract.sol"; */
/* import { SaiTapAbstract } from "./sai/SaiTapAbstract.sol"; */
/* import { SaiTopAbstract } from "./sai/SaiTopAbstract.sol"; */
/* import { SaiTubAbstract } from "./sai/SaiTubAbstract.sol"; */
/* import { SaiVoxAbstract } from "./sai/SaiVoxAbstract.sol"; */
// Partial DSS Abstracts
/* import { WardsAbstract } from "./utils/WardsAbstract.sol"; */
////// src/FlapperMassBid.sol
// Copyright (C) 2021 Sam MacPherson (hexonaut)
//
// 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 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity 0.8.11; */
/* import {
VowAbstract,
FlapAbstract,
DSTokenAbstract,
DaiJoinAbstract,
DaiAbstract,
VatAbstract
} from "dss-interfaces/Interfaces.sol"; */
contract FlapperMassBid {
struct AuctionCandidate {
uint256 index;
uint256 auction;
uint256 bid;
}
uint256 constant WAD = 10 ** 18;
uint256 constant RAY = 10 ** 27;
address public immutable owner;
VowAbstract public immutable vow;
FlapAbstract public immutable flap;
DaiJoinAbstract public immutable daiJoin;
DaiAbstract public immutable dai;
VatAbstract public immutable vat;
DSTokenAbstract public immutable mkr;
constructor(address _owner, address _vow, address _daiJoin) {
owner = _owner;
vow = VowAbstract(_vow);
flap = FlapAbstract(vow.flapper());
daiJoin = DaiJoinAbstract(_daiJoin);
dai = DaiAbstract(daiJoin.dai());
vat = VatAbstract(daiJoin.vat());
mkr = DSTokenAbstract(flap.gem());
// Setup permissions
mkr.approve(address(flap), type(uint256).max);
vat.hope(address(daiJoin));
}
function findAuctions(
uint256 startAuctionIndex,
uint256 endAuctionIndex,
uint256 maxAuctionsToBid,
uint256 mkrBidInWads
) external view returns (uint256 numAuctions, bytes memory data) {
require(endAuctionIndex >= startAuctionIndex, "start-must-be-before-end");
require(maxAuctionsToBid > 0, "at-least-one-auction");
require(mkrBidInWads > 0, "need-to-bid-something");
require(mkr.balanceOf(owner) >= mkrBidInWads * maxAuctionsToBid, "not-enough-mkr-in-your-wallet");
require(mkr.allowance(owner, address(this)) >= mkrBidInWads * maxAuctionsToBid, "not-enough-mkr-allowance");
uint256 beg = flap.beg();
uint256 i;
AuctionCandidate[] memory candidates = new AuctionCandidate[](maxAuctionsToBid);
for (i = startAuctionIndex; i <= endAuctionIndex; i++) {
(uint256 bid,, address guy, uint48 tic, uint48 end) = flap.bids(i);
if (guy == address(0)) continue; // Auction doesn't exist
if (tic <= block.timestamp && tic != 0) continue; // Auction finished
if (end <= block.timestamp) continue; // Auction end
if (mkrBidInWads <= bid) continue; // Bid not high enough
if (mkrBidInWads * WAD < beg * bid) continue; // Bid increase is not above beg
if (numAuctions < maxAuctionsToBid) {
// Always append if not full
candidates[numAuctions] = AuctionCandidate(numAuctions, i, bid);
numAuctions++;
} else {
// Potentially add to candidates if it's smaller amount
// First find the largest candidate to replace
AuctionCandidate memory largestBidCandidate;
for (uint256 o = 0; o < maxAuctionsToBid; o++) {
AuctionCandidate memory candidate = candidates[o];
if (candidate.bid > largestBidCandidate.bid) {
largestBidCandidate = candidate;
}
}
// Replace it if the current bid is smaller
if (bid < largestBidCandidate.bid) {
candidates[largestBidCandidate.index] = AuctionCandidate(largestBidCandidate.index, i, bid);
}
}
}
uint256[] memory auctions = new uint256[](numAuctions);
for (i = 0; i < numAuctions; i++) {
auctions[i] = candidates[i].auction;
}
data = abi.encode(mkrBidInWads, auctions); // Encode for easier copy+paste
}
function execute (bytes calldata data) external {
require(msg.sender == owner, "only-owner");
(uint256 bid, uint256[] memory auctions) = abi.decode(data, (uint256, uint256[]));
uint256 lot = vow.bump();
// At most you will need bid * numAuctions MKR
mkr.transferFrom(owner, address(this), bid * auctions.length);
for (uint256 i = 0; i < auctions.length; i++) {
try flap.tend(auctions[i], lot, bid) {} catch {
// Carry on if one of the bids fails
}
}
// Transfer any remaining MKR back out
mkr.transfer(owner, mkr.balanceOf(address(this)));
}
function extractVatDAI() external {
require(msg.sender == owner, "only-owner");
// Pull DAI out of vat (if any)
daiJoin.exit(owner, vat.dai(address(this)) / RAY);
}
function extractMKR() external {
require(msg.sender == owner, "only-owner");
// Pull MKR out of here (it will show up if outbid)
mkr.transfer(owner, mkr.balanceOf(address(this)));
}
// This should never have DAI in it, but let's just be safe
function extractDAI() external {
require(msg.sender == owner, "only-owner");
// Pull MKR out of here (it will show up if outbid)
dai.transfer(owner, dai.balanceOf(address(this)));
}
}
contract FlapperMassBidFactory {
address public immutable vow;
address public immutable daiJoin;
constructor(address _vow, address _daiJoin) {
vow = _vow;
daiJoin = _daiJoin;
}
function create() external returns (FlapperMassBid) {
return new FlapperMassBid(msg.sender, vow, daiJoin);
}
} | https:github.com/dapphub/ds-auth | interface DSAuthorityAbstract {
function canCall(address, address, bytes4) external view returns (bool);
}
| 2,203,199 |
./partial_match/4/0x9d703DceE59C627a47098Ad03bC786A97333E36F/sources/animalMain.sol | TO DO使用亂數來產生DNA, 星級, 動物種類動手玩創意,可以限制每次建立動物需要花費多少ETH | function createAnimal() public payable {
bytes32 dna = bytes32(random());
uint star = uint(random())%100;
uint roletype= (uint(random()) % 4)+1;
require(msg.value == 100 wei );
uint id = animals.push(animal(dna, uint8(star), uint8(roletype))) - 1;
animalToOwner[id] = msg.sender;
ownerAnimalCount[msg.sender]++;
if(star == 0) {star = 5; }
else if (star <= 20) {star =4; }
else if (star <= 30) {star =3; }
else if (star <= 50) {star =2; }
else{star = 1;}
}
| 8,567,820 |
./full_match/73799/0x201d20e1c28194BbF970A79C24aC43ddcbBB6f7d/sources/contracts/facets/ProofManagerFacet.sol | _claimProofFor - Claims a green certificate on behalf of an owner This function reverts if the claimedProof is revoked This function reverts if the claimed amount is superior than the claimer balance On successful claim, this function emits the `ProofClaimed` event certificateID ID of the certificate to claim owner Address of the certificate owner amount Amount of energy to claim/ | function _claimProofFor(
uint256 certificateID,
address owner,
uint256 amount
) private {
uint256 ownedBalance = _balanceOf(owner, certificateID);
LibProofManager.checkClaimableProof(certificateID, owner, amount, ownedBalance);
LibIssuer.registerClaimedProof(certificateID, owner, amount);
_burn(owner, certificateID, amount);
emit ProofClaimed(certificateID, owner, block.timestamp, amount);
| 16,363,268 |
pragma solidity ^0.5.0;
/**
* The TokenFarm contract does this and that...
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function decimals() public view returns (uint8);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract IERC20Mintable {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function decimals() public view returns (uint8);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function mint(address _to,uint256 _value) public;
function burn(uint256 _value) public;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract TokenFarm {
using SafeMath for uint256;
modifier onlyOwner {
require(
msg.sender == owner,
"Only owner can call this function."
);
_;
}
modifier onlyModerators {
require(
Admins[msg.sender]==true,
"Only owner can call this function."
);
_;
}
// These get stored on the blockchain
// Owner is the person who deployes the contract
address public owner;
string public name = "Dapp Token Farm";
IERC20Mintable public dappToken;
struct staker {
uint256 id;
mapping(address=> uint256) balance;
mapping(address=> uint256) timestamp;
mapping(address=> uint256) timefeestartstamp;
}
struct rate {
uint256 rate;
bool exists;
}
// people that have ever staked
mapping(address => uint256) public totalStaked;
address[] private tokenPools;
mapping(address => staker) stakers;
mapping(address => rate) public RatePerCoin;
mapping (address=>bool) Admins;
uint256 public minimumDaysLockup=3;
uint256 public penaltyFee=10;
// This is passing in addresses, I can find them manually
constructor(IERC20Mintable _dapptoken, address _spiritclashtoken)
public
{
dappToken = _dapptoken;
owner = msg.sender;
Admins[msg.sender]=true;
setCoinRate(_spiritclashtoken,80000);
}
// 1. Stakes Tokens(Deposit)
function stakeTokens(uint256 _amount,IERC20 token) external { // remove payable
// Require amount greater than 0
require(RatePerCoin[address(token)].exists==true,"token doesnt have a rate");
require(_amount > 0, "amount cannot be 0");
if (stakers[msg.sender].balance[address(token)] > 0) {
claimToken(address(token));
}
// Transfer Mock Dai tokens to this contract for staking
token.transferFrom(msg.sender, address(this), _amount);
// Update staking balance
stakers[msg.sender].balance[address(token)] = stakers[msg.sender].balance[address(token)].add( _amount);
totalStaked[address(token)] = totalStaked[address(token)].add( _amount);
stakers[msg.sender].timestamp[address(token)] = block.timestamp;
stakers[msg.sender].timefeestartstamp[address(token)] = block.timestamp;
}
// Unstaking Tokens(Withdraw)
function unstakeToken(IERC20 token) external {
// Fetch staking balance
uint256 balance = stakers[msg.sender].balance[address(token)];
// Require amount greater then 0
require(balance > 0, "staking balance cannot be 0");
// Check to see if the sender has waited longer then 3 days before withdrawl
if( (block.timestamp.sub(stakers[msg.sender].timefeestartstamp[address(token)])) < (minimumDaysLockup*24*60*60)){
uint256 fee = (balance.mul(100).div(penaltyFee)).div(100);
token.transfer(owner, fee);
balance = balance.sub(fee);
}
claimTokens();
// Reset staking balance
stakers[msg.sender].balance[address(token)] = 0;
totalStaked[address(token)] = totalStaked[address(token)].sub(balance);
//transfer unstaked coins
token.transfer(msg.sender, balance);
}
function unstakeTokens() external{ // this is fine
claimTokens();
for (uint i=0; i< tokenPools.length; i++){
uint256 balance = stakers[msg.sender].balance[tokenPools[i]];
if(balance > 0){
// Check to see if the sender has waited longer then 3 days before withdrawl
totalStaked[tokenPools[i]] = totalStaked[tokenPools[i]].sub(balance);
stakers[msg.sender].balance[tokenPools[i]] = 0;
if((block.timestamp.sub(stakers[msg.sender].timefeestartstamp[tokenPools[i]])) < (minimumDaysLockup*24*60*60)){
uint256 fee = (balance.mul(100).div(penaltyFee)).div(100);
balance = balance.sub(fee);
IERC20(tokenPools[i]).transfer(owner, fee);
}
IERC20(tokenPools[i]).transfer(msg.sender, balance);
}
}
}
function earned(address token) public view returns(uint256){ // this is fine
uint256 multiplier =100000000;
return (stakers[msg.sender].balance[token]*
(RatePerCoin[token].rate) * //coin earn rate in percentage so should be divided by 100
(
(stakers[msg.sender].balance[token]*multiplier)/(totalStaked[token]) //calculate token share percentage
)/(365*24*60*60)// 31 536 000
///seconds per year
*(
block.timestamp.sub(stakers[msg.sender].timestamp[token]) // get time
)
)/multiplier/10;
}
function claimTokens() public { // This function looks good to me.
uint256 rewardbal=0;
for (uint i=0; i< tokenPools.length; i++){
address token = tokenPools[i];
if(stakers[msg.sender].balance[token]>0){
uint256 earnings = earned(token);
stakers[msg.sender].timestamp[token]=block.timestamp;
rewardbal= rewardbal.add(earnings);
}
}
IERC20Mintable(dappToken).mint(msg.sender, rewardbal);
}
function claimToken(address token) public { // For sure an issue
require(stakers[msg.sender].balance[token]>0,"you have no balance and cant claim");
uint256 earnings = earned(token);
stakers[msg.sender].timestamp[token]=block.timestamp;
IERC20Mintable(dappToken).mint(msg.sender, earnings);
}
function setMinimumLockup(uint256 _days) external onlyModerators {
minimumDaysLockup =_days;
}
function setPenaltyFee(uint256 _fee) external onlyModerators {
penaltyFee =_fee;
}
function transferOwnership(address _newOwner) external onlyOwner{
owner=_newOwner;
}
function setCoinRate(address coin,uint256 Rate) public onlyModerators {
RatePerCoin[coin].rate =Rate;
if(RatePerCoin[coin].exists == false){
tokenPools.push(coin);
RatePerCoin[coin].exists = true;
}
}
function setAdmin(address addy,bool value) external onlyOwner{
Admins[addy]= value;
}
function stakingBalance(address token) external view returns(uint256) {
return stakers[msg.sender].balance[token];
}
}
pragma solidity ^0.5.0;
contract ClashPay {
using SafeMath for uint256;
string public name = "Clash Pay";
string public symbol = "SCP";
uint256 public totalSupply = 10000000000000000000;
uint8 public decimals = 18;
address public owner;
address public Tokenfarm;
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Burn(
address indexed burner,
uint256 value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
constructor() public {
balanceOf[msg.sender] = totalSupply;
owner= msg.sender;
}
function setContract(address _contract) external{
require(msg.sender==owner,"must be owner");
Tokenfarm=_contract;
}
function transfer(address _to, uint256 _value) external returns (bool success) {
require(address(0)!= _to,"to burn tokens use the burn function");
balanceOf[msg.sender] =balanceOf[msg.sender].sub( _value);
balanceOf[_to] = balanceOf[_to].add( _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) external returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success) {
require(address(0)!= _to,"to burn tokens use the burn function");
balanceOf[_from] = balanceOf[_from].sub( _value); // msg.sender => _from
balanceOf[_to] = balanceOf[_to].add( _value);
allowance[_from][msg.sender] =allowance[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function mint(address _to,uint256 _value) public {
require(msg.sender==Tokenfarm,"only Tokenfarm contract can mint tokens");
totalSupply= totalSupply.add( _value);
balanceOf[_to]=balanceOf[_to].add(_value);
emit Transfer(address(0),msg.sender,_value);
}
function burn(uint256 _value) public{
balanceOf[msg.sender] =balanceOf[msg.sender].sub( _value);
emit Burn(msg.sender,_value);
emit Transfer(msg.sender,address(0),_value);
}
function transferOwnership(address _newOwner) external{
require(msg.sender==owner,"only the owner an call this function");
owner=_newOwner;
}
} | Fetch staking balance Require amount greater then 0 Check to see if the sender has waited longer then 3 days before withdrawl | function unstakeToken(IERC20 token) external {
uint256 balance = stakers[msg.sender].balance[address(token)];
require(balance > 0, "staking balance cannot be 0");
if( (block.timestamp.sub(stakers[msg.sender].timefeestartstamp[address(token)])) < (minimumDaysLockup*24*60*60)){
uint256 fee = (balance.mul(100).div(penaltyFee)).div(100);
token.transfer(owner, fee);
balance = balance.sub(fee);
}
claimTokens();
totalStaked[address(token)] = totalStaked[address(token)].sub(balance);
stakers[msg.sender].balance[address(token)] = 0;
token.transfer(msg.sender, balance);
}
| 6,871,038 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
import "../test.sol";
import "../../utils/SparseMerkleProof.sol";
contract SparseMerkleProofTest is DSTest {
// └─ 609cb3db293942026cbe8a4af05e7c3bf84d5d0ddd3e7992cba7679672a7320b
// ├─ fce70162d9cd6f7eaa27bd32c59b918b73504d82ce1857aee333bbbbf3047ed8
// │ ├─ 2156125536ad8579550f90b9ce42bc89e1b0afe53429e7d2b72812cc9ed21fbf
// │ └─ e8fdeb54f7c1e6c5a2bbf26f95ca5b182e13540419623b7b32f843b7124c7d2f
// └─ d8ac990c2064ff16b14142fb8eef4b6158814f90f718da31a21a28ff06ed3aaa
// ├─ 1218485dabb222fb1e7703a88737abbc3f37cb6c8601f6b07d775ddba17ce393
// └─ aee3dbe89996e687f3374b5325eda4687bfe27401b5ce2d9b225ab0cb209e562
function test_multi_verify() public {
bytes32 root = hex"609cb3db293942026cbe8a4af05e7c3bf84d5d0ddd3e7992cba7679672a7320b";
uint depth = 2;
bytes32 indices = hex"0301";
bytes32[] memory leaves = new bytes32[](2);
leaves[0] = hex"aee3dbe89996e687f3374b5325eda4687bfe27401b5ce2d9b225ab0cb209e562";
leaves[1] = hex"e8fdeb54f7c1e6c5a2bbf26f95ca5b182e13540419623b7b32f843b7124c7d2f";
bytes32[] memory decommitments = new bytes32[](2);
decommitments[0] = hex"1218485dabb222fb1e7703a88737abbc3f37cb6c8601f6b07d775ddba17ce393";
decommitments[1] = hex"2156125536ad8579550f90b9ce42bc89e1b0afe53429e7d2b72812cc9ed21fbf";
assertTrue(SparseMerkleProof.multiVerify(
root,
depth,
indices,
leaves,
decommitments
));
}
function testFail_multi_verify() public pure {
bytes32 root = hex"609cb3db293942026cbe8a4af05e7c3bf84d5d0ddd3e7992cba7679672a7320b";
uint depth = 2;
bytes32 indices = hex"0103";
bytes32[] memory leaves = new bytes32[](2);
leaves[0] = hex"e8fdeb54f7c1e6c5a2bbf26f95ca5b182e13540419623b7b32f843b7124c7d2f";
leaves[1] = hex"aee3dbe89996e687f3374b5325eda4687bfe27401b5ce2d9b225ab0cb209e562";
bytes32[] memory decommitments = new bytes32[](2);
decommitments[0] = hex"2156125536ad8579550f90b9ce42bc89e1b0afe53429e7d2b72812cc9ed21fbf";
decommitments[1] = hex"1218485dabb222fb1e7703a88737abbc3f37cb6c8601f6b07d775ddba17ce393";
SparseMerkleProof.multiVerify(
root,
depth,
indices,
leaves,
decommitments
);
}
// └─ ad4e8946ee8f8a4b98c6ece5d271d842abc752aa6b3a133efb44e2c13dd5a635
// ├─ 777611620e9efc9152fbfdf25b0eb7cb3876c51ce3630e77bb4204e7001252fb
// │ ├─ 950a019d53380dd2d4e240aaace158b09aac75689325fbdb4994748a9ce04c89
// │ └─ 3ad9e2f40f14c1834af2848ff5d8b568ffb5aec4ea137dbcd69411d5a5b3082c
// └─ 0fdef50f4e46e1db97d092c03e160fd45d6fd9bde3424790c1c5fe140bb93850
// └─ 0fdef50f4e46e1db97d092c03e160fd45d6fd9bde3424790c1c5fe140bb93850
function test_single_verify() public {
bytes32 root = hex"ad4e8946ee8f8a4b98c6ece5d271d842abc752aa6b3a133efb44e2c13dd5a635";
bytes32 leaf = hex"950a019d53380dd2d4e240aaace158b09aac75689325fbdb4994748a9ce04c89";
uint pos = 0;
bytes32[] memory proof = new bytes32[](2);
proof[0] = hex"3ad9e2f40f14c1834af2848ff5d8b568ffb5aec4ea137dbcd69411d5a5b3082c";
proof[1] = hex"0fdef50f4e46e1db97d092c03e160fd45d6fd9bde3424790c1c5fe140bb93850";
assertTrue(SparseMerkleProof.singleVerify(
root,
leaf,
pos,
proof
));
}
function testFail_single_verify() public {
bytes32 root = hex"ad4e8946ee8f8a4b98c6ece5d271d842abc752aa6b3a133efb44e2c13dd5a635";
bytes32 leaf = hex"950a019d53380dd2d4e240aaace158b09aac75689325fbdb4994748a9ce04c89";
uint pos = 1;
bytes32[] memory proof = new bytes32[](2);
proof[0] = hex"3ad9e2f40f14c1834af2848ff5d8b568ffb5aec4ea137dbcd69411d5a5b3082c";
proof[1] = hex"0fdef50f4e46e1db97d092c03e160fd45d6fd9bde3424790c1c5fe140bb93850";
assertTrue(SparseMerkleProof.singleVerify(
root,
leaf,
pos,
proof
));
}
}
| └─ ad4e8946ee8f8a4b98c6ece5d271d842abc752aa6b3a133efb44e2c13dd5a635 ├─ 777611620e9efc9152fbfdf25b0eb7cb3876c51ce3630e77bb4204e7001252fb │ ├─ 950a019d53380dd2d4e240aaace158b09aac75689325fbdb4994748a9ce04c89 │ └─ 3ad9e2f40f14c1834af2848ff5d8b568ffb5aec4ea137dbcd69411d5a5b3082c └─ 0fdef50f4e46e1db97d092c03e160fd45d6fd9bde3424790c1c5fe140bb93850 └─ 0fdef50f4e46e1db97d092c03e160fd45d6fd9bde3424790c1c5fe140bb93850 | function test_single_verify() public {
bytes32 root = hex"ad4e8946ee8f8a4b98c6ece5d271d842abc752aa6b3a133efb44e2c13dd5a635";
bytes32 leaf = hex"950a019d53380dd2d4e240aaace158b09aac75689325fbdb4994748a9ce04c89";
uint pos = 0;
bytes32[] memory proof = new bytes32[](2);
proof[0] = hex"3ad9e2f40f14c1834af2848ff5d8b568ffb5aec4ea137dbcd69411d5a5b3082c";
proof[1] = hex"0fdef50f4e46e1db97d092c03e160fd45d6fd9bde3424790c1c5fe140bb93850";
assertTrue(SparseMerkleProof.singleVerify(
root,
leaf,
pos,
proof
));
}
| 1,060,923 |
./full_match/1/0x5d131Fc9a7692B0168dFba6E26F24c7221671d3b/sources/contracts/erc/1155/ERC1155.sol | ERC1155Metadata functions/ | function _currentTokenId() internal virtual returns (uint256) {
return _currentId;
}
| 17,089,523 |
./full_match/4/0xB4b58210DC03c1A29021B296D80E17aD46427393/sources/contracts/base/ERC721.sol | Safely mints `tokenId`, transfers it to `to`, and emits two log events - 1. Credits the `minter` with the mint. 2. Shows transfer from the `minter` 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 creator,
address to,
uint256 tokenId
) internal virtual {
_safeMint(creator, to, tokenId, '');
}
| 769,874 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been 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());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// 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 "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending 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 payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./interfaces/IUniswapV3CrossPoolOracle.sol";
import "./interfaces/IGStakingVault.sol";
import "./mock/Mintable.sol";
import "./interfaces/INonfungiblePositionManager.sol";
import "./interfaces/IUniswapPoolV3.sol";
import "./interfaces/IUniswapV3Factory.sol";
import "./libs/SqrtPriceMath.sol";
import "./libs/LiquidityMath.sol";
import "./libs/TickMath.sol";
contract GStakingManager is AccessControl, ReentrancyGuard {
using SafeERC20 for IERC20;
uint64 private constant ACCUMULATED_MULTIPLIER = 1e12;
// keccak256("BIG_GUARDIAN_ROLE")
bytes32 public constant BIG_GUARDIAN_ROLE = 0x05c653944982f4fec5b037dad255d4ecd85c5b85ea2ec7654def404ae5f686ec;
// keccak256("GUARDIAN_ROLE")
bytes32 public constant GUARDIAN_ROLE = 0x55435dd261a4b9b3364963f7738a7a662ad9c84396d64be3365284bb7f0a5041;
// keccak256("MINTER_ROLE")
bytes32 public constant MINTER_ROLE = 0x9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6;
uint256 public constant USDC_THRESHOLD = 1000 * 10**6;
uint256 public constant SILVER_PIVOT = 50 days;
uint256 public constant GOLD_PIVOT = 100 days;
uint256 public constant MAX_FAUCET = 50;
uint256 public constant PERCENT = 10000;
// Reward of each user.
struct RewardInfo {
mapping(StakeType => uint256) rewardDebt; // Reward debt. See explanation below.
uint256 pendingReward; // Reward but not harvest
//
// pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 rewardToken;
mapping(StakeType => uint256) totalReward;
uint256 openTime;
uint256 closeTime;
mapping(StakeType => uint256) lastRewardSecond; // Last block number that rewards distribution occurs.
mapping(StakeType => uint256) accRewardPerShare; // Accumulated rewards per share, times 1e12. See below.
uint128 chainId;
PoolType poolType;
}
struct StakeInfo {
//for gpool
uint256 amount;
uint256 startStake; // start stake time
// for nft
uint256 nftInGpoolAmount;
}
struct SetTierParam {
address account;
Tier tier;
}
struct SetDateParam {
address account;
uint256 time;
}
struct LockedReward {
address rewardToken;
uint256 amount;
}
struct NFTInfo {
address pool;
address token0;
address token1;
int24 tickLower;
int24 tickUpper;
uint128 liquidity;
uint256 amount0;
uint256 amount1;
}
enum Tier {
NORANK,
BRONZE,
SILVER,
GOLD
}
enum PoolType {
CLAIMABLE,
REWARD_CALC
}
enum StakeType {
GPOOL,
NFT
}
// locking Amount if withdraw earlier
mapping(uint256 => mapping(address => LockedReward)) public lockingAmounts;
mapping(address => bool) public hadStake;
mapping(address => StakeInfo) public stakeInfo;
// Info of each pool reward
mapping(uint256 => mapping(address => RewardInfo)) public rewardInfo;
// Classify pools into CLAIMABLE AND REWARD_CALC
mapping(PoolType => uint256[]) public poolTypes;
//when you requestTokens address and blocktime+1 day is saved in Time Lock
mapping(address => uint256) public lockTime;
//nft record
//address user => tokenId => value.
mapping(address => mapping(uint256 => uint256)) public nftRecords;
PoolInfo[] public poolInfo;
uint256 public totalGpoolStaked;
uint256 public totalNFTStaked; // calculate by gpool
uint32 public twapPeriod;
uint256 public gpoolRewardPercent = 5000;
uint256 public firstStakingFee; //eth
address payable public feeTo;
// oracle state
IERC20 public gpoolToken;
address public weth;
IERC20 public usdc;
IGStakingVault public vault;
IUniswapV3CrossPoolOracle public oracle;
INonfungiblePositionManager public positionManager;
IUniswapV3Factory public uniswapFactory;
event Stake(address sender, uint256 amount, uint256 startStake);
event StakeNFT(address sender, uint256 tokenId, uint256 amount, uint256 startStake);
event Unstake(address sender, uint256 amount, uint256 startStake);
event UnstakeNFT(address sender, uint256 tokenId, uint256 amount, uint256 startStake);
event ClaimLockedReward(address sender, uint256 poolId, uint256 amount);
event ClaimReward(address sender, uint256 poolId, uint256 amount);
event CreatePool(uint256 poolId, PoolType poolType, uint128 chainId, address rewardToken, uint256 totalReward, uint256 openTime, uint256 closeTime);
event UpdatePoolReward(uint256 poolId, uint256 amountReward);
event UpdatePoolRewardRate(uint256 oldRate, uint256 newRate);
event UpdatePoolTime(uint256 poolId, uint256 startTime, uint256 endTime);
event SetTier(address account, Tier tier, uint256 startStake);
event SetDate(address account, Tier tier, uint256 startDate);
event VaultUpdated(address oldVault, address newVault);
event UpdateFirstStakingFee(uint256 _fee, address payable _feeTo);
/**
* @notice Validate pool by pool ID
* @param pid id of the pool
*/
modifier validatePoolById(uint256 pid) {
require(pid < poolInfo.length, "StakingPool: pool is not exist");
_;
}
constructor(
IGStakingVault _vault,
IUniswapV3CrossPoolOracle _oracle,
IERC20 _gpoolToken,
IERC20 _usdc,
address _weth,
INonfungiblePositionManager _positionManager,
IUniswapV3Factory _uniswapFactory,
address payable _feeTo,
uint256 _firstStakingFee,
address[] memory _admins
) {
vault = _vault;
oracle = _oracle;
gpoolToken = _gpoolToken;
usdc = _usdc;
weth = _weth;
positionManager = _positionManager;
uniswapFactory = _uniswapFactory;
twapPeriod = 1;
firstStakingFee = _firstStakingFee;
feeTo = _feeTo;
for (uint256 i = 0; i < _admins.length; ++i) {
_setupRole(GUARDIAN_ROLE, _admins[i]);
}
_setRoleAdmin(GUARDIAN_ROLE, BIG_GUARDIAN_ROLE);
_setupRole(GUARDIAN_ROLE, msg.sender);
_setupRole(BIG_GUARDIAN_ROLE, msg.sender);
}
function transferBigGuardian(address _newGuardian) public onlyRole(BIG_GUARDIAN_ROLE) {
require(_newGuardian != address(0) && _newGuardian != msg.sender, "Invalid new guardian");
renounceRole(BIG_GUARDIAN_ROLE, msg.sender);
_setupRole(BIG_GUARDIAN_ROLE, _newGuardian);
}
function updateVaultAddress(address _vault) public onlyRole(BIG_GUARDIAN_ROLE) {
require(_vault != address(0), "Vault address is invalid");
require(_vault != address(vault), "Vault address is exactly the same");
emit VaultUpdated(address(vault), _vault);
vault = IGStakingVault(_vault);
}
/**
* @notice allow users to call the requestTokens function to mint tokens
* @param amount amount to min, in ether format
*/
function requestTokens(uint256 amount) external {
ERC20Mintable gptoken = ERC20Mintable(address(gpoolToken));
require(amount <= MAX_FAUCET, "Can faucet max 50 token per time");
//perform a few check to make sure function can execute
require(block.timestamp > lockTime[msg.sender], "lock time has not expired. Please try again later");
//set role minter
_setupRole(MINTER_ROLE, msg.sender);
//mint tokens
gptoken.mint(msg.sender, amount);
//updates locktime 1 day from now
lockTime[msg.sender] = block.timestamp + 1 days;
}
function getTotalStake(StakeType stakeType) public view returns (uint256) {
return stakeType == StakeType.GPOOL ? totalGpoolStaked : totalNFTStaked;
}
/**
* @notice stake gpool to manager.
* @param amount amount to stake
*/
function stake(uint256 amount) external payable nonReentrant {
require(gpoolToken.balanceOf(msg.sender) >= amount, "not enough gpool");
_getStakeFeeIfNeed(msg.value, msg.sender);
StakeInfo storage staker = stakeInfo[msg.sender];
require(
gpoolInUSDC(staker.amount + amount + staker.nftInGpoolAmount) >= USDC_THRESHOLD,
"minimum stake does not match"
);
gpoolToken.safeTransferFrom(msg.sender, address(this), amount);
if (staker.startStake == 0) {
staker.startStake = block.timestamp;
}
StakeType stakeType = StakeType.GPOOL;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
if (block.timestamp <= pool.openTime) {
continue;
}
RewardInfo storage user = rewardInfo[pid][msg.sender];
updatePool(pid, stakeType);
uint256 pending = ((staker.amount * pool.accRewardPerShare[stakeType]) / ACCUMULATED_MULTIPLIER) -
user.rewardDebt[stakeType];
user.pendingReward = user.pendingReward + pending;
user.rewardDebt[stakeType] =
((staker.amount + amount) * pool.accRewardPerShare[stakeType]) /
ACCUMULATED_MULTIPLIER;
}
staker.amount += amount;
totalGpoolStaked += amount;
emit Stake(msg.sender, amount, staker.startStake);
}
function stakeNFT(uint256 tokenId) public payable nonReentrant {
_getStakeFeeIfNeed(msg.value, msg.sender);
StakeInfo storage staker = stakeInfo[msg.sender];
NFTInfo memory ntfInfo = getAmountFromTokenId(tokenId);
uint256 amout0InGpool = (ntfInfo.token0 == address(gpoolToken))
? ntfInfo.amount0
: tokenInGpool(ntfInfo.token0, ntfInfo.amount0);
uint256 amout1InGpool = (ntfInfo.token1 == address(gpoolToken))
? ntfInfo.amount1
: tokenInGpool(ntfInfo.token1, ntfInfo.amount1);
uint256 amount = amout0InGpool + amout1InGpool;
require(
gpoolInUSDC(staker.amount + amount + staker.nftInGpoolAmount) >= USDC_THRESHOLD,
"minimum stake does not match"
);
positionManager.transferFrom(msg.sender, address(this), tokenId);
if (staker.startStake == 0) {
staker.startStake = block.timestamp;
}
StakeType stakeType = StakeType.NFT;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
if (block.timestamp <= pool.openTime) {
continue;
}
RewardInfo storage user = rewardInfo[pid][msg.sender];
updatePool(pid, stakeType);
uint256 pending = ((staker.nftInGpoolAmount * pool.accRewardPerShare[stakeType]) / ACCUMULATED_MULTIPLIER) -
user.rewardDebt[stakeType];
user.pendingReward = user.pendingReward + pending;
user.rewardDebt[stakeType] =
((staker.nftInGpoolAmount + amount) * pool.accRewardPerShare[stakeType]) /
ACCUMULATED_MULTIPLIER;
}
staker.nftInGpoolAmount += amount;
totalNFTStaked += amount;
nftRecords[msg.sender][tokenId] = amount;
emit StakeNFT(msg.sender, tokenId, amount, staker.startStake);
}
/**
* @notice unstake Gpool.
* @param amount amount to withdraw
*/
function unstake(uint256 amount) external nonReentrant {
StakeInfo storage staker = stakeInfo[msg.sender];
require(amount <= staker.amount, "not enough balance");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
_updateUserReward(pid, amount, StakeType.GPOOL);
}
staker.amount -= amount;
totalGpoolStaked -= amount;
if (
(staker.amount + staker.nftInGpoolAmount) == 0 ||
gpoolInUSDC(staker.amount + staker.nftInGpoolAmount) < USDC_THRESHOLD
) {
staker.startStake = 0;
} else {
staker.startStake = block.timestamp;
}
gpoolToken.safeTransfer(msg.sender, amount);
emit Unstake(msg.sender, amount, staker.startStake);
}
/**
* @notice unstake NFT.
* @param tokenId amount to withdraw
*/
function unstakeNFT(uint256 tokenId) external nonReentrant {
StakeInfo storage staker = stakeInfo[msg.sender];
uint256 amount = nftRecords[msg.sender][tokenId];
require(amount > 0, "invalid tokenId");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
_updateUserReward(pid, amount, StakeType.NFT);
}
staker.nftInGpoolAmount -= amount;
totalNFTStaked -= amount;
if (
(staker.amount + staker.nftInGpoolAmount) == 0 ||
gpoolInUSDC(staker.amount + staker.nftInGpoolAmount) < USDC_THRESHOLD
) {
staker.startStake = 0;
} else {
staker.startStake = block.timestamp;
}
nftRecords[msg.sender][tokenId] = 0;
positionManager.transferFrom(address(this), msg.sender, tokenId);
emit UnstakeNFT(msg.sender, tokenId, amount, staker.startStake);
}
function _getStakeFeeIfNeed(uint256 amount, address user) private {
if (!hadStake[user]) {
require(amount == firstStakingFee, "Fee is not valid");
hadStake[user] = true;
feeTo.transfer(amount);
} else {
require(amount == 0, "Fee only apply in first staking");
}
}
function _updateUserReward(
uint256 pid,
uint256 amount,
StakeType stakeType
) internal {
PoolInfo storage pool = poolInfo[pid];
if (block.timestamp <= pool.openTime) {
return;
}
RewardInfo storage user = rewardInfo[pid][msg.sender];
StakeInfo storage staker = stakeInfo[msg.sender];
uint256 userAmountByType = (stakeType == StakeType.GPOOL) ? staker.amount : staker.nftInGpoolAmount;
updatePool(pid, stakeType);
uint256 pending = ((userAmountByType * pool.accRewardPerShare[stakeType]) / ACCUMULATED_MULTIPLIER) -
user.rewardDebt[stakeType];
if (pending > 0) {
user.pendingReward = user.pendingReward + pending;
}
user.rewardDebt[stakeType] =
((userAmountByType - amount) * pool.accRewardPerShare[stakeType]) /
ACCUMULATED_MULTIPLIER;
}
function claimLockedReward(uint256 pid) public validatePoolById(pid) returns (uint256) {
require(getTier(msg.sender) == Tier.GOLD, "Be gold to claim!");
LockedReward memory lockedReward = lockingAmounts[pid][msg.sender];
require(lockedReward.amount > 0, "Nothing to claim!");
vault.claimReward(address(lockedReward.rewardToken), msg.sender, lockedReward.amount);
emit ClaimLockedReward(msg.sender, pid, lockedReward.amount);
delete lockingAmounts[pid][msg.sender];
return lockedReward.amount;
}
/**
* @notice Harvest proceeds msg.sender
* @param pid id of the pool
*/
function claimReward(uint256 pid) public validatePoolById(pid) returns (uint256) {
Tier userTier = getTier(msg.sender);
require(getTier(msg.sender) != Tier.NORANK, "only tier");
require(
gpoolInUSDC(stakeInfo[msg.sender].amount + stakeInfo[msg.sender].nftInGpoolAmount) >= USDC_THRESHOLD,
"minimum stake does not match"
);
PoolInfo storage pool = poolInfo[pid];
require(pool.poolType == PoolType.CLAIMABLE, "Not able to claim from reward_calc pool!");
if (block.timestamp <= pool.openTime) {
return 0;
}
updatePool(pid, StakeType.GPOOL);
updatePool(pid, StakeType.NFT);
RewardInfo storage user = rewardInfo[pid][msg.sender];
StakeInfo storage staker = stakeInfo[msg.sender];
LockedReward memory lockedReward = lockingAmounts[pid][msg.sender];
uint256 totalPending = pendingReward(pid, msg.sender);
user.pendingReward = 0;
user.rewardDebt[StakeType.GPOOL] =
(staker.amount * pool.accRewardPerShare[StakeType.GPOOL]) /
(ACCUMULATED_MULTIPLIER);
user.rewardDebt[StakeType.NFT] =
(staker.nftInGpoolAmount * pool.accRewardPerShare[StakeType.NFT]) /
(ACCUMULATED_MULTIPLIER);
if (totalPending > 0) {
uint256 rewardByTier = (totalPending * uint256(userTier)) / uint256(Tier.GOLD);
uint256 lockedAmount = totalPending - rewardByTier;
_lockUserReward(msg.sender, pid, lockedAmount);
vault.claimReward(address(pool.rewardToken), msg.sender, rewardByTier);
totalPending = rewardByTier;
}
if (userTier == Tier.GOLD && lockedReward.amount > 0) {
vault.claimReward(address(pool.rewardToken), msg.sender, lockedReward.amount);
emit ClaimLockedReward(msg.sender, pid, lockedReward.amount);
delete lockingAmounts[pid][msg.sender];
}
emit ClaimReward(msg.sender, pid, totalPending);
return totalPending;
}
/**
* @notice Harvest proceeds of all pools for msg.sender
* @param pids ids of the pools
*/
function claimAll(uint256[] memory pids) external {
uint256 length = pids.length;
for (uint256 i = 0; i < length; ++i) {
claimReward(pids[i]);
}
}
/**
* @notice View function to see pending rewards on frontend.
* @param pid id of the pool
* @param userAddress the address of the user
*/
function pendingReward(uint256 pid, address userAddress) public view validatePoolById(pid) returns (uint256) {
PoolInfo storage pool = poolInfo[pid];
RewardInfo storage user = rewardInfo[pid][userAddress];
StakeInfo memory staker = stakeInfo[userAddress];
uint256 accRewardPerShareGpool = pool.accRewardPerShare[StakeType.GPOOL];
uint256 accRewardPerShareNFT = pool.accRewardPerShare[StakeType.NFT];
uint256 endTime = pool.closeTime < block.timestamp ? pool.closeTime : block.timestamp;
// gpool
if (endTime > pool.lastRewardSecond[StakeType.GPOOL] && totalGpoolStaked != 0) {
uint256 poolReward = (pool.totalReward[StakeType.GPOOL] *
(endTime - pool.lastRewardSecond[StakeType.GPOOL])) / (pool.closeTime - pool.openTime);
accRewardPerShareGpool = (accRewardPerShareGpool +
((poolReward * ACCUMULATED_MULTIPLIER) / totalGpoolStaked));
}
// nft
if (endTime > pool.lastRewardSecond[StakeType.NFT] && totalNFTStaked != 0) {
uint256 poolReward = (pool.totalReward[StakeType.NFT] * (endTime - pool.lastRewardSecond[StakeType.NFT])) /
(pool.closeTime - pool.openTime);
accRewardPerShareNFT = (accRewardPerShareNFT + ((poolReward * ACCUMULATED_MULTIPLIER) / totalNFTStaked));
}
uint256 totalUserDebt = user.rewardDebt[StakeType.NFT] + user.rewardDebt[StakeType.GPOOL];
uint256 totalPendingReward = (user.pendingReward +
(((staker.amount * accRewardPerShareGpool + staker.nftInGpoolAmount * accRewardPerShareNFT) /
ACCUMULATED_MULTIPLIER) - totalUserDebt));
return totalPendingReward;
}
/**
* @notice Update reward variables of the given pool to be up-to-date.
* @param pid id of the pool
*/
function updatePool(uint256 pid, StakeType stakeType) public validatePoolById(pid) {
PoolInfo storage pool = poolInfo[pid];
uint256 endTime = pool.closeTime < block.timestamp ? pool.closeTime : block.timestamp;
if (endTime <= pool.lastRewardSecond[stakeType]) {
return;
}
uint256 totalStake = getTotalStake(stakeType);
if (totalStake == 0) {
pool.lastRewardSecond[stakeType] = endTime;
return;
}
uint256 poolReward = (pool.totalReward[stakeType] * (endTime - pool.lastRewardSecond[stakeType])) /
(pool.closeTime - pool.openTime);
uint256 deltaRewardPerShare = (poolReward * ACCUMULATED_MULTIPLIER) / totalStake;
if (deltaRewardPerShare == 0 && block.timestamp < pool.closeTime) {
// wait for delta > 0
return;
}
pool.accRewardPerShare[stakeType] = pool.accRewardPerShare[stakeType] + deltaRewardPerShare;
pool.lastRewardSecond[stakeType] = endTime;
}
/**
* @notice Update reward vairables for all pools. Be careful of gas spending!
*/
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid, StakeType.GPOOL);
updatePool(pid, StakeType.NFT);
}
}
// create new pool reward
function createPool(
IERC20 rewardToken,
uint256 totalReward,
uint256 openTime,
uint256 closeTime,
PoolType poolType,
uint128 chainId
) external onlyRole(GUARDIAN_ROLE) {
require(block.timestamp <= openTime, "only future");
require(closeTime > openTime, "invalid time");
require(totalReward > 0, "invalid totalReward");
massUpdatePools();
if (poolType == PoolType.CLAIMABLE) {
require(rewardToken.balanceOf(msg.sender) >= totalReward, "not enough token balance");
rewardToken.safeTransferFrom(msg.sender, address(vault), totalReward);
}
poolInfo.push();
PoolInfo storage pool = poolInfo[poolInfo.length - 1];
pool.rewardToken = rewardToken;
pool.totalReward[StakeType.GPOOL] = (totalReward * gpoolRewardPercent) / PERCENT;
pool.totalReward[StakeType.NFT] = totalReward - pool.totalReward[StakeType.GPOOL];
pool.openTime = openTime;
pool.closeTime = closeTime;
pool.lastRewardSecond[StakeType.GPOOL] = openTime;
pool.lastRewardSecond[StakeType.NFT] = openTime;
pool.poolType = poolType;
pool.chainId = chainId;
uint256 pid = poolInfo.length - 1;
poolTypes[poolType].push(pid);
emit CreatePool(pid, poolType, chainId, address(rewardToken), totalReward, openTime, closeTime);
}
// update startTime, endTime of pool
function updatePoolTime(
uint256 pid,
uint256 startTime,
uint256 endTime
) external onlyRole(GUARDIAN_ROLE) validatePoolById(pid) {
PoolInfo storage pool = poolInfo[pid];
require(pool.openTime > block.timestamp, "pool started");
require(block.timestamp <= startTime, "only future");
require(endTime > startTime, "invalid time");
pool.openTime = startTime;
pool.closeTime = endTime;
pool.lastRewardSecond[StakeType.GPOOL] = startTime;
pool.lastRewardSecond[StakeType.NFT] = startTime;
emit UpdatePoolTime(pid, startTime, endTime);
}
// update total Reward of pool
function updatePoolReward(uint256 pid, uint256 amountReward)
external
onlyRole(GUARDIAN_ROLE)
validatePoolById(pid)
{
PoolInfo storage pool = poolInfo[pid];
require(pool.openTime > block.timestamp, "pool started");
require(amountReward > 0, "invalid totalReward");
uint256 oldTotalReward = pool.totalReward[StakeType.NFT] + pool.totalReward[StakeType.GPOOL];
pool.totalReward[StakeType.GPOOL] = (amountReward * gpoolRewardPercent) / PERCENT;
pool.totalReward[StakeType.NFT] = amountReward - pool.totalReward[StakeType.GPOOL];
if (pool.poolType == PoolType.CLAIMABLE) {
if (amountReward > oldTotalReward) {
pool.rewardToken.safeTransferFrom(msg.sender, address(vault), amountReward - oldTotalReward);
} else if (amountReward < oldTotalReward) {
vault.claimReward(address(pool.rewardToken), msg.sender, oldTotalReward - amountReward);
}
}
emit UpdatePoolReward(pid, amountReward);
}
function updatePoolRewardRate(uint256 _gpoolRewardPercent) public onlyRole(GUARDIAN_ROLE) {
require(_gpoolRewardPercent <= PERCENT, "Rate is not valid");
uint256 oldRate = gpoolRewardPercent;
gpoolRewardPercent = _gpoolRewardPercent;
for (uint256 pid = 0; pid < poolInfo.length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
if (block.timestamp >= pool.openTime) {
continue;
}
uint256 totalRewardByPool = pool.totalReward[StakeType.NFT] + pool.totalReward[StakeType.GPOOL];
pool.totalReward[StakeType.GPOOL] = (totalRewardByPool * gpoolRewardPercent) / PERCENT;
pool.totalReward[StakeType.NFT] = totalRewardByPool - pool.totalReward[StakeType.GPOOL];
}
emit UpdatePoolRewardRate(oldRate, _gpoolRewardPercent);
}
function updateFirstStakingFee(uint256 _fee, address payable _feeTo) public onlyRole(GUARDIAN_ROLE) {
feeTo = _feeTo;
firstStakingFee = _fee;
emit UpdateFirstStakingFee(_fee, _feeTo);
}
// gpoolInUSDC
// convert gpool to usdc value
function gpoolInUSDC(uint256 gpoolAmount) public view returns (uint256) {
// twap is in second
return oracle.assetToAsset(address(gpoolToken), gpoolAmount, address(usdc), twapPeriod);
}
function tokenInGpool(address token, uint256 amount) public view returns (uint256) {
// twap is in second
return oracle.assetToAsset(address(token), amount, address(gpoolToken), twapPeriod);
}
// getTier: user's gpass
function getTier(address user) public view returns (Tier) {
StakeInfo memory staker = stakeInfo[user];
if (staker.startStake == 0) {
return Tier.NORANK;
}
if (block.timestamp <= staker.startStake + SILVER_PIVOT) {
return Tier.BRONZE;
}
if (block.timestamp <= staker.startStake + GOLD_PIVOT) {
return Tier.SILVER;
}
return Tier.GOLD;
}
function setTwapPeriod(uint32 _twapPeriod) external onlyRole(GUARDIAN_ROLE) {
twapPeriod = _twapPeriod;
}
function setTiers(SetTierParam[] calldata params) external onlyRole(GUARDIAN_ROLE) {
uint256 length = params.length;
for (uint256 i = 0; i < length; ++i) {
StakeInfo storage staker = stakeInfo[params[i].account];
uint256 startStake = 0;
if (params[i].tier == Tier.GOLD) {
startStake = block.timestamp - GOLD_PIVOT - 1;
} else if (params[i].tier == Tier.SILVER) {
startStake = block.timestamp - SILVER_PIVOT - 1;
} else if (params[i].tier == Tier.BRONZE) {
startStake = block.timestamp - 1;
}
staker.startStake = startStake;
emit SetTier(params[i].account, params[i].tier, startStake);
}
}
function setDateStake(SetDateParam[] calldata params) external onlyRole(GUARDIAN_ROLE) {
uint256 length = params.length;
for (uint256 i = 0; i < length; ++i) {
StakeInfo storage staker = stakeInfo[params[i].account];
uint256 startStake = block.timestamp - params[i].time - 1;
staker.startStake = startStake;
Tier tier;
if (params[i].time <= 50 days) {
tier = Tier.BRONZE;
} else if (params[i].time <= 100 days) {
tier = Tier.SILVER;
} else {
tier = Tier.GOLD;
}
emit SetDate(params[i].account, tier, startStake);
}
}
// admin can withdraw reward token
function withdrawReward(IERC20 token, uint256 amount) external onlyRole(GUARDIAN_ROLE) {
require(token != gpoolToken, "only reward token");
token.safeTransfer(msg.sender, amount);
}
function _lockUserReward(
address _user,
uint256 _poolId,
uint256 _lockedAmount
) internal {
if (_lockedAmount > 0) {
PoolInfo storage pool = poolInfo[_poolId];
LockedReward memory userLockedReward = lockingAmounts[_poolId][_user];
uint256 updatedLockingAmount = userLockedReward.amount + _lockedAmount;
lockingAmounts[_poolId][_user] = LockedReward(address(pool.rewardToken), updatedLockingAmount);
}
}
// for nft
function getUniswapPoolInfo(uint256 tokenId) internal view returns (NFTInfo memory info) {
(
,
,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
,
,
,
) = positionManager.positions(tokenId);
info.pool = uniswapFactory.getPool(token0, token1, fee);
info.tickLower = tickLower;
info.tickUpper = tickUpper;
info.liquidity = liquidity;
info.token0 = token0;
info.token1 = token1;
}
function getAmountFromTokenId(uint256 tokenId) public view returns (NFTInfo memory) {
NFTInfo memory nftInfo = getUniswapPoolInfo(tokenId);
require(_isValidToken(nftInfo.token0, nftInfo.token1), "NFT: Wrong NFT type");
int24 tickLower = nftInfo.tickLower;
int24 tickUpper = nftInfo.tickUpper;
uint128 liquidityDelta = nftInfo.liquidity;
IUniswapPoolV3 uniswapPool = IUniswapPoolV3(nftInfo.pool);
IUniswapPoolV3.Slot0 memory slot = uniswapPool.slot0();
uint128 liquidity = uniswapPool.liquidity();
if (slot.tick < tickLower) {
// current tick is below the passed range; liquidity can only become in range by crossing from left to
// right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it
nftInfo.amount0 = SqrtPriceMath.getAmount0DeltaV2(
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidityDelta,
true
);
} else if (slot.tick < tickUpper) {
// current tick is inside the passed range
uint128 liquidityBefore = liquidity; // SLOAD for gas optimization
nftInfo.amount0 = SqrtPriceMath.getAmount0DeltaV2(
slot.sqrtPriceX96,
TickMath.getSqrtRatioAtTick(tickUpper),
liquidityDelta,
true
);
nftInfo.amount1 = SqrtPriceMath.getAmount1DeltaV2(
TickMath.getSqrtRatioAtTick(tickLower),
slot.sqrtPriceX96,
liquidityDelta,
true
);
liquidity = LiquidityMath.addDelta(liquidityBefore, liquidityDelta);
} else {
// current tick is above the passed range; liquidity can only become in range by crossing from right to
// left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it
nftInfo.amount1 = SqrtPriceMath.getAmount1DeltaV2(
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidityDelta,
true
);
}
return nftInfo;
}
function _isValidToken(address token0, address token1) private view returns (bool) {
if ((token0 == weth && token1 == address(gpoolToken)) || (token1 == weth && token0 == address(gpoolToken))) {
return true;
}
return false;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IGStakingVault {
function claimReward(address _token, address _receiver, uint _amount) external;
function recoverFund(address _token, address _receiver) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IPoolInitializer.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IERC721Permit.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IPeripheryPayments.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IPeripheryImmutableState.sol";
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
interface IUniswapPoolV3 {
struct Slot0 {
// the current price
uint160 sqrtPriceX96;
// the current tick
int24 tick;
// the most-recently updated index of the observations array
uint16 observationIndex;
// the current maximum number of observations that are being stored
uint16 observationCardinality;
// the next maximum number of observations to store, triggered in observations.write
uint16 observationCardinalityNext;
// the current protocol fee as a percentage of the swap fee taken on withdrawal
// represented as an integer denominator (1/x)%
uint8 feeProtocol;
// whether the pool is locked
bool unlocked;
}
function slot0() external view returns (Slot0 memory);
function liquidity() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
interface IUniswapV3CrossPoolOracle {
function assetToAsset(
address _tokenIn,
uint256 _amountIn,
address _tokenOut,
uint32 _twapPeriod
) external view returns (uint256 amountOut);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = denominator & (~denominator + 1);
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for liquidity
library LiquidityMath {
/// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
/// @param x The liquidity before change
/// @param y The delta by which liquidity should be changed
/// @return z The liquidity delta
function addDelta(uint128 x, uint128 y) internal pure returns (uint128 z) {
require((z = x + uint128(y)) >= x, 'LA');
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.0;
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;
import "./LowGasSafeMath.sol";
import "./SafeCast.sol";
import "./FullMath.sol";
import "./UnsafeMath.sol";
import "./FixedPoint96.sol";
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
using LowGasSafeMath for uint256;
using SafeCast for uint256;
/// @notice Gets the next sqrt price given a delta of token0
/// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
/// price less in order to not send too much output.
/// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
/// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
/// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of token0
/// @return The price after adding or removing amount, depending on add
function getNextSqrtPriceFromAmount0RoundingUp(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160) {
// we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
if (amount == 0) return sqrtPX96;
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
if (add) {
uint256 product;
if ((product = amount * sqrtPX96) / amount == sqrtPX96) {
uint256 denominator = numerator1 + product;
if (denominator >= numerator1)
// always fits in 160 bits
return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
}
return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));
} else {
uint256 product;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);
uint256 denominator = numerator1 - product;
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
}
}
/// @notice Gets the next sqrt price given a delta of token1
/// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
/// price less in order to not send too much output.
/// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
/// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of token1
/// @return The price after adding or removing `amount`
function getNextSqrtPriceFromAmount1RoundingDown(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160) {
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (add) {
uint256 quotient =
(
amount <= type(uint160).max
? (amount << FixedPoint96.RESOLUTION) / liquidity
: FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
);
return uint256(sqrtPX96).add(quotient).toUint160();
} else {
uint256 quotient =
(
amount <= type(uint160).max
? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
: FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
);
require(sqrtPX96 > quotient);
// always fits 160 bits
return uint160(sqrtPX96 - quotient);
}
}
/// @notice Gets the next sqrt price given an input amount of token0 or token1
/// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
/// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
/// @param liquidity The amount of usable liquidity
/// @param amountIn How much of token0, or token1, is being swapped in
/// @param zeroForOne Whether the amount in is token0 or token1
/// @return sqrtQX96 The price after adding the input amount to token0 or token1
function getNextSqrtPriceFromInput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountIn,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96) {
require(sqrtPX96 > 0);
require(liquidity > 0);
// round to make sure that we don't pass the target price
return
zeroForOne
? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
: getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
}
/// @notice Gets the next sqrt price given an output amount of token0 or token1
/// @dev Throws if price or liquidity are 0 or the next price is out of bounds
/// @param sqrtPX96 The starting price before accounting for the output amount
/// @param liquidity The amount of usable liquidity
/// @param amountOut How much of token0, or token1, is being swapped out
/// @param zeroForOne Whether the amount out is token0 or token1
/// @return sqrtQX96 The price after removing the output amount of token0 or token1
function getNextSqrtPriceFromOutput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountOut,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96) {
require(sqrtPX96 > 0);
require(liquidity > 0);
// round to make sure that we pass the target price
return
zeroForOne
? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
: getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
}
/// @notice Gets the amount0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
/// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices
function getAmount0DeltaV2(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;
require(sqrtRatioAX96 > 0);
return
roundUp
? UnsafeMath.divRoundingUp(
FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),
sqrtRatioAX96
)
: FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
}
/// @notice Gets the amount1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices
function getAmount1DeltaV2(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
roundUp
? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
: FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Helper that gets signed token0 delta
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount0 delta
/// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices
function getAmount0Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount0) {
return
liquidity < 0
? -getAmount0DeltaV2(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
: getAmount0DeltaV2(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
}
/// @notice Helper that gets signed token1 delta
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount1 delta
/// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices
function getAmount1Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount1) {
return
liquidity < 0
? -getAmount1DeltaV2(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
: getAmount1DeltaV2(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(int256(MAX_TICK)), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 has unspecified behavior, and must be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
}
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title ERC20Mintable
* @dev Implementation of the ERC20Mintable. Extension of {ERC20} that adds a minting behaviour.
*/
abstract contract ERC20Mintable is ERC20 {
// indicates if minting is finished
bool private _mintingFinished = false;
/**
* @dev Emitted during finish minting
*/
event MintFinished();
/**
* @dev Tokens can be minted only before minting finished.
*/
modifier canMint() {
require(!_mintingFinished, "ERC20Mintable: minting is finished");
_;
}
/**
* @return if minting is finished or not.
*/
function mintingFinished() public view returns (bool) {
return _mintingFinished;
}
/**
* @dev Function to mint tokens.
*
* WARNING: it allows everyone to mint new tokens. Access controls MUST be defined in derived contracts.
*
* @param account The address that will receive the minted tokens
* @param amount The amount of tokens to mint
*/
function mint(address account, uint256 amount) public canMint {
_mint(account, amount);
}
/**
* @dev Function to stop minting new tokens.
*
* WARNING: it allows everyone to finish minting. Access controls MUST be defined in derived contracts.
*/
function finishMinting() public canMint {
_finishMinting();
}
/**
* @dev Function to stop minting new tokens.
*/
function _finishMinting() internal virtual {
_mintingFinished = true;
emit MintFinished();
}
}
| unstake Gpool. amount amount to withdraw/ | function unstake(uint256 amount) external nonReentrant {
StakeInfo storage staker = stakeInfo[msg.sender];
require(amount <= staker.amount, "not enough balance");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
_updateUserReward(pid, amount, StakeType.GPOOL);
}
staker.amount -= amount;
totalGpoolStaked -= amount;
if (
(staker.amount + staker.nftInGpoolAmount) == 0 ||
gpoolInUSDC(staker.amount + staker.nftInGpoolAmount) < USDC_THRESHOLD
) {
staker.startStake = 0;
staker.startStake = block.timestamp;
}
gpoolToken.safeTransfer(msg.sender, amount);
emit Unstake(msg.sender, amount, staker.startStake);
}
| 5,408,856 |
pragma solidity ^0.4.14;
// https://ethereum.github.io/browser-solidity/
// modifier http://solidity.readthedocs.io/en/develop/common-patterns.html#state-machine
contract StateMachine {
enum Stages {
AcceptingBlindedBids,
RevealBids,
AnotherStage,
AreWeDoneYet,
Finished
}
// This is the current stage.
Stages public stage = Stages.AcceptingBlindedBids;
uint public creationTime = now;
modifier atStage(Stages _stage) {
require(stage == _stage);
_;
}
function nextStage() internal {
stage = Stages(uint(stage) + 1);
}
// Perform timed transitions. Be sure to mention
// this modifier first, otherwise the guards
// will not take the new stage into account.
modifier timedTransitions() {
if (stage == Stages.AcceptingBlindedBids &&
now >= creationTime + 10 days)
nextStage();
if (stage == Stages.RevealBids &&
now >= creationTime + 12 days)
nextStage();
// The other stages transition by transaction
_;
}
// Order of the modifiers matters here!
function bid()
payable
timedTransitions
atStage(Stages.AcceptingBlindedBids)
{
// We will not implement that here
}
function reveal()
timedTransitions
atStage(Stages.RevealBids)
{
}
// This modifier goes to the next stage
// after the function is done.
modifier transitionNext()
{
_;
nextStage();
}
function g()
timedTransitions
atStage(Stages.AnotherStage)
transitionNext
{
}
function h()
timedTransitions
atStage(Stages.AreWeDoneYet)
transitionNext
{
}
function i()
timedTransitions
atStage(Stages.Finished)
{
}
} | Order of the modifiers matters here! We will not implement that here | function bid()
payable
timedTransitions
atStage(Stages.AcceptingBlindedBids)
{
}
| 5,449,814 |
./full_match/5/0xF297472518294fa447483F9E5D40F43575FA78D1/sources/contracts/CrowdFunding.sol | getting the amount from the frontendgetting the campaign by id | function donatetoCampaign(uint256 _id) public payable {
uint256 ammount = msg.value;
Campaingn storage campaingn = campaingns[_id];
campaingn.donators.push(msg.sender);
campaingn.dontaions.push(ammount);
if (sent) {
campaingn.ammountCollected = campaingn.ammountCollected + ammount;
}
}
| 7,059,692 |
./full_match/80001/0x299D14a1100E5FF4E1B8CcB958161976629b6102/sources/contracts/relayer/loe-relayer/loe-feat-eip2771/contracts/contracts/nfts/ERC721VoucherMintableBurnable.sol | Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. voucher An NFTVoucher to hash. | function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) {
return _hashTypedDataV4(keccak256(abi.encode(
keccak256("NFTVoucher(uint256 tokenId,string uri)"),
voucher.tokenId,
keccak256(bytes(voucher.uri))
)));
}
| 870,792 |
//SPDX-License-Identifier: MIT
//Copyright 2021 Louis Sobel
pragma solidity ^0.8.0;
/*
88888888ba, 88888888ba 888b 88 88888888888 888888888888
88 `"8b 88 "8b 8888b 88 88 88
88 `8b 88 ,8P 88 `8b 88 88 88
88 88 88aaaaaa8P' 88 `8b 88 88aaaaa 88
88 88 88""""""8b, 88 `8b 88 88""""" 88
88 8P 88 `8b 88 `8b 88 88 88
88 .a8P 88 a8P 88 `8888 88 88
88888888Y"' 88888888P" 88 `888 88 88
https://dbnft.io
Generate NFTs by compiling the DBN language to EVM opcodes, then
deploying a contract that can render your art as a bitmap.
> Line 0 0 100 100
╱
╱
╱
╱
╱
╱
╱
╱
╱
╱
*/
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./DBNERC721Enumerable.sol";
import "./OpenSeaTradable.sol";
import "./OwnerSignedTicketRestrictable.sol";
import "./Drawing.sol";
import "./Token.sol";
import "./Serialize.sol";
/**
* @notice Compile DBN drawings to Ethereum Virtual Machine opcodes and deploy the code as NFT art.
* @dev This contract implements the ERC721 (including Metadata and Enumerable extensions)
* @author Louis Sobel
*/
contract DBNCoordinator is Ownable, DBNERC721Enumerable, OpenSeaTradable, OwnerSignedTicketRestrictable {
using Counters for Counters.Counter;
using Strings for uint256;
/**
* @dev There's two ~types of tokenId out of the 10201 (101x101) total tokens
* - 101 "allowlisted ones" [0, 100]
* - And "Open" ones [101, 10200]
* Minting of the allowlisted ones is through mintTokenId function
* Minting of the Open ones is through plain mint
*/
uint256 private constant LAST_ALLOWLISTED_TOKEN_ID = 100;
uint256 private constant LAST_TOKEN_ID = 10200;
/**
* @dev Event emitted when a a token is minted, linking the token ID
* to the address of the deployed drawing contract
*/
event DrawingDeployed(uint256 tokenId, address addr);
// Configuration
enum ContractMode { AllowlistOnly, Open }
ContractMode private _contractMode;
uint256 private _mintPrice;
string private _baseExternalURI;
address payable public recipient;
bool public recipientLocked;
// Minting
Counters.Counter private _tokenIds;
mapping (uint256 => address) private _drawingAddressForTokenId;
/**
* @dev Initializes the contract
* @param owner address to immediately transfer the contract to
* @param baseExternalURI URL (like https//dbnft.io/dbnft/) to which
* tokenIDs will be appended to get the `external_URL` metadata field
* @param openSeaProxyRegistry address of the opensea proxy registry, will
* be saved and queried in isAllowedForAll to facilitate opensea listing
*/
constructor(
address owner,
string memory baseExternalURI,
address payable _recipient,
address openSeaProxyRegistry
) ERC721("Design By Numbers NFT", "DBNFT") {
transferOwnership(owner);
_baseExternalURI = baseExternalURI;
_contractMode = ContractMode.AllowlistOnly;
// first _open_ token id
_tokenIds._value = LAST_ALLOWLISTED_TOKEN_ID + 1;
// initial mint price
_mintPrice = 0;
// initial recipient
recipient = _recipient;
// set up the opensea proxy registry
_setOpenSeaRegistry(openSeaProxyRegistry);
}
/******************************************************************************************
* _____ ____ _ _ ______ _____ _____
* / ____/ __ \| \ | | ____|_ _/ ____|
* | | | | | | \| | |__ | || | __
* | | | | | | . ` | __| | || | |_ |
* | |___| |__| | |\ | | _| || |__| |
* \_____\____/|_| \_|_| |_____\_____|
*
* Functions for configuring / interacting with the contract itself
*/
/**
* @notice The current "mode" of the contract: either AllowlistOnly (0) or Open (1).
* In AllowlistOnly mode, a signed ticket is required to mint. In Open mode,
* minting is open to all.
*/
function getContractMode() public view returns (ContractMode) {
return _contractMode;
}
/**
* @notice Moves the contract mode to Open. Only the owner can call this. Once the
* contract moves to Open, it cannot be moved back to AllowlistOnly
*/
function openMinting() public onlyOwner {
_contractMode = ContractMode.Open;
}
/**
* @notice Returns the current cost to mint. Applies to either mode.
* (And of course, this does not include gas ⛽️)
*/
function getMintPrice() public view returns (uint256) {
return _mintPrice;
}
/**
* @notice Sets the cost to mint. Only the owner can call this.
*/
function setMintPrice(uint256 price) public onlyOwner {
_mintPrice = price;
}
/**
* @notice Sets the recipient. Cannot be called after the recipient is locked.
* Only the owner can call this.
*/
function setRecipient(address payable to) public onlyOwner {
require(!recipientLocked, "RECIPIENT_LOCKED");
recipient = to;
}
/**
* @notice Prevents any future changes to the recipient.
* Only the owner can call this.
* @dev This enables post-deploy configurability of the recipient,
* combined with the ability to lock it in to facilitate
* confidence as to where the funds will be able to go.
*/
function lockRecipient() public onlyOwner {
recipientLocked = true;
}
/**
* @notice Disburses the contract balance to the stored recipient.
* Only the owner can call this.
*/
function disburse() public onlyOwner {
recipient.transfer(address(this).balance);
}
/******************************************************************************************
* __ __ _____ _ _ _______ _____ _ _ _____
* | \/ |_ _| \ | |__ __|_ _| \ | |/ ____|
* | \ / | | | | \| | | | | | | \| | | __
* | |\/| | | | | . ` | | | | | | . ` | | |_ |
* | | | |_| |_| |\ | | | _| |_| |\ | |__| |
* |_| |_|_____|_| \_| |_| |_____|_| \_|\_____|
*
* Functions for minting tokens!
*/
/**
* @notice Mints a token by deploying the given drawing bytecode
* @param bytecode The bytecode of the drawing to mint a token for.
* This bytecode should have been created by the DBN Compiler, otherwise
* the behavior of this function / the subsequent token is undefined.
*
* Requires passed value of at least the current mint price.
* Will revert if there are no more tokens available or if the current contract
* mode is not yet Open.
*/
function mint(bytes memory bytecode) public payable {
require(_contractMode == ContractMode.Open, "NOT_OPEN");
uint256 tokenId = _tokenIds.current();
require(tokenId <= LAST_TOKEN_ID, 'SOLD_OUT');
_tokenIds.increment();
_mintAtTokenId(bytecode, tokenId);
}
/**
* @notice Mints a token at the specific token ID by deploying the given drawing bytecode.
* Requires passing a ticket id and a signature generated by the contract owner
* granting permission for the caller to mint the specific token ID.
* @param bytecode The bytecode of the drawing to mint a token for
* This bytecode should have been created by the DBN Compiler, otherwise
* the behavior of this function / the subsequent token is undefined.
* @param tokenId The token ID to mint. Needs to be in the range [0, LAST_ALLOWLISTED_TOKEN_ID]
* @param ticketId The ID of the ticket; included as part of the signed data
* @param signature The bytes of the signature that must have been generated
* by the current owner of the contract.
*
* Requires passed value of at least the current mint price.
*/
function mintTokenId(
bytes memory bytecode,
uint256 tokenId,
uint256 ticketId,
bytes memory signature
) public payable onlyWithTicketFor(tokenId, ticketId, signature) {
require(tokenId <= LAST_ALLOWLISTED_TOKEN_ID, 'WRONG_TOKENID_RANGE');
_mintAtTokenId(bytecode, tokenId);
}
/**
* @dev Internal function that does the actual minting for both open and allowlisted mint
* @param bytecode The bytecode of the drawing to mint a token for
* @param tokenId The token ID to mint
*/
function _mintAtTokenId(
bytes memory bytecode,
uint256 tokenId
) internal {
require(msg.value >= _mintPrice, "WRONG_PRICE");
// Deploy the drawing
address addr = Drawing.deploy(bytecode, tokenId);
// Link the token ID to the drawing address
_drawingAddressForTokenId[tokenId] = addr;
// Mint the token (to the sender)
_safeMint(msg.sender, tokenId);
emit DrawingDeployed(tokenId, addr);
}
/**
* @notice Allows gas-less trading on OpenSea by safelisting the ProxyRegistry of the user
* @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy
* @inheritdoc ERC721
*/
function isApprovedForAll(
address owner,
address operator
) public view override returns (bool) {
return super.isApprovedForAll(owner, operator) || _isOwnersOpenSeaProxy(owner, operator);
}
/******************************************************************************************
* _______ ____ _ ________ _ _ _____ ______ _____ ______ _____ _____
* |__ __/ __ \| |/ / ____| \ | | | __ \| ____| /\ | __ \| ____| __ \ / ____|
* | | | | | | ' /| |__ | \| | | |__) | |__ / \ | | | | |__ | |__) | (___
* | | | | | | < | __| | . ` | | _ /| __| / /\ \ | | | | __| | _ / \___ \
* | | | |__| | . \| |____| |\ | | | \ \| |____ / ____ \| |__| | |____| | \ \ ____) |
* |_| \____/|_|\_\______|_| \_| |_| \_\______/_/ \_\_____/|______|_| \_\_____/
*
* Functions for reading / querying tokens
*/
/**
* @dev Helper that gets the address for a given token and reverts if it is not present
* @param tokenId the token to get the address of
*/
function _addressForToken(uint256 tokenId) internal view returns (address) {
address addr = _drawingAddressForTokenId[tokenId];
require(addr != address(0), "UNKNOWN_ID");
return addr;
}
/**
* @dev Helper that pulls together the metadata struct for a given token
* @param tokenId the token to get the metadata for
* @param addr the address of its drawing contract
*/
function _getMetadata(uint256 tokenId, address addr) internal view returns (Token.Metadata memory) {
string memory tokenIdAsString = tokenId.toString();
return Token.Metadata(
string(abi.encodePacked("DBNFT #", tokenIdAsString)),
string(Drawing.description(addr)),
string(abi.encodePacked(_baseExternalURI, tokenIdAsString)),
uint256(uint160(addr)).toHexString()
);
}
/**
* @notice The ERC721 tokenURI of the given token as an application/json data URI
* @param tokenId the token to get the tokenURI of
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
address addr = _addressForToken(tokenId);
(, bytes memory bitmapData) = Drawing.render(addr);
Token.Metadata memory metadata = _getMetadata(tokenId, addr);
return Serialize.tokenURI(bitmapData, metadata);
}
/**
* @notice Returns the metadata of the token, without the image data, as a JSON string
* @param tokenId the token to get the metadata of
*/
function tokenMetadata(uint256 tokenId) public view returns (string memory) {
address addr = _addressForToken(tokenId);
Token.Metadata memory metadata = _getMetadata(tokenId, addr);
return Serialize.metadataAsJSON(metadata);
}
/**
* @notice Returns the underlying bytecode of the drawing contract
* @param tokenId the token to get the drawing bytecode of
*/
function tokenCode(uint256 tokenId) public view returns (bytes memory) {
address addr = _addressForToken(tokenId);
return addr.code;
}
/**
* @notice Renders the token and returns an estimate of the gas used and the bitmap data itself
* @param tokenId the token to render
*/
function renderToken(uint256 tokenId) public view returns (uint256, bytes memory) {
address addr = _addressForToken(tokenId);
return Drawing.render(addr);
}
/**
* @notice Returns a list of which tokens in the [0, LAST_ALLOWLISTED_TOKEN_ID]
* have already been minted.
*/
function mintedAllowlistedTokens() public view returns (uint256[] memory) {
uint8 count = 0;
for (uint8 i = 0; i <= LAST_ALLOWLISTED_TOKEN_ID; i++) {
if (_exists(i)) {
count++;
}
}
uint256[] memory result = new uint256[](count);
count = 0;
for (uint8 i = 0; i <= LAST_ALLOWLISTED_TOKEN_ID; i++) {
if (_exists(i)) {
result[count] = i;
count++;
}
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
* @dev Modified copy of OpenZeppelin ERC721 Enumerable.
*
* Changes:
* - gets rid of _removeTokenFromAllTokensEnumeration: no burns (saves space)
* - adds public accessor for the allTokens array
*/
abstract contract DBNERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "OWNER_INDEX_OOB");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < DBNERC721Enumerable.totalSupply(), "GLOBAL_INDEX_OOB");
return _allTokens[index];
}
/**
* @notice Get a list of all minted tokens.
* @dev No guarantee of order.
*/
function allTokens() public view returns (uint256[] memory) {
return _allTokens;
}
/**
* @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`.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// Based off of https://gist.github.com/dievardump/483eb43bc6ed30b14f01e01842e3339b/
/// - but removes the _contractURI bits
/// - and makes it abstract
/// @title OpenSea contract helper that defines a few things
/// @author Simon Fremaux (@dievardump)
/// @dev This is a contract used to add OpenSea's
/// gas-less trading and contractURI support
abstract contract OpenSeaTradable {
address private _proxyRegistry;
/// @notice Returns the current OS proxyRegistry address registered
function openSeaProxyRegistry() public view returns (address) {
return _proxyRegistry;
}
/// @notice Helper allowing OpenSea gas-less trading by verifying who's operator
/// for owner
/// @dev Allows to check if `operator` is owner's OpenSea proxy on eth mainnet / rinkeby
/// or to check if operator is OpenSea's proxy contract on Polygon and Mumbai
/// @param owner the owner we check for
/// @param operator the operator (proxy) we check for
function _isOwnersOpenSeaProxy(address owner, address operator) internal virtual view
returns (bool)
{
address proxyRegistry_ = _proxyRegistry;
// if we have a proxy registry
if (proxyRegistry_ != address(0)) {
address ownerProxy = ProxyRegistry(proxyRegistry_).proxies(owner);
return ownerProxy == operator;
}
return false;
}
/// @dev Internal function to set the _proxyRegistry
/// @param proxyRegistryAddress the new proxy registry address
function _setOpenSeaRegistry(address proxyRegistryAddress) internal virtual {
_proxyRegistry = proxyRegistryAddress;
}
}
contract ProxyRegistry {
mapping(address => address) public proxies;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/**
* @dev Implements a mixin that uses ECDSA cryptography to restrict token minting to "ticket"-holders.
* This allows off-chain, gasless allowlisting of minting.
*
* A "Ticket" is a logical tuple of:
* - the Token ID
* - the address of a minter
* - the address of the token contract
* - a ticket ID (random number)
*
* By signing this tuple, the owner of the contract can grant permission to a specific address
* to mint a specific token ID at that specific token contract.
*/
abstract contract OwnerSignedTicketRestrictable is Ownable {
// Mapping to enable (very basic) ticket revocation
mapping (uint256 => bool) private _revokedTickets;
/**
* @dev Throws if the given signature, signed by the contract owner, does not grant
* the transaction sender a ticket to mint the given tokenId
* @param tokenId the ID of the token to check
* @param ticketId the ID of the ticket (included in signature)
* @param signature the bytes of the signature to use for verification
*
* This delegates straight into the checkTicket public function.
*/
modifier onlyWithTicketFor(uint256 tokenId, uint256 ticketId, bytes memory signature) {
checkTicket(msg.sender, tokenId, ticketId, signature);
_;
}
/**
* @notice Check the validity of a signature
* @dev Throws if the given signature wasn't signed by the contract owner for the
* "ticket" described by address(this) and the passed parameters
* (or if the ticket ID is revoked)
* @param minter the address of the minter in the ticket
* @param tokenId the token ID of the ticket
* @param ticketId the ticket ID
* @param signature the bytes of the signature
*
* Reuse of a ticket is prevented by existing controls preventing double-minting.
*/
function checkTicket(
address minter,
uint256 tokenId,
uint256 ticketId,
bytes memory signature
) public view {
bytes memory params = abi.encode(
address(this),
minter,
tokenId,
ticketId
);
address addr = ECDSA.recover(
ECDSA.toEthSignedMessageHash(keccak256(params)),
signature
);
require(addr == owner(), "BAD_SIGNATURE");
require(!_revokedTickets[ticketId], "TICKET_REVOKED");
}
/**
* @notice Revokes the given ticket IDs, preventing them from being used in the future
* @param ticketIds the ticket IDs to revoke
* @dev This can do nothing if the ticket ID has already been used, but
* this function gives an escape hatch for accidents, etc.
*/
function revokeTickets(uint256[] calldata ticketIds) public onlyOwner {
for (uint i=0; i<ticketIds.length; i++) {
_revokedTickets[ticketIds[i]] = true;
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./BitmapHeader.sol";
/**
* @dev Internal helper library to encapsulate interactions with a "Drawing" contract
*/
library Drawing {
/**
* @dev Deploys the given bytecode as a drawing contract
* @param bytecode The bytecode to pass to the CREATE opcode
* Must have been generated by the DBN compiler for predictable results.
* @param tokenId The tokenId to inject into the bytecode
* @return the address of the newly created contract
*
* Will also inject the given tokenID into the bytecode before deploy so that
* It is available in the deployed contract's context via a codecopy.
*
* The bytecode passed needs to be _deploy_ bytecode (so end up returning the
* actual bytecode). If any issues occur with the CREATE the transaction
* will fail with an assert (consuming all remaining gas). Detailed reasoning inline.
*/
function deploy(bytes memory bytecode, uint256 tokenId) internal returns (address) {
// First, inject the token id into the bytecode.
// The end of the bytecode is [2 bytes token id][32 bytes ipfs hash]
// (and we get the tokenID in in bigendian)
// This clearly assumes some coordination with the compiler (leaving this space blank!)
bytecode[bytecode.length - 32 - 2] = bytes1(uint8((tokenId & 0xFF00) >> 8));
bytecode[bytecode.length - 32 - 1] = bytes1(uint8(tokenId & 0xFF));
address addr;
assembly {
addr := create(0, add(bytecode, 0x20), mload(bytecode))
}
/*
if addr is zero, a few things could have happened:
a) out-of-gas in the create (which gets forwarded [current*(63/64) - 32000])
b) other exceptional halt (call stack too deep, invalid jump, etc)
c) revert from the create
in a): we should drain all existing gas and effectively bubble up the out of gas.
this makes sure that gas estimators do the right thing
in b): this is a nasty situation, so let's just drain away our gas anyway (true assert)
in c): pretty much same as b) — this is a bug in the passed bytecode, and we should fail.
that said, we _could_ check the μo return buffer for REVERT data, but no need for now.
So no matter what, we want to "assert" the addr is not zero
*/
assert(addr != address(0));
return addr;
}
/**
* @dev Renders the specified drawing contract as a bitmap
* @param addr The address of the drawing contract
* @return an estimation of the gas used and the 10962 bytes of the bitmap
*
* It calls the "0xBD" opcode of the drawing to get just the bitmap pixel data;
* the bitmap header is generated within this calling contract. This is to ensure
* that even if the deployed drawing doesn't conform to the DBN-drawing spec,
* a valid bitmap will always be returned.
*
* To further ensure that a valid bitmap is always returned, if the call
* to the drawing contract reverts, a bitmap will still be returned
* (though with the center pixel set to "55" to facilitate debugging)
*/
function render(address addr) internal view returns (uint256, bytes memory) {
uint bitmapLength = 10962;
uint headerLength = 40 + 14 + 404;
uint pixelDataLength = (10962 - headerLength);
bytes memory result = new bytes(bitmapLength);
bytes memory input = hex"BD";
uint256 startGas = gasleft();
BitmapHeader.writeTo(result);
uint resultOffset = 0x20 + headerLength; // after the header (and 0x20 for the dynamic byte length)
assembly {
let success := staticcall(
gas(),
addr,
add(input, 0x20),
1,
0, // return dst, but we're using the returnbuffer
0 // return length (we're using the returnbuffer)
)
let dataDst := add(result, resultOffset)
switch success
case 1 {
// Render call succeeded!
// copy min(returndataize, pixelDataLength) from the returnbuffer
// in happy path: returndatasize === pixeldatalength
// -> then great, either
// unexpected (too little data): returndatasize < pixeldatalength
// -> then we mustn't copy too much from the buffer! (use returndatasize)
// unexpected (too much data): returndatasize > pixeldatalength
// -> then we mustn't overflow our result! (use pixeldatalength)
let copySize := returndatasize()
if gt(copySize, pixelDataLength) {
copySize := pixelDataLength
}
returndatacopy(
dataDst, // dst offset
0, // src offset
copySize // length
)
}
case 0 {
// Render call failed :/
// Leave a little indicating pixel to hopefully help debugging
mstore8(
add(dataDst, 5250), // location of the center pixel (50 * 104 + 50)
0x55
)
}
}
// this overestimates _some_, but that's fine
uint256 endGas = gasleft();
return ((startGas - endGas), result);
}
/**
* @dev Gets the description stored in the code of a drawing contract
* @param addr The address of the drawing contract
* @return a (possibly empty) string description of the drawing
*
* It calls the "0xDE" opcode of the drawing to get its description.
* If the call fails, it will return an empty string.
*/
function description(address addr) internal view returns (string memory) {
(bool success, bytes memory desc) = addr.staticcall(hex"DE");
if (success) {
return string(desc);
} else {
return "";
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Namespace to encapsulate a "Metadata" struct for a drawing
*/
library Token {
struct Metadata {
string name;
string description;
string externalUrl;
string drawingAddress;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Token.sol";
import "./Base64.sol";
/**
* @dev Internal library encapsulating JSON / Token URI serialization
*/
library Serialize {
/**
* @dev Generates a ERC721 TokenURI for the given data
* @param bitmapData The raw bytes of the drawing's bitmap
* @param metadata The struct holding information about the drawing
* @return a string application/json data URI containing the token information
*
* We do _not_ base64 encode the JSON. This results in a slightly non-compliant
* data URI, because of the commas (and potential non-URL-safe characters).
* Empirically, this is fine: and re-base64-encoding everything would use
* gas and time and is not worth it.
*
* There's also a few ways we could encode the image in the metadata JSON:
* 1. image/bmp data url in the `image` field (base64-encoded given binary data)
* 2. raw svg data in the `image_data` field
* 3. image/svg data url in the `image` field (containing a base64-encoded image, but not itself base64-encoded)
* 4. (3), but with another layer of base64 encoding
* Through some trial and error, (1) does not work with Rarible or OpenSea. The rest do. (4) would be yet another
* layer of base64 (taking time, so is not desirable), (2) uses a potentially non-standard field, so we use (3).
*/
function tokenURI(bytes memory bitmapData, Token.Metadata memory metadata) internal pure returns (string memory) {
string memory imageKey = "image";
bytes memory imageData = _svgDataURI(bitmapData);
string memory fragment = _metadataJSONFragmentWithoutImage(metadata);
return string(abi.encodePacked(
'data:application/json,',
fragment,
// image data :)
'","', imageKey, '":"', imageData, '"}'
));
}
/**
* @dev Returns just the metadata of the image (no bitmap data) as a JSON string
* @param metadata The struct holding information about the drawing
*/
function metadataAsJSON(Token.Metadata memory metadata) internal pure returns (string memory) {
string memory fragment = _metadataJSONFragmentWithoutImage(metadata);
return string(abi.encodePacked(
fragment,
'"}'
));
}
/**
* @dev Returns a partial JSON string with the metadata of the image.
* Used by both the full tokenURI and the plain-metadata serializers.
* @param metadata The struct holding information about the drawing
*/
function _metadataJSONFragmentWithoutImage(Token.Metadata memory metadata) internal pure returns (string memory) {
return string(abi.encodePacked(
// name
'{"name":"',
metadata.name,
// description
'","description":"',
metadata.description,
// external_url
'","external_url":"',
metadata.externalUrl,
// code address
'","drawing_address":"',
metadata.drawingAddress
));
}
/**
* @dev Generates a data URI of an SVG containing an <image> tag containing the given bitmapData
* @param bitmapData The raw bytes of the drawing's bitmap
*/
function _svgDataURI(bytes memory bitmapData) internal pure returns (bytes memory) {
return abi.encodePacked(
"data:image/svg+xml,",
"<svg xmlns='http://www.w3.org/2000/svg' width='303' height='303'><image width='303' height='303' style='image-rendering: pixelated' href='",
"data:image/bmp;base64,",
Base64.encode(bitmapData),
"'/></svg>"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library encapsulating logic to generate the header + palette for a bitmap.
*
* Uses the "40-byte" header format, as described at
* http://www.ece.ualberta.ca/~elliott/ee552/studentAppNotes/2003_w/misc/bmp_file_format/bmp_file_format.htm
*
* Note that certain details (width, height, palette size, file size) are hardcoded
* based off the DBN-specific assumptions of 101x101 with 101 shades of grey.
*
*/
library BitmapHeader {
bytes32 internal constant HEADER1 = 0x424dd22a000000000000ca010000280000006500000065000000010008000000;
bytes22 internal constant HEADER2 = 0x00000000000000000000000000006500000000000000;
/**
* @dev Writes a 458 byte bitmap header + palette to the given array
* @param output The destination array. Gets mutated!
*/
function writeTo(bytes memory output) internal pure {
assembly {
mstore(add(output, 0x20), HEADER1)
mstore(add(output, 0x40), HEADER2)
}
// palette index is "DBN" color : [0, 100]
// map that to [0, 255] via:
// 255 - ((255 * c) / 100)
for (uint i = 0; i < 101; i++) {
bytes1 c = bytes1(uint8(255 - ((255 * i) / 100)));
uint o = i*4 + 54; // after the header
output[o] = c;
output[o + 1] = c;
output[o + 2] = c;
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Helper library for base64-encoding bytes
*/
library Base64 {
uint256 internal constant ALPHA1 = 0x4142434445464748494a4b4c4d4e4f505152535455565758595a616263646566;
uint256 internal constant ALPHA2 = 0x6768696a6b6c6d6e6f707172737475767778797a303132333435363738392b2f;
/**
* @dev Encodes the given bytearray to base64
* @param input The input data
* @return the output data
*/
function encode(bytes memory input) internal pure returns (bytes memory) {
if (input.length == 0) {
return input;
}
bytes memory output = new bytes(_encodedLength(input.length));
uint remaining = input.length;
assembly {
let src := add(input, 0x20)
let dst := add(output, 0x20)
// chunk loop
for {} gt(remaining, 0) {} {
let chunk := shr(16, mload(src))
let processing := 30
let sixtetCounter := 240 // 30 * 8
if lt(remaining, 30) {
processing := remaining
// slide right by 30–#remaining bytes (shl by 3 to get bits)
chunk := shr(shl(3, sub(30, remaining)), chunk)
// but now it needs to be nudge to the left by a few bits,
// to make sure total number of bits is multiple of 6
// 0 mod 3: nudge 0 bits
// 1 mod 3: nudge 4 bits
// 2 mod 3: nudge 2 bits
// we take advantage that this is the same as
// (v * 4) % 6
// this is empirically true, though I don't remember the number theory proving it
let nudgeBits := mulmod(remaining, 4, 6)
chunk := shl(nudgeBits, chunk)
// initial sixtet (remaining * 8 + nudge)
sixtetCounter := add(shl(3, remaining), nudgeBits)
}
remaining := sub(remaining, processing)
src := add(src, processing)
// byte loop
for {} gt(sixtetCounter, 0) {} {
sixtetCounter := sub(sixtetCounter, 6)
let val := shr(sixtetCounter, and(shl(sixtetCounter, 0x3F), chunk))
let alpha := ALPHA1
if gt(val, 0x1F) {
alpha := ALPHA2
val := sub(val, 0x20)
}
let char := byte(val, alpha)
mstore8(dst, char)
dst := add(dst, 1)
}
}
// padding depending on input length % 3
switch mod(mload(input), 3)
case 1 {
// two pads
mstore8(dst, 0x3D) // 0x3d is =
mstore8(add(1, dst), 0x3D) // 0x3d is =
}
case 2 {
// one pad
mstore8(dst, 0x3D)
}
}
return output;
}
/**
* @dev Helper to get the length of the output data
*
* Implements Ceil(inputLength / 3) * 4
*/
function _encodedLength(uint inputLength) internal pure returns (uint) {
return ((inputLength + 2) / 3) * 4;
}
} | Generates a ERC721 TokenURI for the given data bitmapData The raw bytes of the drawing's bitmap metadata The struct holding information about the drawing return a string application/json data URI containing the token information We do _not_ base64 encode the JSON. This results in a slightly non-compliant data URI, because of the commas (and potential non-URL-safe characters). Empirically, this is fine: and re-base64-encoding everything would use gas and time and is not worth it. There's also a few ways we could encode the image in the metadata JSON: 1. image/bmp data url in the `image` field (base64-encoded given binary data) 2. raw svg data in the `image_data` field 3. image/svg data url in the `image` field (containing a base64-encoded image, but not itself base64-encoded) 4. (3), but with another layer of base64 encoding Through some trial and error, (1) does not work with Rarible or OpenSea. The rest do. (4) would be yet another layer of base64 (taking time, so is not desirable), (2) uses a potentially non-standard field, so we use (3)./ image data :) | function tokenURI(bytes memory bitmapData, Token.Metadata memory metadata) internal pure returns (string memory) {
string memory imageKey = "image";
bytes memory imageData = _svgDataURI(bitmapData);
string memory fragment = _metadataJSONFragmentWithoutImage(metadata);
return string(abi.encodePacked(
'data:application/json,',
fragment,
'","', imageKey, '":"', imageData, '"}'
));
| 13,463,336 |
pragma solidity 0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Token is StandardToken, BurnableToken, Ownable {
/**
* @dev Use SafeMath library for all uint256 variables
*/
using SafeMath for uint256;
/**
* @dev ERC20 variables
*/
string public name = "MIMIC";
string public symbol = "MIMIC";
uint256 public decimals = 18;
/**
* @dev Total token supply
*/
uint256 public INITIAL_SUPPLY = 900000000 * (10 ** decimals);
/**
* @dev Addresses where the tokens will be stored initially
*/
address public constant ICO_ADDRESS = 0x93Fc953BefEF145A92760476d56E45842CE00b2F;
address public constant PRESALE_ADDRESS = 0x3be448B6dD35976b58A9935A1bf165d5593F8F27;
/**
* @dev Address that can receive the tokens before the end of the ICO
*/
address public constant BACKUP_ONE = 0x9146EE4eb69f92b1e59BE9C7b4718d6B75F696bE;
address public constant BACKUP_TWO = 0xe12F95964305a00550E1970c3189D6aF7DB9cFdd;
address public constant BACKUP_FOUR = 0x2FBF54a91535A5497c2aF3BF5F64398C4A9177a2;
address public constant BACKUP_THREE = 0xa41554b1c2d13F10504Cc2D56bF0Ba9f845C78AC;
/**
* @dev Team members has temporally locked token.
* Variables used to define how the tokens will be unlocked.
*/
uint256 public lockStartDate = 0;
uint256 public lockEndDate = 0;
uint256 public lockAbsoluteDifference = 0;
mapping (address => uint256) public initialLockedAmounts;
/**
* @dev Defines if tokens arre free to move or not
*/
bool public areTokensFree = false;
/**
* @dev Emitted when the token locked amount of an address is set
*/
event SetLockedAmount(address indexed owner, uint256 amount);
/**
* @dev Emitted when the token locked amount of an address is updated
*/
event UpdateLockedAmount(address indexed owner, uint256 amount);
/**
* @dev Emitted when it will be time to free the unlocked tokens
*/
event FreeTokens();
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[owner] = totalSupply_;
}
/**
* @dev Check whenever an address has the power to transfer tokens before the end of the ICO
* @param _sender Address of the transaction sender
* @param _to Destination address of the transaction
*/
modifier canTransferBeforeEndOfIco(address _sender, address _to) {
require(
areTokensFree ||
_sender == owner ||
_sender == ICO_ADDRESS ||
_sender == PRESALE_ADDRESS ||
(
_to == BACKUP_ONE ||
_to == BACKUP_TWO ||
_to == BACKUP_THREE ||
_to == BACKUP_FOUR
)
, "Cannot transfer tokens yet"
);
_;
}
/**
* @dev Check whenever an address can transfer an certain amount of token in the case all or some part
* of them are locked
* @param _sender Address of the transaction sender
* @param _amount The amount of tokens the address is trying to transfer
*/
modifier canTransferIfLocked(address _sender, uint256 _amount) {
uint256 afterTransfer = balances[_sender].sub(_amount);
require(afterTransfer >= getLockedAmount(_sender), "Not enought unlocked tokens");
_;
}
/**
* @dev Returns the amount of tokens an address has locked
* @param _addr The address in question
*/
function getLockedAmount(address _addr) public view returns (uint256){
if (now >= lockEndDate || initialLockedAmounts[_addr] == 0x0)
return 0;
if (now < lockStartDate)
return initialLockedAmounts[_addr];
uint256 alpha = uint256(now).sub(lockStartDate); // absolute purchase date
uint256 tokens = initialLockedAmounts[_addr].sub(alpha.mul(initialLockedAmounts[_addr]).div(lockAbsoluteDifference)); // T - (α * T) / β
return tokens;
}
/**
* @dev Sets the amount of locked tokens for a specific address. It doesn't transfer tokens!
* @param _addr The address in question
* @param _amount The amount of tokens to lock
*/
function setLockedAmount(address _addr, uint256 _amount) public onlyOwner {
require(_addr != address(0x0), "Cannot set locked amount to null address");
initialLockedAmounts[_addr] = _amount;
emit SetLockedAmount(_addr, _amount);
}
/**
* @dev Updates (adds to) the amount of locked tokens for a specific address. It doesn't transfer tokens!
* @param _addr The address in question
* @param _amount The amount of locked tokens to add
*/
function updateLockedAmount(address _addr, uint256 _amount) public onlyOwner {
require(_addr != address(0x0), "Cannot update locked amount to null address");
require(_amount > 0, "Cannot add 0");
initialLockedAmounts[_addr] = initialLockedAmounts[_addr].add(_amount);
emit UpdateLockedAmount(_addr, _amount);
}
/**
* @dev Frees all the unlocked tokens
*/
function freeTokens() public onlyOwner {
require(!areTokensFree, "Tokens have already been freed");
areTokensFree = true;
lockStartDate = now;
// lockEndDate = lockStartDate + 365 days;
lockEndDate = lockStartDate + 1 days;
lockAbsoluteDifference = lockEndDate.sub(lockStartDate);
emit FreeTokens();
}
/**
* @dev Override of ERC20's transfer function with modifiers
* @param _to The address to which tranfer the tokens
* @param _value The amount of tokens to transfer
*/
function transfer(address _to, uint256 _value)
public
canTransferBeforeEndOfIco(msg.sender, _to)
canTransferIfLocked(msg.sender, _value)
returns (bool)
{
return super.transfer(_to, _value);
}
/**
* @dev Override of ERC20's transfer function with modifiers
* @param _from The address from which tranfer the tokens
* @param _to The address to which tranfer the tokens
* @param _value The amount of tokens to transfer
*/
function transferFrom(address _from, address _to, uint _value)
public
canTransferBeforeEndOfIco(_from, _to)
canTransferIfLocked(_from, _value)
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
}
contract Presale is Ownable {
/**
* @dev Use SafeMath library for all uint256 variables
*/
using SafeMath for uint256;
/**
* @dev Our previously deployed Token (ERC20) contract
*/
Token public token;
/**
* @dev How many tokens a buyer takes per wei
*/
uint256 public rate;
/**
* @dev The address where all the funds will be stored
*/
address public wallet;
/**
* @dev The address where all the tokens are stored
*/
address public holder;
/**
* @dev The amount of wei raised during the ICO
*/
uint256 public weiRaised;
/**
* @dev The amount of tokens purchased by the buyers
*/
uint256 public tokenPurchased;
/**
* @dev Crowdsale start date
*/
uint256 public constant startDate = 1535994000; // 2018-09-03 17:00:00 (UTC)
/**
* @dev Crowdsale end date
*/
uint256 public constant endDate = 1541264400; // 2018-10-01 10:00:00 (UTC)
/**
* @dev The minimum amount of ethereum that we accept as a contribution
*/
uint256 public minimumAmount = 40 ether;
/**
* @dev The maximum amount of ethereum that an address can contribute
*/
uint256 public maximumAmount = 200 ether;
/**
* @dev Mapping tracking how much an address has contribuited
*/
mapping (address => uint256) public contributionAmounts;
/**
* @dev Mapping containing which addresses are whitelisted
*/
mapping (address => bool) public whitelist;
/**
* @dev Emitted when an amount of tokens is beign purchased
*/
event Purchase(address indexed sender, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @dev Emitted when we change the conversion rate
*/
event ChangeRate(uint256 rate);
/**
* @dev Emitted when we change the minimum contribution amount
*/
event ChangeMinimumAmount(uint256 amount);
/**
* @dev Emitted when we change the maximum contribution amount
*/
event ChangeMaximumAmount(uint256 amount);
/**
* @dev Emitted when the whitelisted state of and address is changed
*/
event Whitelist(address indexed beneficiary, bool indexed whitelisted);
/**
* @dev Contract constructor
* @param _tokenAddress The address of the previously deployed Token contract
*/
constructor(address _tokenAddress, uint256 _rate, address _wallet, address _holder) public {
require(_tokenAddress != address(0), "Token Address cannot be a null address");
require(_rate > 0, "Conversion rate must be a positive integer");
require(_wallet != address(0), "Wallet Address cannot be a null address");
require(_holder != address(0), "Holder Address cannot be a null address");
token = Token(_tokenAddress);
rate = _rate;
wallet = _wallet;
holder = _holder;
}
/**
* @dev Modifier used to verify if an address can purchase
*/
modifier canPurchase(address _beneficiary) {
require(now >= startDate, "Presale has not started yet");
require(now <= endDate, "Presale has finished");
require(whitelist[_beneficiary] == true, "Your address is not whitelisted");
uint256 amount = uint256(contributionAmounts[_beneficiary]).add(msg.value);
require(msg.value >= minimumAmount, "Cannot contribute less than the minimum amount");
require(amount <= maximumAmount, "Cannot contribute more than the maximum amount");
_;
}
/**
* @dev Fallback function, called when someone tryes to pay send ether to the contract address
*/
function () external payable {
purchase(msg.sender);
}
/**
* @dev General purchase function, used by the fallback function and from buyers who are buying for other addresses
* @param _beneficiary The Address that will receive the tokens
*/
function purchase(address _beneficiary) internal canPurchase(_beneficiary) {
uint256 weiAmount = msg.value;
// Validate beneficiary and wei amount
require(_beneficiary != address(0), "Beneficiary Address cannot be a null address");
require(weiAmount > 0, "Wei amount must be a positive integer");
// Calculate token amount
uint256 tokenAmount = _getTokenAmount(weiAmount);
// Update totals
weiRaised = weiRaised.add(weiAmount);
tokenPurchased = tokenPurchased.add(tokenAmount);
contributionAmounts[_beneficiary] = contributionAmounts[_beneficiary].add(weiAmount);
_transferEther(weiAmount);
// Make the actual purchase and send the tokens to the contributor
_purchaseTokens(_beneficiary, tokenAmount);
// Emit purchase event
emit Purchase(msg.sender, _beneficiary, weiAmount, tokenAmount);
}
/**
* @dev Updates the conversion rate to a new value
* @param _rate The new conversion rate
*/
function updateConversionRate(uint256 _rate) public onlyOwner {
require(_rate > 0, "Conversion rate must be a positive integer");
rate = _rate;
emit ChangeRate(_rate);
}
/**
* @dev Updates the minimum contribution amount to a new value
* @param _amount The new minimum contribution amount expressed in wei
*/
function updateMinimumAmount(uint256 _amount) public onlyOwner {
require(_amount > 0, "Minimum amount must be a positive integer");
minimumAmount = _amount;
emit ChangeMinimumAmount(_amount);
}
/**
* @dev Updates the maximum contribution amount to a new value
* @param _amount The new maximum contribution amount expressed in wei
*/
function updateMaximumAmount(uint256 _amount) public onlyOwner {
require(_amount > 0, "Maximum amount must be a positive integer");
maximumAmount = _amount;
emit ChangeMaximumAmount(_amount);
}
/**
* @dev Updates the whitelisted status of an address
* @param _addr The address in question
* @param _whitelist The new whitelist status
*/
function setWhitelist(address _addr, bool _whitelist) public onlyOwner {
require(_addr != address(0x0), "Whitelisted address must be valid");
whitelist[_addr] = _whitelist;
emit Whitelist(_addr, _whitelist);
}
/**
* @dev Processes the actual purchase (token transfer)
* @param _beneficiary The Address that will receive the tokens
* @param _amount The amount of tokens to transfer
*/
function _purchaseTokens(address _beneficiary, uint256 _amount) internal {
token.transferFrom(holder, _beneficiary, _amount);
}
/**
* @dev Transfers the ethers recreived from the contributor to the Presale wallet
* @param _amount The amount of ethers to transfer
*/
function _transferEther(uint256 _amount) internal {
// this should throw an exeption if it fails
wallet.transfer(_amount);
}
/**
* @dev Returns an amount of wei converted in tokens
* @param _wei Value in wei to be converted
* @return Amount of tokens
*/
function _getTokenAmount(uint256 _wei) internal view returns (uint256) {
// wei * ((rate * (30 + 100)) / 100)
return _wei.mul(rate.mul(130).div(100));
}
} | Updates (adds to) the amount of locked tokens for a specific address. It doesn't transfer tokens! _addr The address in question _amount The amount of locked tokens to add/ | function updateLockedAmount(address _addr, uint256 _amount) public onlyOwner {
require(_addr != address(0x0), "Cannot update locked amount to null address");
require(_amount > 0, "Cannot add 0");
initialLockedAmounts[_addr] = initialLockedAmounts[_addr].add(_amount);
emit UpdateLockedAmount(_addr, _amount);
}
| 12,647,313 |
./full_match/137/0xab03C0c0Ba39a886eD51757272E91cd739542118/sources/contracts/KeeperRewardDistributor/KeeperRewardDistributor.sol | @inheritdoc IKeeperRewardDistributor/ | function setDefaultMaxGasPrice(uint256 _defaultMaxGasPrice) external override onlyRole(MEDIUM_TIMELOCK_ADMIN) {
defaultMaxGasPrice = _defaultMaxGasPrice;
emit DefaultMaxGasPriceChanged(_defaultMaxGasPrice);
}
| 4,727,314 |
pragma solidity 0.4.18;
/// @title ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20)
contract ERC20 {
uint public totalSupply;
function balanceOf(address _owner) constant public returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint remaining);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/// @title Basic ERC20 token contract implementation.
/// @dev Based on OpenZeppelin's StandardToken.
contract BasicToken is ERC20 {
using SafeMath for uint256;
uint256 public totalSupply;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => uint256) balances;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender address The address which will spend the funds.
/// @param _value uint256 The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve (see NOTE)
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) {
revert();
}
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 uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @dev Gets the balance of the specified address.
/// @param _owner address The address to query the the balance of.
/// @return uint256 representing the amount owned by the passed address.
function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
/// @dev Transfer token to a specified address.
/// @param _to address The address to transfer to.
/// @param _value uint256 The amount to be transferred.
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/// @dev Transfer tokens from one address to another.
/// @param _from address The address which you want to send tokens from.
/// @param _to address The address which you want to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
}
/// @title ERC Token Standard #677 Interface (https://github.com/ethereum/EIPs/issues/677)
contract ERC677 is ERC20 {
function transferAndCall(address to, uint value, bytes data) public returns (bool ok);
event TransferAndCall(address indexed from, address indexed to, uint value, bytes data);
}
/// @title Math operations with safety checks
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// require(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// require(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) {
require(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function toPower2(uint256 a) internal pure returns (uint256) {
return mul(a, a);
}
function sqrt(uint256 a) internal pure returns (uint256) {
uint256 c = (a + 1) / 2;
uint256 b = a;
while (c < b) {
b = c;
c = (a / c + c) / 2;
}
return b;
}
}
/// @title Standard677Token implentation, base on https://github.com/ethereum/EIPs/issues/677
contract Standard677Token is ERC677, BasicToken {
/// @dev ERC223 safe token transfer from one address to another
/// @param _to address the address which you want to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function transferAndCall(address _to, uint _value, bytes _data) public returns (bool) {
require(super.transfer(_to, _value)); // do a normal token transfer
TransferAndCall(msg.sender, _to, _value, _data);
//filtering if the target is a contract with bytecode inside it
if (isContract(_to)) return contractFallback(_to, _value, _data);
return true;
}
/// @dev called when transaction target is a contract
/// @param _to address the address which you want to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function contractFallback(address _to, uint _value, bytes _data) private returns (bool) {
ERC223Receiver receiver = ERC223Receiver(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
return true;
}
/// @dev check if the address is contract
/// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
/// @param _addr address the address to check
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;
}
}
/// @title Ownable
/// @dev The Ownable contract has an owner address, and provides basic authorization control functions,
/// this simplifies the implementation of "user permissions".
/// @dev Based on OpenZeppelin's Ownable.
contract Ownable {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed _by, address indexed _to);
event OwnershipTransferred(address indexed _from, address indexed _to);
/// @dev Constructor sets the original `owner` of the contract to the sender account.
function Ownable() public {
owner = msg.sender;
}
/// @dev Reverts if called by any account other than the owner.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyOwnerCandidate() {
require(msg.sender == newOwnerCandidate);
_;
}
/// @dev Proposes to transfer control of the contract to a newOwnerCandidate.
/// @param _newOwnerCandidate address The address to transfer ownership to.
function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
require(_newOwnerCandidate != address(0));
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner.
function acceptOwnership() external onlyOwnerCandidate {
address previousOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = address(0);
OwnershipTransferred(previousOwner, owner);
}
}
/// @title Token holder contract.
contract TokenHolder is Ownable {
/// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens.
/// @param _tokenAddress address The address of the ERC20 contract.
/// @param _amount uint256 The amount of tokens to be transferred.
function transferAnyERC20Token(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) {
return ERC20(_tokenAddress).transfer(owner, _amount);
}
}
/// @title Colu Local Currency contract.
/// @author Rotem Lev.
contract ColuLocalCurrency is Ownable, Standard677Token, TokenHolder {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
/// @dev cotract to use when issuing a CC (Local Currency)
/// @param _name string name for CC token that is created.
/// @param _symbol string symbol for CC token that is created.
/// @param _decimals uint8 percison for CC token that is created.
/// @param _totalSupply uint256 total supply of the CC token that is created.
function ColuLocalCurrency(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public {
require(_totalSupply != 0);
require(bytes(_name).length != 0);
require(bytes(_symbol).length != 0);
totalSupply = _totalSupply;
name = _name;
symbol = _symbol;
decimals = _decimals;
balances[msg.sender] = totalSupply;
}
}
/// @title ERC223Receiver Interface
/// @dev Based on the specs form: https://github.com/ethereum/EIPs/issues/223
contract ERC223Receiver {
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok);
}
/// @title Standard ERC223 Token Receiver implementing tokenFallback function and tokenPayable modifier
contract Standard223Receiver is ERC223Receiver {
Tkn tkn;
struct Tkn {
address addr;
address sender; // the transaction caller
uint256 value;
}
bool __isTokenFallback;
modifier tokenPayable {
require(__isTokenFallback);
_;
}
/// @dev Called when the receiver of transfer is contract
/// @param _sender address the address of tokens sender
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) {
if (!supportsToken(msg.sender)) {
return false;
}
// Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory.
// Solution: Remove the the data
tkn = Tkn(msg.sender, _sender, _value);
__isTokenFallback = true;
if (!address(this).delegatecall(_data)) {
__isTokenFallback = false;
return false;
}
// avoid doing an overwrite to .token, which would be more expensive
// makes accessing .tkn values outside tokenPayable functions unsafe
__isTokenFallback = false;
return true;
}
function supportsToken(address token) public constant returns (bool);
}
/// @title TokenOwnable
/// @dev The TokenOwnable contract adds a onlyTokenOwner modifier as a tokenReceiver with ownable addaptation
contract TokenOwnable is Standard223Receiver, Ownable {
/// @dev Reverts if called by any account other than the owner for token sending.
modifier onlyTokenOwner() {
require(tkn.sender == owner);
_;
}
}
/// @title Market Maker Interface.
/// @author Tal Beja.
contract MarketMaker is ERC223Receiver {
function getCurrentPrice() public constant returns (uint _price);
function change(address _fromToken, uint _amount, address _toToken) public returns (uint _returnAmount);
function change(address _fromToken, uint _amount, address _toToken, uint _minReturn) public returns (uint _returnAmount);
function change(address _toToken) public returns (uint _returnAmount);
function change(address _toToken, uint _minReturn) public returns (uint _returnAmount);
function quote(address _fromToken, uint _amount, address _toToken) public constant returns (uint _returnAmount);
function openForPublicTrade() public returns (bool success);
function isOpenForPublic() public returns (bool success);
event Change(address indexed fromToken, uint inAmount, address indexed toToken, uint returnAmount, address indexed account);
}
/// @title Ellipse Market Maker contract.
/// @dev market maker, using ellipse equation.
/// @author Tal Beja.
contract EllipseMarketMaker is TokenOwnable {
// precision for price representation (as in ether or tokens).
uint256 public constant PRECISION = 10 ** 18;
// The tokens pair.
ERC20 public token1;
ERC20 public token2;
// The tokens reserves.
uint256 public R1;
uint256 public R2;
// The tokens full suplly.
uint256 public S1;
uint256 public S2;
// State flags.
bool public operational;
bool public openForPublic;
// Library contract address.
address public mmLib;
/// @dev Constructor calling the library contract using delegate.
function EllipseMarketMaker(address _mmLib, address _token1, address _token2) public {
require(_mmLib != address(0));
// Signature of the mmLib's constructor function
// bytes4 sig = bytes4(keccak256("constructor(address,address,address)"));
bytes4 sig = 0x6dd23b5b;
// 3 arguments of size 32
uint256 argsSize = 3 * 32;
// sig + arguments size
uint256 dataSize = 4 + argsSize;
bytes memory m_data = new bytes(dataSize);
assembly {
// Add the signature first to memory
mstore(add(m_data, 0x20), sig)
// Add the parameters
mstore(add(m_data, 0x24), _mmLib)
mstore(add(m_data, 0x44), _token1)
mstore(add(m_data, 0x64), _token2)
}
// delegatecall to the library contract
require(_mmLib.delegatecall(m_data));
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param token can be token1 or token2
function supportsToken(address token) public constant returns (bool) {
return (token1 == token || token2 == token);
}
/// @dev gets called when no other function matches, delegate to the lib contract.
function() public {
address _mmLib = mmLib;
if (msg.data.length > 0) {
assembly {
calldatacopy(0xff, 0, calldatasize)
let retVal := delegatecall(gas, _mmLib, 0xff, calldatasize, 0, 0x20)
switch retVal case 0 { revert(0,0) } default { return(0, 0x20) }
}
}
}
}
/// @title Ellipse Market Maker Interfase
/// @author Tal Beja
contract IEllipseMarketMaker is MarketMaker {
// precision for price representation (as in ether or tokens).
uint256 public constant PRECISION = 10 ** 18;
// The tokens pair.
ERC20 public token1;
ERC20 public token2;
// The tokens reserves.
uint256 public R1;
uint256 public R2;
// The tokens full suplly.
uint256 public S1;
uint256 public S2;
// State flags.
bool public operational;
bool public openForPublic;
// Library contract address.
address public mmLib;
function supportsToken(address token) public constant returns (bool);
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256);
function validateReserves() public view returns (bool);
function withdrawExcessReserves() public returns (uint256);
function initializeAfterTransfer() public returns (bool);
function initializeOnTransfer() public returns (bool);
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256);
}
/// @title Colu Local Currency + Market Maker factory contract.
/// @author Rotem Lev.
contract CurrencyFactory is Standard223Receiver, TokenHolder {
struct CurrencyStruct {
string name;
uint8 decimals;
uint256 totalSupply;
address owner;
address mmAddress;
}
// map of Market Maker owners: token address => currency struct
mapping (address => CurrencyStruct) public currencyMap;
// address of the deployed CLN contract (ERC20 Token)
address public clnAddress;
// address of the deployed elipse market maker contract
address public mmLibAddress;
address[] public tokens;
event MarketOpen(address indexed marketMaker);
event TokenCreated(address indexed token, address indexed owner);
// modifier to check if called by issuer of the token
modifier tokenIssuerOnly(address token, address owner) {
require(currencyMap[token].owner == owner);
_;
}
// modifier to only accept transferAndCall from CLN token
modifier CLNOnly() {
require(msg.sender == clnAddress);
_;
}
/// @dev constructor only reuires the address of the CLN token which must use the ERC20 interface
/// @param _mmLib address for the deployed market maker elipse contract
/// @param _clnAddress address for the deployed ERC20 CLN token
function CurrencyFactory(address _mmLib, address _clnAddress) public {
require(_mmLib != address(0));
require(_clnAddress != address(0));
mmLibAddress = _mmLib;
clnAddress = _clnAddress;
}
/// @dev create the MarketMaker and the CC token put all the CC token in the Market Maker reserve
/// @param _name string name for CC token that is created.
/// @param _symbol string symbol for CC token that is created.
/// @param _decimals uint8 percison for CC token that is created.
/// @param _totalSupply uint256 total supply of the CC token that is created.
function createCurrency(string _name,
string _symbol,
uint8 _decimals,
uint256 _totalSupply) public
returns (address) {
ColuLocalCurrency subToken = new ColuLocalCurrency(_name, _symbol, _decimals, _totalSupply);
EllipseMarketMaker newMarketMaker = new EllipseMarketMaker(mmLibAddress, clnAddress, subToken);
//set allowance
require(subToken.transfer(newMarketMaker, _totalSupply));
require(IEllipseMarketMaker(newMarketMaker).initializeAfterTransfer());
currencyMap[subToken] = CurrencyStruct({ name: _name, decimals: _decimals, totalSupply: _totalSupply, mmAddress: newMarketMaker, owner: msg.sender});
tokens.push(subToken);
TokenCreated(subToken, msg.sender);
return subToken;
}
/// @dev normal send cln to the market maker contract, sender must approve() before calling method. can only be called by owner
/// @dev sending CLN will return CC from the reserve to the sender.
/// @param _token address address of the cc token managed by this factory.
/// @param _clnAmount uint256 amount of CLN to transfer into the Market Maker reserve.
function insertCLNtoMarketMaker(address _token,
uint256 _clnAmount) public
tokenIssuerOnly(_token, msg.sender)
returns (uint256 _subTokenAmount) {
require(_clnAmount > 0);
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
require(ERC20(clnAddress).transferFrom(msg.sender, this, _clnAmount));
require(ERC20(clnAddress).approve(marketMakerAddress, _clnAmount));
_subTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(clnAddress, _clnAmount, _token);
require(ERC20(_token).transfer(msg.sender, _subTokenAmount));
}
/// @dev ERC223 transferAndCall, send cln to the market maker contract can only be called by owner (see MarketMaker)
/// @dev sending CLN will return CC from the reserve to the sender.
/// @param _token address address of the cc token managed by this factory.
function insertCLNtoMarketMaker(address _token) public
tokenPayable
CLNOnly
tokenIssuerOnly(_token, tkn.sender)
returns (uint256 _subTokenAmount) {
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
require(ERC20(clnAddress).approve(marketMakerAddress, tkn.value));
_subTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(clnAddress, tkn.value, _token);
require(ERC20(_token).transfer(tkn.sender, _subTokenAmount));
}
/// @dev normal send cc to the market maker contract, sender must approve() before calling method. can only be called by owner
/// @dev sending CC will return CLN from the reserve to the sender.
/// @param _token address address of the cc token managed by this factory.
/// @param _ccAmount uint256 amount of CC to transfer into the Market Maker reserve.
function extractCLNfromMarketMaker(address _token,
uint256 _ccAmount) public
tokenIssuerOnly(_token, msg.sender)
returns (uint256 _clnTokenAmount) {
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
require(ERC20(_token).transferFrom(msg.sender, this, _ccAmount));
require(ERC20(_token).approve(marketMakerAddress, _ccAmount));
_clnTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(_token, _ccAmount, clnAddress);
require(ERC20(clnAddress).transfer(msg.sender, _clnTokenAmount));
}
/// @dev ERC223 transferAndCall, send CC to the market maker contract can only be called by owner (see MarketMaker)
/// @dev sending CC will return CLN from the reserve to the sender.
function extractCLNfromMarketMaker() public
tokenPayable
tokenIssuerOnly(msg.sender, tkn.sender)
returns (uint256 _clnTokenAmount) {
address marketMakerAddress = getMarketMakerAddressFromToken(msg.sender);
require(ERC20(msg.sender).approve(marketMakerAddress, tkn.value));
_clnTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(msg.sender, tkn.value, clnAddress);
require(ERC20(clnAddress).transfer(tkn.sender, _clnTokenAmount));
}
/// @dev opens the Market Maker to recvice transactions from all sources.
/// @dev Request to transfer ownership of Market Maker contract to Owner instead of factory.
/// @param _token address address of the cc token managed by this factory.
function openMarket(address _token) public
tokenIssuerOnly(_token, msg.sender)
returns (bool) {
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
require(MarketMaker(marketMakerAddress).openForPublicTrade());
Ownable(marketMakerAddress).requestOwnershipTransfer(msg.sender);
MarketOpen(marketMakerAddress);
return true;
}
/// @dev implementation for standard 223 reciver.
/// @param _token address of the token used with transferAndCall.
function supportsToken(address _token) public constant returns (bool) {
return (clnAddress == _token || currencyMap[_token].totalSupply > 0);
}
/// @dev helper function to get the market maker address form token
/// @param _token address of the token used with transferAndCall.
function getMarketMakerAddressFromToken(address _token) public constant returns (address _marketMakerAddress) {
_marketMakerAddress = currencyMap[_token].mmAddress;
require(_marketMakerAddress != address(0));
}
}
/**
* The IssuanceFactory creates an issuance contract that accepts on one side CLN
* locks then up in an elipse market maker up to the supplied softcap
* and returns a CC token based on price that is derived form the two supplies and reserves of each
*/
/// @title Colu Issuance factoy with CLN for CC tokens.
/// @author Rotem Lev.
contract IssuanceFactory is CurrencyFactory {
using SafeMath for uint256;
uint256 public PRECISION;
struct IssuanceStruct {
uint256 hardcap;
uint256 reserve;
uint256 startTime;
uint256 endTime;
uint256 targetPrice;
uint256 clnRaised;
}
uint256 public totalCLNcustodian;
//map of Market Maker owners
mapping (address => IssuanceStruct) public issueMap;
// total supply of CLN
uint256 public CLNTotalSupply;
event CLNRaised(address indexed token, address indexed participant, uint256 amount);
event CLNRefunded(address indexed token, address indexed participant, uint256 amount);
event SaleFinalized(address indexed token, uint256 clnRaised);
// sale has begun based on time and status
modifier saleOpen(address _token) {
require(now >= issueMap[_token].startTime && issueMap[_token].endTime >= now);
require(issueMap[_token].clnRaised < issueMap[_token].hardcap);
_;
}
// sale is passed its endtime
modifier hasEnded(address _token) {
require(issueMap[_token].endTime < now);
_;
}
// sale considered successful when it raised equal to or more than the softcap
modifier saleWasSuccessfull(address _token) {
require(issueMap[_token].clnRaised >= issueMap[_token].reserve);
_;
}
// sale considerd failed when it raised less than the softcap
modifier saleHasFailed(address _token) {
require(issueMap[_token].clnRaised < issueMap[_token].reserve);
_;
}
// checks if the instance of market maker contract is closed for public
modifier marketClosed(address _token) {
require(!MarketMaker(currencyMap[_token].mmAddress).isOpenForPublic());
_;
}
/// @dev constructor
/// @param _mmLib address for the deployed elipse market maker contract
/// @param _clnAddress address for the deployed CLN ERC20 token
function IssuanceFactory(address _mmLib, address _clnAddress) public CurrencyFactory(_mmLib, _clnAddress) {
CLNTotalSupply = ERC20(_clnAddress).totalSupply();
PRECISION = IEllipseMarketMaker(_mmLib).PRECISION();
}
/// @dev createIssuance create local currency issuance sale
/// @param _startTime uint256 blocktime for sale start
/// @param _durationTime uint 256 duration of the sale
/// @param _hardcap uint CLN hardcap for issuance
/// @param _reserveAmount uint CLN reserve ammount
/// @param _name string name of the token
/// @param _symbol string symbol of the token
/// @param _decimals uint8 ERC20 decimals of local currency
/// @param _totalSupply uint total supply of the local currency
function createIssuance( uint256 _startTime,
uint256 _durationTime,
uint256 _hardcap,
uint256 _reserveAmount,
string _name,
string _symbol,
uint8 _decimals,
uint256 _totalSupply) public
returns (address) {
require(_startTime > now);
require(_durationTime > 0);
require(_hardcap > 0);
uint256 R2 = IEllipseMarketMaker(mmLibAddress).calcReserve(_reserveAmount, CLNTotalSupply, _totalSupply);
uint256 targetPrice = IEllipseMarketMaker(mmLibAddress).getPrice(_reserveAmount, R2, CLNTotalSupply, _totalSupply);
require(isValidIssuance(_hardcap, targetPrice, _totalSupply, R2));
address tokenAddress = super.createCurrency(_name, _symbol, _decimals, _totalSupply);
addToMap(tokenAddress, _startTime, _startTime + _durationTime, _hardcap, _reserveAmount, targetPrice);
return tokenAddress;
}
/// @dev internal helper to add currency data to the issuance map
/// @param _token address token address for this issuance (same as CC adress)
/// @param _startTime uint256 blocktime for sale start
/// @param _endTime uint256 blocktime for sale end
/// @param _hardcap uint256 sale hardcap
/// @param _reserveAmount uint256 sale softcap
/// @param _targetPrice uint256 sale CC price per CLN if it were to pass the softcap
function addToMap(address _token,
uint256 _startTime,
uint256 _endTime,
uint256 _hardcap,
uint256 _reserveAmount,
uint256 _targetPrice) private {
issueMap[_token] = IssuanceStruct({ hardcap: _hardcap,
reserve: _reserveAmount,
startTime: _startTime,
endTime: _endTime,
clnRaised: 0,
targetPrice: _targetPrice});
}
/// @dev participate in the issuance of the local currency
/// @param _token address token address for this issuance (same as CC adress)
/// @param _clnAmount uint256 amount of CLN to try and participate
/// @return releaseAmount uint ammount of CC tokens released and transfered to sender
function participate(address _token,
uint256 _clnAmount) public
saleOpen(_token)
returns (uint256 releaseAmount) {
require(_clnAmount > 0);
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
// how much do we need to actually send to market maker of the incomming amount
// and how much of the amount can participate
uint256 transferToReserveAmount;
uint256 participationAmount;
(transferToReserveAmount, participationAmount) = getParticipationAmounts(_clnAmount, _token);
// send what we need to the market maker for reserve
require(ERC20(clnAddress).transferFrom(msg.sender, this, participationAmount));
approveAndChange(clnAddress, _token, transferToReserveAmount, marketMakerAddress);
// pay back to participant with the participated amount * price
releaseAmount = participationAmount.mul(issueMap[_token].targetPrice).div(PRECISION);
issueMap[_token].clnRaised = issueMap[_token].clnRaised.add(participationAmount);
totalCLNcustodian = totalCLNcustodian.add(participationAmount);
CLNRaised(_token, msg.sender, participationAmount);
require(ERC20(_token).transfer(msg.sender, releaseAmount));
}
/// @dev Participate in the CLN based issuance (for contract)
/// @param _token address token address for this issuance (same as CC adress)
function participate(address _token)
public
tokenPayable
saleOpen(_token)
returns (uint256 releaseAmount) {
require(tkn.value > 0 && msg.sender == clnAddress);
//check if we need to send cln to mm or save it
uint256 transferToReserveAmount;
uint256 participationAmount;
(transferToReserveAmount, participationAmount) = getParticipationAmounts(tkn.value, _token);
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
approveAndChange(clnAddress, _token, transferToReserveAmount, marketMakerAddress);
// transfer only what we need
releaseAmount = participationAmount.mul(issueMap[_token].targetPrice).div(PRECISION);
issueMap[_token].clnRaised = issueMap[_token].clnRaised.add(participationAmount);
totalCLNcustodian = totalCLNcustodian.add(participationAmount);
CLNRaised(_token, tkn.sender, participationAmount);
require(ERC20(_token).transfer(tkn.sender, releaseAmount));
// send CLN change to the participent since its transferAndCall
if (tkn.value > participationAmount)
require(ERC20(clnAddress).transfer(tkn.sender, tkn.value.sub(participationAmount)));
}
/// @dev called by the creator to finish the sale, open the market maker and get his tokens
/// @dev can only be called after the sale end time and if the sale passed the softcap
/// @param _token address token address for this issuance (same as CC adress)
function finalize(address _token) public
tokenIssuerOnly(_token, msg.sender)
hasEnded(_token)
saleWasSuccessfull(_token)
marketClosed(_token)
returns (bool) {
// move all CC and CLN that were raised and not in the reserves to the issuer
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
uint256 clnAmount = issueMap[_token].clnRaised.sub(issueMap[_token].reserve);
totalCLNcustodian = totalCLNcustodian.sub(clnAmount);
uint256 ccAmount = ERC20(_token).balanceOf(this);
// open Market Maker for public trade.
require(MarketMaker(marketMakerAddress).openForPublicTrade());
require(ERC20(_token).transfer(msg.sender, ccAmount));
require(ERC20(clnAddress).transfer(msg.sender, clnAmount));
SaleFinalized(_token, issueMap[_token].clnRaised);
return true;
}
/// @dev Give back CC and get a refund back in CLN,
/// dev can only be called after sale ended and the softcap not reached
/// @param _token address token address for this issuance (same as CC adress)
/// @param _ccAmount uint256 amount of CC to try and refund
function refund(address _token,
uint256 _ccAmount) public
hasEnded(_token)
saleHasFailed(_token)
marketClosed(_token)
returns (bool) {
require(_ccAmount > 0);
// exchange CC for CLN throuh Market Maker
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
require(ERC20(_token).transferFrom(msg.sender, this, _ccAmount));
uint256 factoryCCAmount = ERC20(_token).balanceOf(this);
require(ERC20(_token).approve(marketMakerAddress, factoryCCAmount));
require(MarketMaker(marketMakerAddress).change(_token, factoryCCAmount, clnAddress) > 0);
uint256 returnAmount = _ccAmount.mul(PRECISION).div(issueMap[_token].targetPrice);
issueMap[_token].clnRaised = issueMap[_token].clnRaised.sub(returnAmount);
totalCLNcustodian = totalCLNcustodian.sub(returnAmount);
CLNRefunded(_token, msg.sender, returnAmount);
require(ERC20(clnAddress).transfer(msg.sender, returnAmount));
return true;
}
/// @dev Give back CC and get a refund back in CLN,
/// dev can only be called after sale ended and the softcap not
function refund() public
tokenPayable
hasEnded(msg.sender)
saleHasFailed(msg.sender)
marketClosed(msg.sender)
returns (bool) {
require(tkn.value > 0);
// if we have CC time to thorw it to the Market Maker
address marketMakerAddress = getMarketMakerAddressFromToken(msg.sender);
uint256 factoryCCAmount = ERC20(msg.sender).balanceOf(this);
require(ERC20(msg.sender).approve(marketMakerAddress, factoryCCAmount));
require(MarketMaker(marketMakerAddress).change(msg.sender, factoryCCAmount, clnAddress) > 0);
uint256 returnAmount = tkn.value.mul(PRECISION).div(issueMap[msg.sender].targetPrice);
issueMap[msg.sender].clnRaised = issueMap[msg.sender].clnRaised.sub(returnAmount);
totalCLNcustodian = totalCLNcustodian.sub(returnAmount);
CLNRefunded(msg.sender, tkn.sender, returnAmount);
require(ERC20(clnAddress).transfer(tkn.sender, returnAmount));
return true;
}
/// @dev normal send cln to the market maker contract, sender must approve() before calling method. can only be called by owner
/// @dev sending CLN will return CC from the reserve to the sender.
function insertCLNtoMarketMaker(address, uint256) public returns (uint256) {
require(false);
return 0;
}
/// @dev ERC223 transferAndCall, send cln to the market maker contract can only be called by owner (see MarketMaker)
/// @dev sending CLN will return CC from the reserve to the sender.
function insertCLNtoMarketMaker(address) public returns (uint256) {
require(false);
return 0;
}
/// @dev normal send CC to the market maker contract, sender must approve() before calling method. can only be called by owner
/// @dev sending CC will return CLN from the reserve to the sender.
function extractCLNfromMarketMaker(address, uint256) public returns (uint256) {
require(false);
return 0;
}
/// @dev ERC223 transferAndCall, send CC to the market maker contract can only be called by owner (see MarketMaker)
/// @dev sending CC will return CLN from the reserve to the sender.
function extractCLNfromMarketMaker() public returns (uint256) {
require(false);
return 0;
}
/// @dev opens the Market Maker to recvice transactions from all sources.
/// @dev Request to transfer ownership of Market Maker contract to Owner instead of factory.
function openMarket(address) public returns (bool) {
require(false);
return false;
}
/// @dev checks if the parameters that were sent to the create are valid for a promised price and buyback
/// @param _hardcap uint256 CLN hardcap for issuance
/// @param _price uint256 computed through the market maker using the supplies and reserves
/// @param _S2 uint256 supply of the CC token
/// @param _R2 uint256 reserve of the CC token
function isValidIssuance(uint256 _hardcap,
uint256 _price,
uint256 _S2,
uint256 _R2) public view
returns (bool) {
return (_S2 > _R2 && _S2.sub(_R2).mul(PRECISION) >= _hardcap.mul(_price));
}
/// @dev helper function to fetch market maker contract address deploed with the CC
/// @param _token address token address for this issuance (same as CC adress)
function getMarketMakerAddressFromToken(address _token) public constant returns (address) {
return currencyMap[_token].mmAddress;
}
/// @dev helper function to approve tokens for market maker and then change tokens
/// @param _token address deployed ERC20 token address to spend
/// @param _token2 address deployed ERC20 token address to buy
/// @param _amount uint256 amount of _token to spend
/// @param _marketMakerAddress address for the deploed market maker with this CC
function approveAndChange(address _token,
address _token2,
uint256 _amount,
address _marketMakerAddress) private
returns (uint256) {
if (_amount > 0) {
require(ERC20(_token).approve(_marketMakerAddress, _amount));
return MarketMaker(_marketMakerAddress).change(_token, _amount, _token2);
}
return 0;
}
/// @dev helper function participation with CLN
/// @dev returns the amount to send to reserve and amount to participate
/// @param _clnAmount amount of cln the user wants to participate with
/// @param _token address token address for this issuance (same as CC adress)
/// @return {
/// "transferToReserveAmount": ammount of CLN to transfer to reserves
/// "participationAmount": ammount of CLN that the sender will participate with in the sale
///}
function getParticipationAmounts(uint256 _clnAmount,
address _token) private view
returns (uint256 transferToReserveAmount, uint256 participationAmount) {
uint256 clnRaised = issueMap[_token].clnRaised;
uint256 reserve = issueMap[_token].reserve;
uint256 hardcap = issueMap[_token].hardcap;
participationAmount = SafeMath.min256(_clnAmount, hardcap.sub(clnRaised));
if (reserve > clnRaised) {
transferToReserveAmount = SafeMath.min256(participationAmount, reserve.sub(clnRaised));
}
}
/// @dev Returns total number of issuances after filters are applied.
/// @dev this function is gas wasteful so do not call this from a state changing transaction
/// @param _pending include pending currency issuances.
/// @param _started include started currency issuances.
/// @param _successful include successful and ended currency issuances.
/// @param _failed include failed and ended currency issuances.
/// @return Total number of currency issuances after filters are applied.
function getIssuanceCount(bool _pending, bool _started, bool _successful, bool _failed)
public
view
returns (uint _count)
{
for (uint i = 0; i < tokens.length; i++) {
IssuanceStruct memory issuance = issueMap[tokens[i]];
if ((_pending && issuance.startTime > now)
|| (_started && now >= issuance.startTime && issuance.endTime >= now && issuance.clnRaised < issuance.hardcap)
|| (_successful && issuance.endTime < now && issuance.clnRaised >= issuance.reserve)
|| (_successful && issuance.endTime >= now && issuance.clnRaised == issuance.hardcap)
|| (_failed && issuance.endTime < now && issuance.clnRaised < issuance.reserve))
_count += 1;
}
}
/// @dev Returns list of issuance ids (allso the token address of the issuance) in defined range after filters are applied.
/// @dev _offset and _limit parameters are intended for pagination
/// @dev this function is gas wasteful so do not call this from a state changing transaction
/// @param _pending include pending currency issuances.
/// @param _started include started currency issuances.
/// @param _successful include successful and ended currency issuances.
/// @param _failed include failed and ended currency issuances.
/// @param _offset index start position of issuance ids array.
/// @param _limit maximum number of issuance ids to return.
/// @return Returns array of token adresses for issuance.
function getIssuanceIds(bool _pending, bool _started, bool _successful, bool _failed, uint _offset, uint _limit)
public
view
returns (address[] _issuanceIds)
{
require(_limit >= 1);
require(_limit <= 100);
_issuanceIds = new address[](_limit);
uint filteredIssuancesCount = 0;
uint retrieveIssuancesCount = 0;
for (uint i = 0; i < tokens.length; i++) {
IssuanceStruct memory issuance = issueMap[tokens[i]];
if ((_pending && issuance.startTime > now)
|| (_started && now >= issuance.startTime && issuance.endTime >= now && issuance.clnRaised < issuance.hardcap)
|| (_successful && issuance.endTime < now && issuance.clnRaised >= issuance.reserve)
|| (_successful && issuance.endTime >= now && issuance.clnRaised == issuance.hardcap)
|| (_failed && issuance.endTime < now && issuance.clnRaised < issuance.reserve))
{
if (filteredIssuancesCount >= _offset) {
_issuanceIds[retrieveIssuancesCount] = tokens[i];
retrieveIssuancesCount += 1;
}
if (retrieveIssuancesCount == _limit) {
return _issuanceIds;
}
filteredIssuancesCount += 1;
}
}
if (retrieveIssuancesCount < _limit) {
address[] memory _issuanceIdsTemp = new address[](retrieveIssuancesCount);
for (i = 0; i < retrieveIssuancesCount; i++) {
_issuanceIdsTemp[i] = _issuanceIds[i];
}
return _issuanceIdsTemp;
}
}
/// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens.
/// @param _tokenAddress address The address of the ERC20 contract.
/// @param _amount uint256 The amount of tokens to be transferred.
function transferAnyERC20Token(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) {
if (_tokenAddress == clnAddress) {
uint256 excessCLN = ERC20(clnAddress).balanceOf(this).sub(totalCLNcustodian);
require(excessCLN <= _amount);
}
if (issueMap[_tokenAddress].hardcap > 0) {
require(MarketMaker(currencyMap[_tokenAddress].mmAddress).isOpenForPublic());
}
return ERC20(_tokenAddress).transfer(owner, _amount);
}
} | Participate in the CLN based issuance (for contract) _token address token address for this issuance (same as CC adress)check if we need to send cln to mm or save it transfer only what we need send CLN change to the participent since its transferAndCall | function participate(address _token)
public
tokenPayable
saleOpen(_token)
returns (uint256 releaseAmount) {
require(tkn.value > 0 && msg.sender == clnAddress);
uint256 transferToReserveAmount;
uint256 participationAmount;
(transferToReserveAmount, participationAmount) = getParticipationAmounts(tkn.value, _token);
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
approveAndChange(clnAddress, _token, transferToReserveAmount, marketMakerAddress);
releaseAmount = participationAmount.mul(issueMap[_token].targetPrice).div(PRECISION);
issueMap[_token].clnRaised = issueMap[_token].clnRaised.add(participationAmount);
totalCLNcustodian = totalCLNcustodian.add(participationAmount);
CLNRaised(_token, tkn.sender, participationAmount);
require(ERC20(_token).transfer(tkn.sender, releaseAmount));
if (tkn.value > participationAmount)
require(ERC20(clnAddress).transfer(tkn.sender, tkn.value.sub(participationAmount)));
}
| 1,809,712 |
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "openzeppelin-solidity/contracts/utils/Address.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "../configuration/LendingPoolAddressesProvider.sol";
import "../configuration/LendingPoolParametersProvider.sol";
import "../configuration/NetworkMetadataProvider.sol";
import "../tokenization/AToken.sol";
import "../libraries/CoreLibrary.sol";
import "../libraries/WadRayMath.sol";
import "../interfaces/IFeeProvider.sol";
import "../flashloan/interfaces/IFlashLoanReceiver.sol";
import "./LendingPoolCore.sol";
import "./LendingPoolDataProvider.sol";
/*************************************************************************************
@title LiquidationManager contract
@author Aave
@notice Implements the actions of the LendingPool, and exposes accessory methods to access the core information
*************************************************************************************/
contract LendingPoolLiquidationManager is ReentrancyGuard {
using SafeMath for uint256;
using WadRayMath for uint256;
using Address for address payable;
LendingPoolAddressesProvider public addressesProvider;
LendingPoolCore core;
LendingPoolDataProvider dataProvider;
LendingPoolParametersProvider parametersProvider;
uint256 constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 50;
enum LiquidationErrors {
NO_ERROR,
NO_COLLATERAL_AVAILABLE,
COLLATERAL_CANNOT_BE_LIQUIDATED,
CURRRENCY_NOT_BORROWED,
HEALTH_FACTOR_ABOVE_THRESHOLD,
NOT_ENOUGH_LIQUIDITY
}
event LiquidationCompleted();
struct LiquidationCallLocalVars{
uint256 healthFactor;
uint256 userCollateralBalance;
uint256 userCompoundedBorrowBalance;
uint256 borrowBalanceIncrease;
uint256 maxPrincipalAmountToLiquidate;
uint256 actualAmountToLiquidate;
uint256 liquidationRatio;
uint256 collateralPrice;
uint256 principalCurrencyPrice;
uint256 maxAmountCollateralToLiquidate;
bool isCollateralEnabled;
}
/**
* @notice implements loan liquidation
* @dev _receiveAToken allows the liquidators to receive the aTokens, instead of the underlying asset.
*/
function liquidationCall(address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken)
external
payable
returns(uint256, string memory)
{
LiquidationCallLocalVars memory vars;
(,,,,,vars.healthFactor) = dataProvider.calculateUserGlobalData(_user);
if(vars.healthFactor >= dataProvider.getHealthFactorLiquidationThreshold()){
return (uint256(LiquidationErrors.HEALTH_FACTOR_ABOVE_THRESHOLD), "Health factor is not below the threshold");
}
vars.userCollateralBalance = dataProvider.getUserUnderlyingAssetBalance(_collateral, _user);
//if _user hasn't deposited this specific collateral, nothing can be liquidated
if(vars.userCollateralBalance == 0) {
return (uint256(LiquidationErrors.NO_COLLATERAL_AVAILABLE), "Invalid collateral to liquidate");
}
vars.isCollateralEnabled = core.isReserveUsageAsCollateralEnabled(_collateral) ||
!core.isUserUseReserveAsCollateralEnabled(_collateral, _user);
//if _collateral isn't enabled as collateral by _user, it cannot be liquidated
if(!vars.isCollateralEnabled) {
return (uint256(LiquidationErrors.COLLATERAL_CANNOT_BE_LIQUIDATED), "The collateral chosen cannot be liuquidated");
}
//if the user hasn't borrowed the specific currency defined by _reserve, it cannot be liquidated
(,vars.userCompoundedBorrowBalance,vars.borrowBalanceIncrease) = core.getUserBorrowBalances(_reserve, _user);
if(vars.userCompoundedBorrowBalance == 0){
return (uint256(LiquidationErrors.CURRRENCY_NOT_BORROWED), "User did not borrow the specified currency");
}
//all clear - calculate the max principal amount that can be liquidated
vars.maxPrincipalAmountToLiquidate = vars.userCompoundedBorrowBalance.mul(LIQUIDATION_CLOSE_FACTOR_PERCENT).div(100);
vars.actualAmountToLiquidate = _purchaseAmount > vars.maxPrincipalAmountToLiquidate
?
vars.maxPrincipalAmountToLiquidate
:
_purchaseAmount;
(uint256 maxCollateralToLiquidate,
uint256 principalAmountNeeded) = calculateAvailableCollateralToLiquidate(_collateral, _reserve, vars.actualAmountToLiquidate, vars.userCollateralBalance);
//if principalAmountNeeded < vars.ActualAmountToLiquidate, there isn't enough
//of _collateral to cover the actual amount that is being liquidated, hence we liquidate
//a smaller amount
if(principalAmountNeeded < vars.actualAmountToLiquidate){
vars.actualAmountToLiquidate = principalAmountNeeded;
}
//if liquidator reclaims the underlying asset, we make sure there is enough available collateral in the reserve
if(!_receiveAToken){
uint256 currentAvailableCollateral = core.getReserveAvailableLiquidity(_collateral);
if(currentAvailableCollateral >= maxCollateralToLiquidate){
return (uint256(LiquidationErrors.NOT_ENOUGH_LIQUIDITY), "There isn't enough liquidity available to liquidate");
}
}
//update principal reserve data
core.updateReserveCumulativeIndexes(_reserve);
CoreLibrary.InterestRateMode borrowRateMode = core.getUserCurrentBorrowRateMode(_reserve,_user);
core.increaseReserveTotalLiquidity(_reserve, vars.borrowBalanceIncrease);
if (borrowRateMode == CoreLibrary.InterestRateMode.FIXED) {
uint256 currentFixedRate = core.getUserCurrentFixedBorrowRate(_reserve, _user);
core.decreaseReserveTotalBorrowsFixedAndUpdateAverageRate(_reserve, vars.actualAmountToLiquidate.sub(vars.borrowBalanceIncrease), currentFixedRate);
} else {
core.decreaseReserveTotalBorrowsVariable(_reserve, vars.actualAmountToLiquidate.sub(vars.borrowBalanceIncrease));
}
core.updateReserveInterestRates(_reserve);
core.setReserveLastUpdate(_reserve);
//step 3: update user borrow data
core.decreaseUserPrincipalBorrowBalance(_reserve, _user, vars.actualAmountToLiquidate.sub(vars.borrowBalanceIncrease));
core.setUserLastUpdate(_reserve,_user);
//update collateral reserve
core.updateReserveCumulativeIndexes(_collateral);
AToken collateralAtoken = AToken(core.getReserveATokenAddress(_collateral));
//calculating aToken equivalent amount from vars.
uint256 aTokenCollateralToLiquidate = collateralAtoken.underlyingAmountToATokenAmount(maxCollateralToLiquidate);
//if liquidator reclaims the aToken, he receives the equivalent atoken amount
if(_receiveAToken) {
collateralAtoken.transferOnLiquidation(_user, msg.sender, aTokenCollateralToLiquidate);
}
else { //otherwise receives the underlying asset
//burn the equivalent amount of atoken
collateralAtoken.burnOnLiquidation(_user, aTokenCollateralToLiquidate);
core.decreaseReserveTotalLiquidity(_collateral, maxCollateralToLiquidate);
core.updateReserveInterestRates(_collateral);
core.transferToUser(_collateral, msg.sender, maxCollateralToLiquidate);
}
core.setReserveLastUpdate(_collateral);
//transfers the principal currency to the pool
core.transferToReserve.value(msg.value)(_reserve, msg.sender, vars.actualAmountToLiquidate);
return (uint256(LiquidationErrors.NO_ERROR), "No errors");
}
struct AvailableCollateralToLiquidateLocalVars{
uint256 userCompoundedBorrowBalance;
uint256 liquidationDiscount;
uint256 collateralPrice;
uint256 principalCurrencyPrice;
uint256 maxAmountCollateralToLiquidate;
}
/**
* @notice calculates how much of a specific collateral can be liquidated, given
* a certain amount of principal currency.
* @dev this function needs to be called after all the checks to validate the liquidation
* have been performed, otherwise it might fail.
*/
function calculateAvailableCollateralToLiquidate(
address _collateral,
address _principal,
uint256 _purchaseAmount,
uint256 _userCollateralBalance) internal view returns(uint256 collateralAmount, uint256 principalAmountNeeded) {
collateralAmount = 0;
principalAmountNeeded = 0;
IPriceOracle oracle = IPriceOracle(addressesProvider.getPriceOracle());
AvailableCollateralToLiquidateLocalVars memory vars;
vars.collateralPrice = oracle.getAssetPrice(_collateral);
vars.principalCurrencyPrice = oracle.getAssetPrice(_principal);
vars.liquidationDiscount = core.getReserveLiquidationDiscount(_collateral);
//this is the maximum possible amount of the selected collateral that can be liquidated, given the
//max amount of principal currency that is available for liquidation.
vars.maxAmountCollateralToLiquidate = vars.principalCurrencyPrice.mul(_purchaseAmount)
.div(vars.collateralPrice)
.mul(vars.liquidationDiscount)
.div(100);
if(vars.maxAmountCollateralToLiquidate > _userCollateralBalance) {
collateralAmount = _userCollateralBalance;
principalAmountNeeded = vars.collateralPrice
.mul(collateralAmount)
.div(vars.principalCurrencyPrice)
.mul(100)
.div(vars.liquidationDiscount);
}
else{
collateralAmount = vars.maxAmountCollateralToLiquidate;
principalAmountNeeded = _purchaseAmount;
}
return (collateralAmount, principalAmountNeeded);
}
} | implements loan liquidation _receiveAToken allows the liquidators to receive the aTokens, instead of the underlying asset./if _user hasn't deposited this specific collateral, nothing can be liquidatedif _collateral isn't enabled as collateral by _user, it cannot be liquidatedif liquidator reclaims the underlying asset, we make sure there is enough available collateral in the reserveif liquidator reclaims the aToken, he receives the equivalent atoken amount | function liquidationCall(address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken)
external
payable
returns(uint256, string memory)
{
LiquidationCallLocalVars memory vars;
(,,,,,vars.healthFactor) = dataProvider.calculateUserGlobalData(_user);
if(vars.healthFactor >= dataProvider.getHealthFactorLiquidationThreshold()){
return (uint256(LiquidationErrors.HEALTH_FACTOR_ABOVE_THRESHOLD), "Health factor is not below the threshold");
}
vars.userCollateralBalance = dataProvider.getUserUnderlyingAssetBalance(_collateral, _user);
if(vars.userCollateralBalance == 0) {
return (uint256(LiquidationErrors.NO_COLLATERAL_AVAILABLE), "Invalid collateral to liquidate");
}
vars.isCollateralEnabled = core.isReserveUsageAsCollateralEnabled(_collateral) ||
!core.isUserUseReserveAsCollateralEnabled(_collateral, _user);
if(!vars.isCollateralEnabled) {
return (uint256(LiquidationErrors.COLLATERAL_CANNOT_BE_LIQUIDATED), "The collateral chosen cannot be liuquidated");
}
if(vars.userCompoundedBorrowBalance == 0){
return (uint256(LiquidationErrors.CURRRENCY_NOT_BORROWED), "User did not borrow the specified currency");
}
vars.actualAmountToLiquidate = _purchaseAmount > vars.maxPrincipalAmountToLiquidate
?
vars.maxPrincipalAmountToLiquidate
:
_purchaseAmount;
(uint256 maxCollateralToLiquidate,
uint256 principalAmountNeeded) = calculateAvailableCollateralToLiquidate(_collateral, _reserve, vars.actualAmountToLiquidate, vars.userCollateralBalance);
if(principalAmountNeeded < vars.actualAmountToLiquidate){
vars.actualAmountToLiquidate = principalAmountNeeded;
}
if(!_receiveAToken){
uint256 currentAvailableCollateral = core.getReserveAvailableLiquidity(_collateral);
if(currentAvailableCollateral >= maxCollateralToLiquidate){
return (uint256(LiquidationErrors.NOT_ENOUGH_LIQUIDITY), "There isn't enough liquidity available to liquidate");
}
}
CoreLibrary.InterestRateMode borrowRateMode = core.getUserCurrentBorrowRateMode(_reserve,_user);
core.increaseReserveTotalLiquidity(_reserve, vars.borrowBalanceIncrease);
if (borrowRateMode == CoreLibrary.InterestRateMode.FIXED) {
uint256 currentFixedRate = core.getUserCurrentFixedBorrowRate(_reserve, _user);
core.decreaseReserveTotalBorrowsFixedAndUpdateAverageRate(_reserve, vars.actualAmountToLiquidate.sub(vars.borrowBalanceIncrease), currentFixedRate);
core.decreaseReserveTotalBorrowsVariable(_reserve, vars.actualAmountToLiquidate.sub(vars.borrowBalanceIncrease));
}
core.updateReserveInterestRates(_reserve);
core.setReserveLastUpdate(_reserve);
core.setUserLastUpdate(_reserve,_user);
AToken collateralAtoken = AToken(core.getReserveATokenAddress(_collateral));
if(_receiveAToken) {
collateralAtoken.transferOnLiquidation(_user, msg.sender, aTokenCollateralToLiquidate);
}
core.decreaseReserveTotalLiquidity(_collateral, maxCollateralToLiquidate);
core.updateReserveInterestRates(_collateral);
core.transferToUser(_collateral, msg.sender, maxCollateralToLiquidate);
}
core.setReserveLastUpdate(_collateral);
core.transferToReserve.value(msg.value)(_reserve, msg.sender, vars.actualAmountToLiquidate);
return (uint256(LiquidationErrors.NO_ERROR), "No errors");
| 6,422,218 |
// SPDX-License-Identifier: Unlicensed
pragma solidity >=0.6.12; // =>0.8.7
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;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
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;
}
}
abstract contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @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;
}
function getUnlockTime() public view returns (uint256) {
return _lockTime;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @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
);
}
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);
}
}
}
}
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"
);
}
}
}
contract MasterChedda is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
address playerAddy;
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
struct PoolInfo {
uint256 lastRewardBlock; // Last block number that Cheddas distribution occurs.
uint256 accCheddaPerShare; // Accumulated Cheddas per share, times 1e12. See below.
}
// The Chedda TOKEN!
IERC20 public Chedda;
// Chedda tokens created per block.
uint256 public CheddaPerBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
uint256 public startBlock;
UserInfo[] public UsersInfo;
address public dev1;
address public dev2;
address public dev3;
// Deposit fee in basis points
uint256 public depositFeeBP = 300; //3%
// Withdraw fee in basis points
uint256 public withdrawFeeBP = 300; //3%
// Claim fee in basis points
uint256 public HarvestfeeBP = 1000; //10%
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event SetDevs(address dev1, address dev2, address dev3);
event SetDepositFee(uint256 depositFeeBP);
event SetHarvestfee(uint256 HarvestfeeBP);
event NewCheddaPerBlock(uint256 rewardPerBlock);
event SetWithdrawFee(uint256 withdrawFeeBP);
constructor(
IERC20 _Chedda,
uint256 _CheddaPerBlock,
uint256 _startBlock
) {
Chedda = _Chedda;
CheddaPerBlock = _CheddaPerBlock;
startBlock = _startBlock;
poolInfo.push(
PoolInfo({lastRewardBlock: startBlock, accCheddaPerShare: 0})
);
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to)
public
pure
returns (uint256)
{
return _to.sub(_from);
}
// View function to see pending Cheddas on frontend.
function pendingCheddas() public view returns (uint256) {
uint256 pendingCheddasTotal;
for (uint256 i = 0; i < UsersInfo.length; i++) {
pendingCheddasTotal += pendingChedda(UsersInfo[i].playerAddy);
}
return pendingCheddasTotal;
}
// totalDeposits is the total Cheddah deposited by users
function totalDeposits() public view returns (uint256) {
uint256 pendingCheddasTotal;
for (uint256 i = 0; i < UsersInfo.length; i++) {
UserInfo storage user = userInfo[0][UsersInfo[i].playerAddy];
pendingCheddasTotal += user.amount;
}
return pendingCheddasTotal;
}
// effectiveRewards is the total Cheddah rewards remaining in contract
function effectiveRewards() public view returns (uint256) {
uint256 effectiveReward=0;
if (Chedda.balanceOf(address(this)) > pendingCheddas() + totalDeposits() )
{
effectiveReward = Chedda
.balanceOf(address(this))
.sub(pendingCheddas())
.sub(totalDeposits());
}
return effectiveReward;
}
function pendingChedda(address _user) public view returns (uint256) {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_user];
uint256 accCheddaPerShare = pool.accCheddaPerShare;
uint256 lpSupply = totalDeposits();
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(
pool.lastRewardBlock,
block.number
);
uint256 CheddaReward = multiplier.mul(CheddaPerBlock);
accCheddaPerShare = accCheddaPerShare.add(
CheddaReward.mul(1e12).div(lpSupply)
);
}
return
user.amount.mul(accCheddaPerShare).div(1e12).sub(user.rewardDebt);
}
function updateCheddaPerBlock(uint256 _CheddaPerBlock) external onlyOwner {
CheddaPerBlock = _CheddaPerBlock;
emit NewCheddaPerBlock(_CheddaPerBlock);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool() public {
PoolInfo storage pool = poolInfo[0];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = totalDeposits();
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 CheddaReward = multiplier.mul(CheddaPerBlock);
pool.accCheddaPerShare = pool.accCheddaPerShare.add(
CheddaReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
// Stake Chedda tokens
function enterStaking(uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
if (user.playerAddy != msg.sender) {
user.playerAddy = msg.sender;
UsersInfo.push(user);
}
updatePool();
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.accCheddaPerShare)
.div(1e12)
.sub(user.rewardDebt);
if (pending > 0) {
uint256 Harvestfee = (pending * HarvestfeeBP) / 10000;
Chedda.transfer(address(msg.sender), pending);
Chedda.transfer(dev3, Harvestfee);
}
}
if (_amount > 0) {
uint256 depositFee = (_amount * depositFeeBP) / 10000;
uint256 depositAmount = _amount.sub(depositFee);
user.amount = user.amount.add(depositAmount);
Chedda.safeTransferFrom(
address(msg.sender),
address(this),
depositAmount
);
Chedda.safeTransferFrom(address(msg.sender), dev2, depositFee);
}
user.rewardDebt = user.amount.mul(pool.accCheddaPerShare).div(1e12);
emit Deposit(msg.sender, 0, _amount);
}
function leaveStaking(uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool();
uint256 pending = user.amount.mul(pool.accCheddaPerShare).div(1e12).sub(
user.rewardDebt
);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 WithdrawFee = (_amount * withdrawFeeBP) / 10000;
Chedda.safeTransfer(address(msg.sender), _amount.sub(WithdrawFee));
Chedda.safeTransfer(dev1, WithdrawFee);
}
if (pending > 0) {
uint256 HarvestBP = (pending * HarvestfeeBP) / 10000;
Chedda.transfer(address(msg.sender), pending);
Chedda.transfer(dev3, HarvestBP);
}
user.rewardDebt = user.amount.mul(pool.accCheddaPerShare).div(1e12);
emit Withdraw(msg.sender, 0, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw() public nonReentrant {
UserInfo storage user = userInfo[0][msg.sender];
uint256 WithdrawFee = (user.amount * withdrawFeeBP) / 10000;
Chedda.safeTransfer(address(msg.sender), user.amount.sub(WithdrawFee));
Chedda.safeTransfer(dev1, WithdrawFee);
emit EmergencyWithdraw(msg.sender, 0, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
function getPoolInfo()
public
view
returns (uint256 lastRewardBlock, uint256 accCheddaPerShare)
{
return (poolInfo[0].lastRewardBlock, poolInfo[0].accCheddaPerShare);
}
function ChangedevAddress(address _dev1, address _dev2, address _dev3) external onlyOwner {
require(_dev1 != address(0), "!nonzero");
require(_dev2 != address(0), "!nonzero");
require(_dev3 != address(0), "!nonzero");
dev1 = _dev1;
dev2 = _dev2;
dev3 = _dev3;
emit SetDevs(_dev1, _dev2, _dev3);
}
function ChangedepositFeeBP(uint256 _depositFeeBP) external onlyOwner {
depositFeeBP = _depositFeeBP;
emit SetDepositFee(_depositFeeBP);
}
function ChangewithdrawFeeBP(uint256 _withdrawFeeBP) external onlyOwner {
withdrawFeeBP = _withdrawFeeBP;
emit SetWithdrawFee(_withdrawFeeBP);
}
function ChangeHarvestfeeBP(uint256 _HarvestfeeBP) external onlyOwner {
require(_HarvestfeeBP < 2000, "max 20%"); // to Prevent any sort of Honypot
HarvestfeeBP = _HarvestfeeBP;
emit SetHarvestfee(_HarvestfeeBP);
}
} | View function to see pending Cheddas on frontend. | function pendingCheddas() public view returns (uint256) {
uint256 pendingCheddasTotal;
for (uint256 i = 0; i < UsersInfo.length; i++) {
pendingCheddasTotal += pendingChedda(UsersInfo[i].playerAddy);
}
return pendingCheddasTotal;
}
| 13,613,302 |
./full_match/80001/0xbDD3384f1822E1209Dc96D6f78f82720ab699e89/sources/contracts/WAYSPACE.sol | Returns the Uniform Resource Identifier (URI) for `tokenId` token. | function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
return
}
| 9,466,989 |
/*
Copyright 2019 Wanchain Foundation.
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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity 0.4.26;
/**
* Math operations with safety checks
*/
import "../components/Halt.sol";
import "./QuotaStorage.sol";
import "../interfaces/IOracle.sol";
interface _ITokenManager {
function getAncestorSymbol(uint id) external view returns (string symbol, uint8 decimals);
}
interface _IStoremanGroup {
function getDeposit(bytes32 id) external view returns(uint deposit);
}
interface IDebtOracle {
function isDebtClean(bytes32 storemanGroupId) external view returns (bool);
}
contract QuotaDelegate is QuotaStorage, Halt {
modifier checkMinValue(uint tokenId, uint value) {
if (fastCrossMinValue > 0) {
string memory symbol;
uint decimals;
(symbol, decimals) = getTokenAncestorInfo(tokenId);
uint price = getPrice(symbol);
require(price > 0, "Price is zero");
uint count = fastCrossMinValue.mul(10**decimals).div(price);
require(value >= count, "value too small");
}
_;
}
/// @notice config params for owner
/// @param _priceOracleAddr token price oracle contract address
/// @param _htlcAddr HTLC contract address
/// @param _depositOracleAddr deposit oracle address, storemanAdmin or oracle
/// @param _depositRate deposit rate value, 15000 means 150%
/// @param _depositTokenSymbol deposit token symbol, default is WAN
/// @param _tokenManagerAddress token manager contract address
function config(
address _priceOracleAddr,
address _htlcAddr,
address _fastHtlcAddr,
address _depositOracleAddr,
address _tokenManagerAddress,
uint _depositRate,
string _depositTokenSymbol
) external onlyOwner {
priceOracleAddress = _priceOracleAddr;
htlcGroupMap[_htlcAddr] = true;
htlcGroupMap[_fastHtlcAddr] = true;
depositOracleAddress = _depositOracleAddr;
depositRate = _depositRate;
depositTokenSymbol = _depositTokenSymbol;
tokenManagerAddress = _tokenManagerAddress;
}
function setDebtOracle(address oracle) external onlyOwner {
debtOracleAddress = oracle;
}
function setFastCrossMinValue(uint value) external onlyOwner {
fastCrossMinValue = value;
}
/// @notice lock quota in mint direction
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function userMintLock(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
uint mintQuota = getUserMintQuota(tokenId, storemanGroupId);
require(
mintQuota >= value,
"Quota is not enough"
);
if (!quota._active) {
quota._active = true;
storemanTokensMap[storemanGroupId][storemanTokenCountMap[storemanGroupId]] = tokenId;
storemanTokenCountMap[storemanGroupId] = storemanTokenCountMap[storemanGroupId]
.add(1);
}
quota.asset_receivable = quota.asset_receivable.add(value);
}
/// @notice lock quota in mint direction
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function smgMintLock(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
if (!quota._active) {
quota._active = true;
storemanTokensMap[storemanGroupId][storemanTokenCountMap[storemanGroupId]] = tokenId;
storemanTokenCountMap[storemanGroupId] = storemanTokenCountMap[storemanGroupId]
.add(1);
}
quota.debt_receivable = quota.debt_receivable.add(value);
}
/// @notice revoke quota in mint direction
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function userMintRevoke(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
quota.asset_receivable = quota.asset_receivable.sub(value);
}
/// @notice revoke quota in mint direction
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function smgMintRevoke(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
quota.debt_receivable = quota.debt_receivable.sub(value);
}
/// @notice redeem quota in mint direction
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function userMintRedeem(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
quota.debt_receivable = quota.debt_receivable.sub(value);
quota._debt = quota._debt.add(value);
}
/// @notice redeem quota in mint direction
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function smgMintRedeem(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
quota.asset_receivable = quota.asset_receivable.sub(value);
quota._asset = quota._asset.add(value);
}
/// @notice perform a fast crosschain mint
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function userFastMint(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc checkMinValue(tokenId, value) {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
uint mintQuota = getUserMintQuota(tokenId, storemanGroupId);
require(
mintQuota >= value,
"Quota is not enough"
);
if (!quota._active) {
quota._active = true;
storemanTokensMap[storemanGroupId][storemanTokenCountMap[storemanGroupId]] = tokenId;
storemanTokenCountMap[storemanGroupId] = storemanTokenCountMap[storemanGroupId]
.add(1);
}
quota._asset = quota._asset.add(value);
}
/// @notice perform a fast crosschain mint
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function smgFastMint(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
if (!quota._active) {
quota._active = true;
storemanTokensMap[storemanGroupId][storemanTokenCountMap[storemanGroupId]] = tokenId;
storemanTokenCountMap[storemanGroupId] = storemanTokenCountMap[storemanGroupId]
.add(1);
}
quota._debt = quota._debt.add(value);
}
/// @notice perform a fast crosschain burn
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function userFastBurn(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc checkMinValue(tokenId, value) {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
require(quota._debt.sub(quota.debt_payable) >= value, "Value is invalid");
quota._debt = quota._debt.sub(value);
}
/// @notice perform a fast crosschain burn
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function smgFastBurn(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
quota._asset = quota._asset.sub(value);
}
/// @notice lock quota in burn direction
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function userBurnLock(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
require(quota._debt.sub(quota.debt_payable) >= value, "Value is invalid");
quota.debt_payable = quota.debt_payable.add(value);
}
/// @notice lock quota in burn direction
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function smgBurnLock(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
quota.asset_payable = quota.asset_payable.add(value);
}
/// @notice revoke quota in burn direction
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function userBurnRevoke(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
quota.debt_payable = quota.debt_payable.sub(value);
}
/// @notice revoke quota in burn direction
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function smgBurnRevoke(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
quota.asset_payable = quota.asset_payable.sub(value);
}
/// @notice redeem quota in burn direction
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function userBurnRedeem(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
quota._asset = quota._asset.sub(value);
quota.asset_payable = quota.asset_payable.sub(value);
}
/// @notice redeem quota in burn direction
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
/// @param value amount of exchange token
function smgBurnRedeem(
uint tokenId,
bytes32 storemanGroupId,
uint value
) external onlyHtlc {
Quota storage quota = quotaMap[tokenId][storemanGroupId];
quota._debt = quota._debt.sub(value);
quota.debt_payable = quota.debt_payable.sub(value);
}
/// @notice source storeman group lock the debt transaction,update the detailed quota info. of the storeman group
/// @param srcStoremanGroupId PK of source storeman group
/// @param dstStoremanGroupId PK of destination storeman group
function debtLock(
bytes32 srcStoremanGroupId,
bytes32 dstStoremanGroupId
) external onlyHtlc {
uint tokenCount = storemanTokenCountMap[srcStoremanGroupId];
// TODO gas out of range
for (uint i = 0; i < tokenCount; i++) {
uint id = storemanTokensMap[srcStoremanGroupId][i];
Quota storage src = quotaMap[id][srcStoremanGroupId];
require( src.debt_receivable == uint(0) && src.debt_payable == uint(0),
"There are debt_receivable or debt_payable in src storeman"
);
if (src._debt == 0) {
continue;
}
Quota storage dst = quotaMap[id][dstStoremanGroupId];
if (!dst._active) {
dst._active = true;
storemanTokensMap[dstStoremanGroupId][storemanTokenCountMap[dstStoremanGroupId]] = id;
storemanTokenCountMap[dstStoremanGroupId] = storemanTokenCountMap[dstStoremanGroupId]
.add(1);
}
dst.debt_receivable = dst.debt_receivable.add(src._debt);
src.debt_payable = src.debt_payable.add(src._debt);
}
}
/// @notice destination storeman group redeem the debt transaction,update the detailed quota info. of the storeman group
/// @param srcStoremanGroupId PK of source storeman group
/// @param dstStoremanGroupId PK of destination storeman group
function debtRedeem(
bytes32 srcStoremanGroupId,
bytes32 dstStoremanGroupId
) external onlyHtlc {
uint tokenCount = storemanTokenCountMap[srcStoremanGroupId];
for (uint i = 0; i < tokenCount; i++) {
uint id = storemanTokensMap[srcStoremanGroupId][i];
Quota storage src = quotaMap[id][srcStoremanGroupId];
if (src._debt == 0) {
continue;
}
Quota storage dst = quotaMap[id][dstStoremanGroupId];
/// Adjust quota record
dst.debt_receivable = dst.debt_receivable.sub(src.debt_payable);
dst._debt = dst._debt.add(src._debt);
src.debt_payable = 0;
src._debt = 0;
}
}
/// @notice source storeman group revoke the debt transaction,update the detailed quota info. of the storeman group
/// @param srcStoremanGroupId PK of source storeman group
/// @param dstStoremanGroupId PK of destination storeman group
function debtRevoke(
bytes32 srcStoremanGroupId,
bytes32 dstStoremanGroupId
) external onlyHtlc {
uint tokenCount = storemanTokenCountMap[srcStoremanGroupId];
for (uint i = 0; i < tokenCount; i++) {
uint id = storemanTokensMap[srcStoremanGroupId][i];
Quota storage src = quotaMap[id][srcStoremanGroupId];
if (src._debt == 0) {
continue;
}
Quota storage dst = quotaMap[id][dstStoremanGroupId];
dst.debt_receivable = dst.debt_receivable.sub(src.debt_payable);
src.debt_payable = 0;
}
}
/// @notice source storeman group lock the debt transaction,update the detailed quota info. of the storeman group
/// @param srcStoremanGroupId PK of source storeman group
/// @param dstStoremanGroupId PK of destination storeman group
function assetLock(
bytes32 srcStoremanGroupId,
bytes32 dstStoremanGroupId
) external onlyHtlc {
uint tokenCount = storemanTokenCountMap[srcStoremanGroupId];
for (uint i = 0; i < tokenCount; i++) {
uint id = storemanTokensMap[srcStoremanGroupId][i];
Quota storage src = quotaMap[id][srcStoremanGroupId];
require( src.asset_receivable == uint(0) && src.asset_payable == uint(0),
"There are asset_receivable or asset_payable in src storeman"
);
if (src._asset == 0) {
continue;
}
Quota storage dst = quotaMap[id][dstStoremanGroupId];
if (!dst._active) {
dst._active = true;
storemanTokensMap[dstStoremanGroupId][storemanTokenCountMap[dstStoremanGroupId]] = id;
storemanTokenCountMap[dstStoremanGroupId] = storemanTokenCountMap[dstStoremanGroupId]
.add(1);
}
dst.asset_receivable = dst.asset_receivable.add(src._asset);
src.asset_payable = src.asset_payable.add(src._asset);
}
}
/// @notice destination storeman group redeem the debt transaction,update the detailed quota info. of the storeman group
/// @param srcStoremanGroupId PK of source storeman group
/// @param dstStoremanGroupId PK of destination storeman group
function assetRedeem(
bytes32 srcStoremanGroupId,
bytes32 dstStoremanGroupId
) external onlyHtlc {
uint tokenCount = storemanTokenCountMap[srcStoremanGroupId];
for (uint i = 0; i < tokenCount; i++) {
uint id = storemanTokensMap[srcStoremanGroupId][i];
Quota storage src = quotaMap[id][srcStoremanGroupId];
if (src._asset == 0) {
continue;
}
Quota storage dst = quotaMap[id][dstStoremanGroupId];
/// Adjust quota record
dst.asset_receivable = dst.asset_receivable.sub(src.asset_payable);
dst._asset = dst._asset.add(src._asset);
src.asset_payable = 0;
src._asset = 0;
}
}
/// @notice source storeman group revoke the debt transaction,update the detailed quota info. of the storeman group
/// @param srcStoremanGroupId PK of source storeman group
/// @param dstStoremanGroupId PK of destination storeman group
function assetRevoke(
bytes32 srcStoremanGroupId,
bytes32 dstStoremanGroupId
) external onlyHtlc {
uint tokenCount = storemanTokenCountMap[srcStoremanGroupId];
for (uint i = 0; i < tokenCount; i++) {
uint id = storemanTokensMap[srcStoremanGroupId][i];
Quota storage src = quotaMap[id][srcStoremanGroupId];
if (src._asset == 0) {
continue;
}
Quota storage dst = quotaMap[id][dstStoremanGroupId];
dst.asset_receivable = dst.asset_receivable.sub(src.asset_payable);
src.asset_payable = 0;
}
}
/// @notice get user mint quota of storeman, tokenId
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
function getUserMintQuota(uint tokenId, bytes32 storemanGroupId)
public
view
returns (uint)
{
string memory symbol;
uint decimals;
uint tokenPrice;
(symbol, decimals) = getTokenAncestorInfo(tokenId);
tokenPrice = getPrice(symbol);
if (tokenPrice == 0) {
return 0;
}
uint fiatQuota = getUserFiatMintQuota(storemanGroupId, symbol);
return fiatQuota.div(tokenPrice).mul(10**decimals).div(1 ether);
}
/// @notice get smg mint quota of storeman, tokenId
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
function getSmgMintQuota(uint tokenId, bytes32 storemanGroupId)
public
view
returns (uint)
{
string memory symbol;
uint decimals;
uint tokenPrice;
(symbol, decimals) = getTokenAncestorInfo(tokenId);
tokenPrice = getPrice(symbol);
if (tokenPrice == 0) {
return 0;
}
uint fiatQuota = getSmgFiatMintQuota(storemanGroupId, symbol);
return fiatQuota.div(tokenPrice).mul(10**decimals).div(1 ether);
}
/// @notice get user burn quota of storeman, tokenId
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
function getUserBurnQuota(uint tokenId, bytes32 storemanGroupId)
public
view
returns (uint burnQuota)
{
Quota storage quota = quotaMap[tokenId][storemanGroupId];
burnQuota = quota._debt.sub(quota.debt_payable);
}
/// @notice get smg burn quota of storeman, tokenId
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
function getSmgBurnQuota(uint tokenId, bytes32 storemanGroupId)
public
view
returns (uint burnQuota)
{
Quota storage quota = quotaMap[tokenId][storemanGroupId];
burnQuota = quota._asset.sub(quota.asset_payable);
}
/// @notice get asset of storeman, tokenId
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
function getAsset(uint tokenId, bytes32 storemanGroupId)
public
view
returns (uint asset, uint asset_receivable, uint asset_payable)
{
Quota storage quota = quotaMap[tokenId][storemanGroupId];
return (quota._asset, quota.asset_receivable, quota.asset_payable);
}
/// @notice get debt of storeman, tokenId
/// @param tokenId tokenPairId of crosschain
/// @param storemanGroupId PK of source storeman group
function getDebt(uint tokenId, bytes32 storemanGroupId)
public
view
returns (uint debt, uint debt_receivable, uint debt_payable)
{
Quota storage quota = quotaMap[tokenId][storemanGroupId];
return (quota._debt, quota.debt_receivable, quota.debt_payable);
}
/// @notice get debt clean state of storeman
/// @param storemanGroupId PK of source storeman group
function isDebtClean(bytes32 storemanGroupId) external view returns (bool) {
uint tokenCount = storemanTokenCountMap[storemanGroupId];
if (tokenCount == 0) {
if (debtOracleAddress == address(0)) {
return true;
} else {
IDebtOracle debtOracle = IDebtOracle(debtOracleAddress);
return debtOracle.isDebtClean(storemanGroupId);
}
}
for (uint i = 0; i < tokenCount; i++) {
uint id = storemanTokensMap[storemanGroupId][i];
Quota storage src = quotaMap[id][storemanGroupId];
if (src._debt > 0 || src.debt_payable > 0 || src.debt_receivable > 0) {
return false;
}
if (src._asset > 0 || src.asset_payable > 0 || src.asset_receivable > 0) {
return false;
}
}
return true;
}
/// @dev get minimize token count for fast cross chain
function getFastMinCount(uint tokenId) public view returns (uint, string, uint, uint, uint) {
if (fastCrossMinValue == 0) {
return (0, "", 0, 0, 0);
}
string memory symbol;
uint decimals;
(symbol, decimals) = getTokenAncestorInfo(tokenId);
uint price = getPrice(symbol);
uint count = fastCrossMinValue.mul(10**decimals).div(price);
return (fastCrossMinValue, symbol, decimals, price, count);
}
// ----------- Private Functions ---------------
/// @notice get storeman group's deposit value in USD
/// @param storemanGroupId storeman group ID
function getFiatDeposit(bytes32 storemanGroupId) private view returns (uint) {
uint deposit = getDepositAmount(storemanGroupId);
return deposit.mul(getPrice(depositTokenSymbol));
}
/// get mint quota in Fiat/USD decimals: 18
function getUserFiatMintQuota(bytes32 storemanGroupId, string rawSymbol) private view returns (uint) {
string memory symbol;
uint decimals;
uint totalTokenUsedValue = 0;
for (uint i = 0; i < storemanTokenCountMap[storemanGroupId]; i++) {
uint id = storemanTokensMap[storemanGroupId][i];
(symbol, decimals) = getTokenAncestorInfo(id);
Quota storage q = quotaMap[id][storemanGroupId];
uint tokenValue = q.asset_receivable.add(q._asset).mul(getPrice(symbol)).mul(1 ether).div(10**decimals); /// change Decimals to 18 digits
totalTokenUsedValue = totalTokenUsedValue.add(tokenValue);
}
return getLastDeposit(storemanGroupId, rawSymbol, totalTokenUsedValue);
}
function getLastDeposit(bytes32 storemanGroupId, string rawSymbol, uint totalTokenUsedValue) private view returns (uint depositValue) {
// keccak256("WAN") = 0x28ba6d5ac5913a399cc20b18c5316ad1459ae671dd23558d05943d54c61d0997
if (keccak256(rawSymbol) == bytes32(0x28ba6d5ac5913a399cc20b18c5316ad1459ae671dd23558d05943d54c61d0997)) {
depositValue = getFiatDeposit(storemanGroupId);
} else {
depositValue = getFiatDeposit(storemanGroupId).mul(DENOMINATOR).div(depositRate); // 15000 = 150%
}
if (depositValue <= totalTokenUsedValue) {
depositValue = 0;
} else {
depositValue = depositValue.sub(totalTokenUsedValue); /// decimals: 18
}
}
/// get mint quota in Fiat/USD decimals: 18
function getSmgFiatMintQuota(bytes32 storemanGroupId, string rawSymbol) private view returns (uint) {
string memory symbol;
uint decimals;
uint totalTokenUsedValue = 0;
for (uint i = 0; i < storemanTokenCountMap[storemanGroupId]; i++) {
uint id = storemanTokensMap[storemanGroupId][i];
(symbol, decimals) = getTokenAncestorInfo(id);
Quota storage q = quotaMap[id][storemanGroupId];
uint tokenValue = q.debt_receivable.add(q._debt).mul(getPrice(symbol)).mul(1 ether).div(10**decimals); /// change Decimals to 18 digits
totalTokenUsedValue = totalTokenUsedValue.add(tokenValue);
}
uint depositValue = 0;
if (keccak256(rawSymbol) == keccak256("WAN")) {
depositValue = getFiatDeposit(storemanGroupId);
} else {
depositValue = getFiatDeposit(storemanGroupId).mul(DENOMINATOR).div(depositRate); // 15000 = 150%
}
if (depositValue <= totalTokenUsedValue) {
return 0;
}
return depositValue.sub(totalTokenUsedValue); /// decimals: 18
}
function getDepositAmount(bytes32 storemanGroupId)
private
view
returns (uint)
{
_IStoremanGroup smgAdmin = _IStoremanGroup(depositOracleAddress);
return smgAdmin.getDeposit(storemanGroupId);
}
function getTokenAncestorInfo(uint tokenId)
private
view
returns (string ancestorSymbol, uint decimals)
{
_ITokenManager tokenManager = _ITokenManager(tokenManagerAddress);
(ancestorSymbol,decimals) = tokenManager.getAncestorSymbol(tokenId);
}
function stringToBytes32(string memory source) public pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function getPrice(string symbol) private view returns (uint price) {
IOracle oracle = IOracle(priceOracleAddress);
price = oracle.getValue(stringToBytes32(symbol));
}
}
| config params for owner _priceOracleAddr token price oracle contract address _htlcAddr HTLC contract address _depositOracleAddr deposit oracle address, storemanAdmin or oracle _depositRate deposit rate value, 15000 means 150% _depositTokenSymbol deposit token symbol, default is WAN _tokenManagerAddress token manager contract address | function config(
address _priceOracleAddr,
address _htlcAddr,
address _fastHtlcAddr,
address _depositOracleAddr,
address _tokenManagerAddress,
uint _depositRate,
string _depositTokenSymbol
) external onlyOwner {
priceOracleAddress = _priceOracleAddr;
htlcGroupMap[_htlcAddr] = true;
htlcGroupMap[_fastHtlcAddr] = true;
depositOracleAddress = _depositOracleAddr;
depositRate = _depositRate;
depositTokenSymbol = _depositTokenSymbol;
tokenManagerAddress = _tokenManagerAddress;
}
| 7,274,955 |
Subsets and Splits